diff --git a/.gitattributes b/.gitattributes index 4c0faf4d254244acba928944755d2ce9d0fe367e..716c0eb52f501df5216129cd2bac770f4a82ba1b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -37,3 +37,13 @@ python_embeded/python.exe filter=lfs diff=lfs merge=lfs -text python_embeded/vcruntime140.dll filter=lfs diff=lfs merge=lfs -text python_embeded/libssl-3.dll filter=lfs diff=lfs merge=lfs -text python_embeded/sqlite3.dll filter=lfs diff=lfs merge=lfs -text +python_embeded/pythonw.exe filter=lfs diff=lfs merge=lfs -text +python_embeded/python.cat filter=lfs diff=lfs merge=lfs -text +python_embeded/libcrypto-3.dll filter=lfs diff=lfs merge=lfs -text +python_embeded/python312.dll filter=lfs diff=lfs merge=lfs -text +python_embeded/Scripts/accelerate-estimate-memory.exe filter=lfs diff=lfs merge=lfs -text +python_embeded/Scripts/accelerate-config.exe filter=lfs diff=lfs merge=lfs -text +python_embeded/Scripts/coloredlogs.exe filter=lfs diff=lfs merge=lfs -text +python_embeded/Scripts/chardetect.exe filter=lfs diff=lfs merge=lfs -text +python_embeded/Scripts/alembic.exe filter=lfs diff=lfs merge=lfs -text +python_embeded/Scripts/dotenv.exe filter=lfs diff=lfs merge=lfs -text diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/AUTHORS b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..45b14c961cdbbebb245ad77d0cd0c8b368bc9aca --- /dev/null +++ b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/AUTHORS @@ -0,0 +1,59 @@ +GitPython was originally written by Michael Trier. +GitPython 0.2 was partially (re)written by Sebastian Thiel, based on 0.1.6 and git-dulwich. + +Contributors are: + +-Michael Trier +-Alan Briolat +-Florian Apolloner +-David Aguilar +-Jelmer Vernooij +-Steve Frécinaux +-Kai Lautaportti +-Paul Sowden +-Sebastian Thiel +-Jonathan Chu +-Vincent Driessen +-Phil Elson +-Bernard `Guyzmo` Pratz +-Timothy B. Hartman +-Konstantin Popov +-Peter Jones +-Anson Mansfield +-Ken Odegard +-Alexis Horgix Chotard +-Piotr Babij +-Mikuláš Poul +-Charles Bouchard-Légaré +-Yaroslav Halchenko +-Tim Swast +-William Luc Ritchie +-David Host +-A. Jesse Jiryu Davis +-Steven Whitman +-Stefan Stancu +-César Izurieta +-Arthur Milchior +-Anil Khatri +-JJ Graham +-Ben Thayer +-Dries Kennes +-Pratik Anurag +-Harmon +-Liam Beguin +-Ram Rachum +-Alba Mendez +-Robert Westman +-Hugo van Kemenade +-Hiroki Tokunaga +-Julien Mauroy +-Patrick Gerard +-Luke Twist +-Joseph Hale +-Santos Gallegos +-Wenhan Zhu +-Eliah Kagan +-Ethan Lin +-Jonas Scharpf + +Portions derived from other open source works and are clearly marked. diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/INSTALLER b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/LICENSE b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ba8a219fe1f27c10b50df8cd4f26c0ab833bbbc8 --- /dev/null +++ b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/LICENSE @@ -0,0 +1,29 @@ +Copyright (C) 2008, 2009 Michael Trier and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +* Neither the name of the GitPython project nor the names of +its contributors may be used to endorse or promote products derived +from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/METADATA b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..2589bfb3dee272a84f3b80aedaedf9a80c475499 --- /dev/null +++ b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/METADATA @@ -0,0 +1,295 @@ +Metadata-Version: 2.1 +Name: GitPython +Version: 3.1.44 +Summary: GitPython is a Python library used to interact with Git repositories +Home-page: https://github.com/gitpython-developers/GitPython +Author: Sebastian Thiel, Michael Trier +Author-email: byronimo@gmail.com, mtrier@gmail.com +License: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Typing :: Typed +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS +Requires-Dist: gitdb<5,>=4.0.1 +Requires-Dist: typing-extensions>=3.7.4.3; python_version < "3.8" +Provides-Extra: test +Requires-Dist: coverage[toml]; extra == "test" +Requires-Dist: ddt!=1.4.3,>=1.1.1; extra == "test" +Requires-Dist: mock; python_version < "3.8" and extra == "test" +Requires-Dist: mypy; extra == "test" +Requires-Dist: pre-commit; extra == "test" +Requires-Dist: pytest>=7.3.1; extra == "test" +Requires-Dist: pytest-cov; extra == "test" +Requires-Dist: pytest-instafail; extra == "test" +Requires-Dist: pytest-mock; extra == "test" +Requires-Dist: pytest-sugar; extra == "test" +Requires-Dist: typing-extensions; python_version < "3.11" and extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx<7.2,>=7.1.2; extra == "doc" +Requires-Dist: sphinx_rtd_theme; extra == "doc" +Requires-Dist: sphinx-autodoc-typehints; extra == "doc" + +![Python package](https://github.com/gitpython-developers/GitPython/workflows/Python%20package/badge.svg) +[![Documentation Status](https://readthedocs.org/projects/gitpython/badge/?version=stable)](https://readthedocs.org/projects/gitpython/?badge=stable) +[![Packaging status](https://repology.org/badge/tiny-repos/python:gitpython.svg)](https://repology.org/metapackage/python:gitpython/versions) + +## [Gitoxide](https://github.com/Byron/gitoxide): A peek into the future… + +I started working on GitPython in 2009, back in the days when Python was 'my thing' and I had great plans with it. +Of course, back in the days, I didn't really know what I was doing and this shows in many places. Somewhat similar to +Python this happens to be 'good enough', but at the same time is deeply flawed and broken beyond repair. + +By now, GitPython is widely used and I am sure there is a good reason for that, it's something to be proud of and happy about. +The community is maintaining the software and is keeping it relevant for which I am absolutely grateful. For the time to come I am happy to continue maintaining GitPython, remaining hopeful that one day it won't be needed anymore. + +More than 15 years after my first meeting with 'git' I am still in excited about it, and am happy to finally have the tools and +probably the skills to scratch that itch of mine: implement `git` in a way that makes tool creation a piece of cake for most. + +If you like the idea and want to learn more, please head over to [gitoxide](https://github.com/Byron/gitoxide), an +implementation of 'git' in [Rust](https://www.rust-lang.org). + +*(Please note that `gitoxide` is not currently available for use in Python, and that Rust is required.)* + +## GitPython + +GitPython is a python library used to interact with git repositories, high-level like git-porcelain, +or low-level like git-plumbing. + +It provides abstractions of git objects for easy access of repository data often backed by calling the `git` +command-line program. + +### DEVELOPMENT STATUS + +This project is in **maintenance mode**, which means that + +- …there will be no feature development, unless these are contributed +- …there will be no bug fixes, unless they are relevant to the safety of users, or contributed +- …issues will be responded to with waiting times of up to a month + +The project is open to contributions of all kinds, as well as new maintainers. + +### REQUIREMENTS + +GitPython needs the `git` executable to be installed on the system and available in your +`PATH` for most operations. If it is not in your `PATH`, you can help GitPython find it +by setting the `GIT_PYTHON_GIT_EXECUTABLE=` environment variable. + +- Git (1.7.x or newer) +- Python >= 3.7 + +The list of dependencies are listed in `./requirements.txt` and `./test-requirements.txt`. +The installer takes care of installing them for you. + +### INSTALL + +GitPython and its required package dependencies can be installed in any of the following ways, all of which should typically be done in a [virtual environment](https://docs.python.org/3/tutorial/venv.html). + +#### From PyPI + +To obtain and install a copy [from PyPI](https://pypi.org/project/GitPython/), run: + +```sh +pip install GitPython +``` + +(A distribution package can also be downloaded for manual installation at [the PyPI page](https://pypi.org/project/GitPython/).) + +#### From downloaded source code + +If you have downloaded the source code, run this from inside the unpacked `GitPython` directory: + +```sh +pip install . +``` + +#### By cloning the source code repository + +To clone the [the GitHub repository](https://github.com/gitpython-developers/GitPython) from source to work on the code, you can do it like so: + +```sh +git clone https://github.com/gitpython-developers/GitPython +cd GitPython +./init-tests-after-clone.sh +``` + +On Windows, `./init-tests-after-clone.sh` can be run in a Git Bash shell. + +If you are cloning [your own fork](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/about-forks), then replace the above `git clone` command with one that gives the URL of your fork. Or use this [`gh`](https://cli.github.com/) command (assuming you have `gh` and your fork is called `GitPython`): + +```sh +gh repo clone GitPython +``` + +Having cloned the repo, create and activate your [virtual environment](https://docs.python.org/3/tutorial/venv.html). + +Then make an [editable install](https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs): + +```sh +pip install -e ".[test]" +``` + +In the less common case that you do not want to install test dependencies, `pip install -e .` can be used instead. + +#### With editable *dependencies* (not preferred, and rarely needed) + +In rare cases, you may want to work on GitPython and one or both of its [gitdb](https://github.com/gitpython-developers/gitdb) and [smmap](https://github.com/gitpython-developers/smmap) dependencies at the same time, with changes in your local working copy of gitdb or smmap immediately reflected in the behavior of your local working copy of GitPython. This can be done by making editable installations of those dependencies in the same virtual environment where you install GitPython. + +If you want to do that *and* you want the versions in GitPython's git submodules to be used, then pass `-e git/ext/gitdb` and/or `-e git/ext/gitdb/gitdb/ext/smmap` to `pip install`. This can be done in any order, and in separate `pip install` commands or the same one, so long as `-e` appears before *each* path. For example, you can install GitPython, gitdb, and smmap editably in the currently active virtual environment this way: + +```sh +pip install -e ".[test]" -e git/ext/gitdb -e git/ext/gitdb/gitdb/ext/smmap +``` + +The submodules must have been cloned for that to work, but that will already be the case if you have run `./init-tests-after-clone.sh`. You can use `pip list` to check which packages are installed editably and which are installed normally. + +To reiterate, this approach should only rarely be used. For most development it is preferable to allow the gitdb and smmap dependencices to be retrieved automatically from PyPI in their latest stable packaged versions. + +### Limitations + +#### Leakage of System Resources + +GitPython is not suited for long-running processes (like daemons) as it tends to +leak system resources. It was written in a time where destructors (as implemented +in the `__del__` method) still ran deterministically. + +In case you still want to use it in such a context, you will want to search the +codebase for `__del__` implementations and call these yourself when you see fit. + +Another way assure proper cleanup of resources is to factor out GitPython into a +separate process which can be dropped periodically. + +#### Windows support + +See [Issue #525](https://github.com/gitpython-developers/GitPython/issues/525). + +### RUNNING TESTS + +_Important_: Right after cloning this repository, please be sure to have executed +the `./init-tests-after-clone.sh` script in the repository root. Otherwise +you will encounter test failures. + +#### Install test dependencies + +Ensure testing libraries are installed. This is taken care of already if you installed with: + +```sh +pip install -e ".[test]" +``` + +If you had installed with a command like `pip install -e .` instead, you can still run +the above command to add the testing dependencies. + +#### Test commands + +To test, run: + +```sh +pytest +``` + +To lint, and apply some linting fixes as well as automatic code formatting, run: + +```sh +pre-commit run --all-files +``` + +This includes the linting and autoformatting done by Ruff, as well as some other checks. + +To typecheck, run: + +```sh +mypy +``` + +#### CI (and tox) + +Style and formatting checks, and running tests on all the different supported Python versions, will be performed: + +- Upon submitting a pull request. +- On each push, *if* you have a fork with GitHub Actions enabled. +- Locally, if you run [`tox`](https://tox.wiki/) (this skips any Python versions you don't have installed). + +#### Configuration files + +Specific tools are all configured in the `./pyproject.toml` file: + +- `pytest` (test runner) +- `coverage.py` (code coverage) +- `ruff` (linter and formatter) +- `mypy` (type checker) + +Orchestration tools: + +- Configuration for `pre-commit` is in the `./.pre-commit-config.yaml` file. +- Configuration for `tox` is in `./tox.ini`. +- Configuration for GitHub Actions (CI) is in files inside `./.github/workflows/`. + +### Contributions + +Please have a look at the [contributions file][contributing]. + +### INFRASTRUCTURE + +- [User Documentation](http://gitpython.readthedocs.org) +- [Questions and Answers](http://stackexchange.com/filters/167317/gitpython) +- Please post on Stack Overflow and use the `gitpython` tag +- [Issue Tracker](https://github.com/gitpython-developers/GitPython/issues) + - Post reproducible bugs and feature requests as a new issue. + Please be sure to provide the following information if posting bugs: + - GitPython version (e.g. `import git; git.__version__`) + - Python version (e.g. `python --version`) + - The encountered stack-trace, if applicable + - Enough information to allow reproducing the issue + +### How to make a new release + +1. Update/verify the **version** in the `VERSION` file. +2. Update/verify that the `doc/source/changes.rst` changelog file was updated. It should include a link to the forthcoming release page: `https://github.com/gitpython-developers/GitPython/releases/tag/` +3. Commit everything. +4. Run `git tag -s ` to tag the version in Git. +5. _Optionally_ create and activate a [virtual environment](https://packaging.python.org/en/latest/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment). (Then the next step can install `build` and `twine`.) +6. Run `make release`. +7. Go to [GitHub Releases](https://github.com/gitpython-developers/GitPython/releases) and publish a new one with the recently pushed tag. Generate the changelog. + +### Projects using GitPython + +- [PyDriller](https://github.com/ishepard/pydriller) +- [Kivy Designer](https://github.com/kivy/kivy-designer) +- [Prowl](https://github.com/nettitude/Prowl) +- [Python Taint](https://github.com/python-security/pyt) +- [Buster](https://github.com/axitkhurana/buster) +- [git-ftp](https://github.com/ezyang/git-ftp) +- [Git-Pandas](https://github.com/wdm0006/git-pandas) +- [PyGitUp](https://github.com/msiemens/PyGitUp) +- [PyJFuzz](https://github.com/mseclab/PyJFuzz) +- [Loki](https://github.com/Neo23x0/Loki) +- [Omniwallet](https://github.com/OmniLayer/omniwallet) +- [GitViper](https://github.com/BeayemX/GitViper) +- [Git Gud](https://github.com/bthayer2365/git-gud) + +### LICENSE + +[3-Clause BSD License](https://opensource.org/license/bsd-3-clause/), also known as the New BSD License. See the [LICENSE file][license]. + +One file exclusively used for fuzz testing is subject to [a separate license, detailed here](./fuzzing/README.md#license). +This file is not included in the wheel or sdist packages published by the maintainers of GitPython. + +[contributing]: https://github.com/gitpython-developers/GitPython/blob/main/CONTRIBUTING.md +[license]: https://github.com/gitpython-developers/GitPython/blob/main/LICENSE diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/RECORD b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b8368868dc6dd2941841ff9a5d2d85687330edcc --- /dev/null +++ b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/RECORD @@ -0,0 +1,83 @@ +GitPython-3.1.44.dist-info/AUTHORS,sha256=tZ9LuyBks2V2HKTPK7kCmtd9Guu_LyU1oZHvU0NiAok,2334 +GitPython-3.1.44.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +GitPython-3.1.44.dist-info/LICENSE,sha256=hvyUwyGpr7wRUUcTURuv3tIl8lEA3MD3NQ6CvCMbi-s,1503 +GitPython-3.1.44.dist-info/METADATA,sha256=0O_Fr2Y7A-DlPYhlbSxGjblBC2mWkw3USNUhyL80Ip8,13245 +GitPython-3.1.44.dist-info/RECORD,, +GitPython-3.1.44.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +GitPython-3.1.44.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +GitPython-3.1.44.dist-info/top_level.txt,sha256=0hzDuIp8obv624V3GmbqsagBWkk8ohtGU-Bc1PmTT0o,4 +git/__init__.py,sha256=nkQImgv-bWdiZOFDjzN-gbt93FoRHD0nY6_t9LQxy4Y,8899 +git/__pycache__/__init__.cpython-312.pyc,, +git/__pycache__/cmd.cpython-312.pyc,, +git/__pycache__/compat.cpython-312.pyc,, +git/__pycache__/config.cpython-312.pyc,, +git/__pycache__/db.cpython-312.pyc,, +git/__pycache__/diff.cpython-312.pyc,, +git/__pycache__/exc.cpython-312.pyc,, +git/__pycache__/remote.cpython-312.pyc,, +git/__pycache__/types.cpython-312.pyc,, +git/__pycache__/util.cpython-312.pyc,, +git/cmd.py,sha256=QwiaBy0mFbi9xjRKhRgUVK-_-K6xVdFqh9l0cxPqPSc,67724 +git/compat.py,sha256=y1E6y6O2q5r8clSlr8ZNmuIWG9nmHuehQEsVsmBffs8,4526 +git/config.py,sha256=vTUlK6d8ORqFqjOv4Vbq_Hm-5mp-jOAt1dkq0IdzJ3U,34933 +git/db.py,sha256=vIW9uWSbqu99zbuU2ZDmOhVOv1UPTmxrnqiCtRHCfjE,2368 +git/diff.py,sha256=wmpMCIdMiVOqreGVPOGYyO4gFboGOAicyrvvI7PPjEg,27095 +git/exc.py,sha256=Gc7g1pHpn8OmTse30NHmJVsBJ2CYH8LxaR8y8UA3lIM,7119 +git/index/__init__.py,sha256=i-Nqb8Lufp9aFbmxpQBORmmQnjEVVM1Pn58fsQkyGgQ,406 +git/index/__pycache__/__init__.cpython-312.pyc,, +git/index/__pycache__/base.cpython-312.pyc,, +git/index/__pycache__/fun.cpython-312.pyc,, +git/index/__pycache__/typ.cpython-312.pyc,, +git/index/__pycache__/util.cpython-312.pyc,, +git/index/base.py,sha256=nDD7XVLNbgBKpJMrrTVyHBy6NVLWgDkk7oUw6ZOegPc,60808 +git/index/fun.py,sha256=37cA3DBC9vpAnSVu5TGA072SnoF5XZOkOukExwlejHs,16736 +git/index/typ.py,sha256=uuKNwitUw83FhVaLSwo4pY7PHDQudtZTLJrLGym4jcI,6570 +git/index/util.py,sha256=fULi7GPG-MvprKrRCD5c15GNdzku_1E38We0d97WB3A,3659 +git/objects/__init__.py,sha256=O6ZL_olX7e5-8iIbKviRPkVSJxN37WA-EC0q9d48U5Y,637 +git/objects/__pycache__/__init__.cpython-312.pyc,, +git/objects/__pycache__/base.cpython-312.pyc,, +git/objects/__pycache__/blob.cpython-312.pyc,, +git/objects/__pycache__/commit.cpython-312.pyc,, +git/objects/__pycache__/fun.cpython-312.pyc,, +git/objects/__pycache__/tag.cpython-312.pyc,, +git/objects/__pycache__/tree.cpython-312.pyc,, +git/objects/__pycache__/util.cpython-312.pyc,, +git/objects/base.py,sha256=0dqNkSRVH0mk0-7ZKIkGBK7iNYrzLTVxwQFUd6CagsE,10277 +git/objects/blob.py,sha256=zwwq0KfOMYeP5J2tW5CQatoLyeqFRlfkxP1Vwx1h07s,1215 +git/objects/commit.py,sha256=GH1_83C9t7RGTukwozTHDgvxYQPRjTHhPDkXJyBbJyo,30553 +git/objects/fun.py,sha256=B4jCqhAjm6Hl79GK58FPzW1H9K6Wc7Tx0rssyWmAcEE,8935 +git/objects/submodule/__init__.py,sha256=6xySp767LVz3UylWgUalntS_nGXRuVzXxDuFAv_Wc2c,303 +git/objects/submodule/__pycache__/__init__.cpython-312.pyc,, +git/objects/submodule/__pycache__/base.cpython-312.pyc,, +git/objects/submodule/__pycache__/root.cpython-312.pyc,, +git/objects/submodule/__pycache__/util.cpython-312.pyc,, +git/objects/submodule/base.py,sha256=MQ-2xV8JznGwy2hLQv1aeQNgAkhBhgc5tdtClFL3DmE,63901 +git/objects/submodule/root.py,sha256=5eTtYNHasqdPq6q0oDCPr7IaO6uAHL3b4DxMoiO2LhE,20246 +git/objects/submodule/util.py,sha256=sQqAYaiSJdFkZa9NlAuK_wTsMNiS-kkQnQjvIoJtc_o,3509 +git/objects/tag.py,sha256=jAGESnpmTEv-dLakPzheT5ILZFFArcItnXYqfxfDrgc,4441 +git/objects/tree.py,sha256=jJH888SHiP4dGzE-ra1yenQOyya_0C_MkHr06c1gHpM,13849 +git/objects/util.py,sha256=Nlza4zLgdPmr_Yasyvvs6c1rKtW_wMxI6wDmQpQ3ufw,23846 +git/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +git/refs/__init__.py,sha256=DWlJNnsx-4jM_E-VycbP-FZUdn6iWhjnH_uZ_pZXBro,509 +git/refs/__pycache__/__init__.cpython-312.pyc,, +git/refs/__pycache__/head.cpython-312.pyc,, +git/refs/__pycache__/log.cpython-312.pyc,, +git/refs/__pycache__/reference.cpython-312.pyc,, +git/refs/__pycache__/remote.cpython-312.pyc,, +git/refs/__pycache__/symbolic.cpython-312.pyc,, +git/refs/__pycache__/tag.cpython-312.pyc,, +git/refs/head.py,sha256=SGa3N301HfAi79X6UR5Mcg7mO9TnCH3Bk549kHlJVaQ,10513 +git/refs/log.py,sha256=kXiuAgTo1DIuM_BfbDUk9gQ0YO-mutIMVdHv1_ES90o,12493 +git/refs/reference.py,sha256=l6mhF4YLSEwtjz6b9PpOQH-fkng7EYWMaJhkjn-2jXA,5630 +git/refs/remote.py,sha256=WwqV9T7BbYf3F_WZNUQivu9xktIIKGklCjDpwQrhD-A,2806 +git/refs/symbolic.py,sha256=c8zOwaqzcg-J-rGrpuWdvh8zwMvSUqAHghd4vJoYG_s,34552 +git/refs/tag.py,sha256=kgzV2vhpL4FD2TqHb0BJuMRAHgAvJF-TcoyWlaB-djQ,5010 +git/remote.py,sha256=pYn9dAlz-QwvNMWXD1M57pMPQitthOM86qTRK_cpTqU,46786 +git/repo/__init__.py,sha256=CILSVH36fX_WxVFSjD9o1WF5LgsNedPiJvSngKZqfVU,210 +git/repo/__pycache__/__init__.cpython-312.pyc,, +git/repo/__pycache__/base.cpython-312.pyc,, +git/repo/__pycache__/fun.cpython-312.pyc,, +git/repo/base.py,sha256=0GU6nKNdT8SYjDI5Y5DeZ1zCEX3tHeq1VW2MSpne05g,59891 +git/repo/fun.py,sha256=HSGC0-rqeKKx9fDg7JyQyMZgIwUWn-FnSZR_gRGpG-E,13573 +git/types.py,sha256=MQzIDEOnoueXGsAJF_0MgUc_osH7Eu0Sw3DQofYzCVE,10272 +git/util.py,sha256=2uAv34zZ_827-zJ3-D5ACrVH-4Q4EO_KLUTH23zi2AI,43770 diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/REQUESTED b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/WHEEL b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/top_level.txt b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..5664e303b5dc2e9ef8e14a0845d9486ec1920afd --- /dev/null +++ b/python_embeded/Lib/site-packages/GitPython-3.1.44.dist-info/top_level.txt @@ -0,0 +1 @@ +git diff --git a/python_embeded/Lib/site-packages/github/Hook.py b/python_embeded/Lib/site-packages/github/Hook.py new file mode 100644 index 0000000000000000000000000000000000000000..289eec0825f695fca981bad8f94600975a19cc81 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Hook.py @@ -0,0 +1,226 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Wan Liuyang # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.HookResponse +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_optional, is_optional_list + + +class Hook(CompletableGithubObject): + """ + This class represents Hooks. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#webhooks + + The OpenAPI schema can be found at + - /components/schemas/hook + + """ + + def _initAttributes(self) -> None: + self._active: Attribute[bool] = NotSet + self._config: Attribute[dict] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._deliveries_url: Attribute[str] = NotSet + self._events: Attribute[list[str]] = NotSet + self._id: Attribute[int] = NotSet + self._last_response: Attribute[github.HookResponse.HookResponse] = NotSet + self._name: Attribute[str] = NotSet + self._ping_url: Attribute[str] = NotSet + self._test_url: Attribute[str] = NotSet + self._type: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "url": self._url.value}) + + @property + def active(self) -> bool: + self._completeIfNotSet(self._active) + return self._active.value + + @property + def config(self) -> dict: + self._completeIfNotSet(self._config) + return self._config.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def deliveries_url(self) -> str: + self._completeIfNotSet(self._deliveries_url) + return self._deliveries_url.value + + @property + def events(self) -> list[str]: + self._completeIfNotSet(self._events) + return self._events.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def last_response(self) -> github.HookResponse.HookResponse: + self._completeIfNotSet(self._last_response) + return self._last_response.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def ping_url(self) -> str: + self._completeIfNotSet(self._ping_url) + return self._ping_url.value + + @property + def test_url(self) -> str: + self._completeIfNotSet(self._test_url) + return self._test_url.value + + @property + def type(self) -> str: + self._completeIfNotSet(self._type) + return self._type.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def delete(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/hooks/{id} `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def edit( + self, + name: str, + config: dict, + events: Opt[list[str]] = NotSet, + add_events: Opt[list[str]] = NotSet, + remove_events: Opt[list[str]] = NotSet, + active: Opt[bool] = NotSet, + ) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/hooks/{id} `_ + """ + assert isinstance(name, str), name + assert isinstance(config, dict), config + assert is_optional_list(events, str), events + assert is_optional_list(add_events, str), add_events + assert is_optional_list(remove_events, str), remove_events + assert is_optional(active, bool), active + post_parameters = NotSet.remove_unset_items( + { + "name": name, + "config": config, + "events": events, + "add_events": add_events, + "remove_events": remove_events, + "active": active, + } + ) + + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def test(self) -> None: + """ + :calls: `POST /repos/{owner}/{repo}/hooks/{id}/tests `_ + """ + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/tests") + + def ping(self) -> None: + """ + :calls: `POST /repos/{owner}/{repo}/hooks/{id}/pings `_ + """ + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/pings") + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "active" in attributes: # pragma no branch + self._active = self._makeBoolAttribute(attributes["active"]) + if "config" in attributes: # pragma no branch + self._config = self._makeDictAttribute(attributes["config"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "deliveries_url" in attributes: # pragma no branch + self._deliveries_url = self._makeStringAttribute(attributes["deliveries_url"]) + if "events" in attributes: # pragma no branch + self._events = self._makeListOfStringsAttribute(attributes["events"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "last_response" in attributes: # pragma no branch + self._last_response = self._makeClassAttribute( + github.HookResponse.HookResponse, attributes["last_response"] + ) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "ping_url" in attributes: # pragma no branch + self._ping_url = self._makeStringAttribute(attributes["ping_url"]) + if "test_url" in attributes: # pragma no branch + self._test_url = self._makeStringAttribute(attributes["test_url"]) + if "type" in attributes: # pragma no branch + self._type = self._makeStringAttribute(attributes["type"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/HookResponse.py b/python_embeded/Lib/site-packages/github/HookResponse.py new file mode 100644 index 0000000000000000000000000000000000000000..4c117477d24b16fcbffc15ab94959c93b9b17c1c --- /dev/null +++ b/python_embeded/Lib/site-packages/github/HookResponse.py @@ -0,0 +1,79 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class HookResponse(NonCompletableGithubObject): + """ + This class represents HookResponses. + + The OpenAPI schema can be found at + - /components/schemas/hook-response + + """ + + def _initAttributes(self) -> None: + self._code: Attribute[int] = NotSet + self._message: Attribute[str] = NotSet + self._status: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"status": self._status.value}) + + @property + def code(self) -> int: + return self._code.value + + @property + def message(self) -> str: + return self._message.value + + @property + def status(self) -> str: + return self._status.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "code" in attributes: # pragma no branch + self._code = self._makeIntAttribute(attributes["code"]) + if "message" in attributes: # pragma no branch + self._message = self._makeStringAttribute(attributes["message"]) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) diff --git a/python_embeded/Lib/site-packages/github/InputFileContent.py b/python_embeded/Lib/site-packages/github/InputFileContent.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d3692340ed188af64ac15ee9a07bca93ed2014 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/InputFileContent.py @@ -0,0 +1,62 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import NotSet, Opt, is_defined, is_optional + + +class InputFileContent: + """ + This class represents InputFileContents. + """ + + def __init__(self, content: str, new_name: Opt[str] = NotSet): + assert isinstance(content, str), content + assert is_optional(new_name, str), new_name + self.__newName: Opt[str] = new_name + self.__content: str = content + + @property + def _identity(self) -> dict[str, str]: + identity: dict[str, Any] = { + "content": self.__content, + } + if is_defined(self.__newName): + identity["filename"] = self.__newName + return identity diff --git a/python_embeded/Lib/site-packages/github/InputGitAuthor.py b/python_embeded/Lib/site-packages/github/InputGitAuthor.py new file mode 100644 index 0000000000000000000000000000000000000000..9b9da24d3c82b51a9ebbbb1178b56c567eff684a --- /dev/null +++ b/python_embeded/Lib/site-packages/github/InputGitAuthor.py @@ -0,0 +1,70 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Nic Dahlquist # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import NotSet, Opt, is_defined, is_optional + + +class InputGitAuthor: + """ + This class represents InputGitAuthors. + """ + + def __init__(self, name: str, email: str, date: Opt[str] = NotSet): + assert isinstance(name, str), name + assert isinstance(email, str), email + assert is_optional(date, str), date # @todo Datetime? + + self.__name: str = name + self.__email: str = email + self.__date: Opt[str] = date + + def __repr__(self) -> str: + return f'InputGitAuthor(name="{self.__name}")' + + @property + def _identity(self) -> dict[str, str]: + identity: dict[str, Any] = { + "name": self.__name, + "email": self.__email, + } + if is_defined(self.__date): + identity["date"] = self.__date + return identity diff --git a/python_embeded/Lib/site-packages/github/InputGitTreeElement.py b/python_embeded/Lib/site-packages/github/InputGitTreeElement.py new file mode 100644 index 0000000000000000000000000000000000000000..8a05b5bf7c775a44555115c7258841ddc977c053 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/InputGitTreeElement.py @@ -0,0 +1,78 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import NotSet, Opt, is_defined, is_optional + + +class InputGitTreeElement: + """ + This class represents InputGitTreeElements. + """ + + def __init__( + self, + path: str, + mode: str, + type: str, + content: Opt[str] = NotSet, + sha: Opt[str | None] = NotSet, + ): + assert isinstance(path, str), path + assert isinstance(mode, str), mode + assert isinstance(type, str), type + assert is_optional(content, str), content + assert sha is None or is_optional(sha, str), sha + self.__path = path + self.__mode = mode + self.__type = type + self.__content = content + self.__sha: Opt[str] | None = sha + + @property + def _identity(self) -> dict[str, Any]: + identity: dict[str, Any] = { + "path": self.__path, + "mode": self.__mode, + "type": self.__type, + } + if is_defined(self.__sha): + identity["sha"] = self.__sha + if is_defined(self.__content): + identity["content"] = self.__content + return identity diff --git a/python_embeded/Lib/site-packages/github/Installation.py b/python_embeded/Lib/site-packages/github/Installation.py new file mode 100644 index 0000000000000000000000000000000000000000..caafbc2bace54d5251065a8761b5e19fd576d17c --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Installation.py @@ -0,0 +1,280 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Jannis Gebauer # +# Copyright 2017 Simon # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Rigas Papathanasopoulos # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Min RK # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.Authorization +import github.Event +import github.Gist +import github.GithubObject +import github.Issue +import github.NamedUser +import github.Notification +import github.Organization +import github.PaginatedList +import github.Plan +import github.Repository +import github.UserKey +from github import Consts +from github.Auth import AppAuth +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet +from github.PaginatedList import PaginatedList +from github.Requester import Requester + +if TYPE_CHECKING: + from github.MainClass import Github + from github.NamedUser import NamedUser + from github.Organization import Organization + +INTEGRATION_PREVIEW_HEADERS = {"Accept": Consts.mediaTypeIntegrationPreview} + + +class Installation(NonCompletableGithubObject): + """ + This class represents Installations. + + The reference can be found here + https://docs.github.com/en/rest/reference/apps#installations + + The OpenAPI schema can be found at + - /components/schemas/installation + + """ + + def _initAttributes(self) -> None: + self._access_tokens_url: Attribute[str] = NotSet + self._account: Attribute[NamedUser | Organization] = NotSet + self._app_id: Attribute[int] = NotSet + self._app_slug: Attribute[str] = NotSet + self._contact_email: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._events: Attribute[list[str]] = NotSet + self._has_multiple_single_files: Attribute[bool] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._permissions: Attribute[dict[str, Any]] = NotSet + self._repositories_url: Attribute[str] = NotSet + self._repository_selection: Attribute[str] = NotSet + self._single_file_name: Attribute[str] = NotSet + self._single_file_paths: Attribute[list[str]] = NotSet + self._suspended_at: Attribute[datetime] = NotSet + self._suspended_by: Attribute[NamedUser] = NotSet + self._target_id: Attribute[int] = NotSet + self._target_type: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + + def __init__( + self, + requester: Requester, + headers: dict[str, str | int], + attributes: Any, + ) -> None: + super().__init__(requester, headers, attributes) + + auth = self._requester.auth if self._requester is not None else None + # Usually, an Installation is created from a Requester with App authentication + if isinstance(auth, AppAuth): + # But the installation has to authenticate as an installation (e.g. for get_repos()) + auth = auth.get_installation_auth(self.id, requester=self._requester) + self._requester = self._requester.withAuth(auth) + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value}) + + @property + def access_tokens_url(self) -> str: + return self._access_tokens_url.value + + @property + def account(self) -> NamedUser | Organization: + return self._account.value + + @property + def app_id(self) -> int: + return self._app_id.value + + @property + def app_slug(self) -> str: + return self._app_slug.value + + @property + def contact_email(self) -> str: + return self._contact_email.value + + @property + def created_at(self) -> datetime: + return self._created_at.value + + @property + def events(self) -> list[str]: + return self._events.value + + @property + def has_multiple_single_files(self) -> bool: + return self._has_multiple_single_files.value + + @property + def html_url(self) -> str: + return self._html_url.value + + @property + def id(self) -> int: + return self._id.value + + @property + def permissions(self) -> dict[str, Any]: + return self._permissions.value + + @property + def repositories_url(self) -> str: + return self._repositories_url.value + + @property + def repository_selection(self) -> str: + return self._repository_selection.value + + @property + def requester(self) -> Requester: + """ + Return my Requester object. + + For example, to make requests to API endpoints not yet supported by PyGitHub. + + """ + return self._requester + + @property + def single_file_name(self) -> str: + return self._single_file_name.value + + @property + def single_file_paths(self) -> list[str]: + return self._single_file_paths.value + + @property + def suspended_at(self) -> datetime: + return self._suspended_at.value + + @property + def suspended_by(self) -> NamedUser: + return self._suspended_by.value + + @property + def target_id(self) -> int: + return self._target_id.value + + @property + def target_type(self) -> str: + return self._target_type.value + + @property + def updated_at(self) -> datetime: + return self._updated_at.value + + def get_github_for_installation(self) -> Github: + return github.Github(**self._requester.kwargs) + + def get_repos(self) -> PaginatedList[github.Repository.Repository]: + """ + :calls: `GET /installation/repositories `_ + """ + url_parameters: dict[str, Any] = {} + + return PaginatedList( + contentClass=github.Repository.Repository, + requester=self._requester, + firstUrl="/installation/repositories", + firstParams=url_parameters, + headers=INTEGRATION_PREVIEW_HEADERS, + list_item="repositories", + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "access_tokens_url" in attributes: # pragma no branch + self._access_tokens_url = self._makeStringAttribute(attributes["access_tokens_url"]) + if "account" in attributes and "target_type" in attributes: # pragma no branch + target_type = attributes["target_type"] + if target_type == "User": + self._account = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["account"]) + if target_type == "Organization": + self._account = self._makeClassAttribute(github.Organization.Organization, attributes["account"]) + if "app_id" in attributes: # pragma no branch + self._app_id = self._makeIntAttribute(attributes["app_id"]) + if "app_slug" in attributes: # pragma no branch + self._app_slug = self._makeStringAttribute(attributes["app_slug"]) + if "contact_email" in attributes: # pragma no branch + self._contact_email = self._makeStringAttribute(attributes["contact_email"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "events" in attributes: # pragma no branch + self._events = self._makeListOfStringsAttribute(attributes["events"]) + if "has_multiple_single_files" in attributes: # pragma no branch + self._has_multiple_single_files = self._makeBoolAttribute(attributes["has_multiple_single_files"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeDictAttribute(attributes["permissions"]) + if "repositories_url" in attributes: # pragma no branch + self._repositories_url = self._makeStringAttribute(attributes["repositories_url"]) + if "repository_selection" in attributes: # pragma no branch + self._repository_selection = self._makeStringAttribute(attributes["repository_selection"]) + if "single_file_name" in attributes: # pragma no branch + self._single_file_name = self._makeStringAttribute(attributes["single_file_name"]) + if "single_file_paths" in attributes: # pragma no branch + self._single_file_paths = self._makeListOfStringsAttribute(attributes["single_file_paths"]) + if "suspended_at" in attributes: # pragma no branch + self._suspended_at = self._makeDatetimeAttribute(attributes["suspended_at"]) + if "suspended_by" in attributes: # pragma no branch + self._suspended_by = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["suspended_by"]) + if "target_id" in attributes: # pragma no branch + self._target_id = self._makeIntAttribute(attributes["target_id"]) + if "target_type" in attributes: # pragma no branch + self._target_type = self._makeStringAttribute(attributes["target_type"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) diff --git a/python_embeded/Lib/site-packages/github/InstallationAuthorization.py b/python_embeded/Lib/site-packages/github/InstallationAuthorization.py new file mode 100644 index 0000000000000000000000000000000000000000..9b7e1a0ea21ffa67a46250fa70753f6de1e2597e --- /dev/null +++ b/python_embeded/Lib/site-packages/github/InstallationAuthorization.py @@ -0,0 +1,136 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Simon # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Denis Blanchette # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.NamedUser +import github.PaginatedList +import github.Repository +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + from github.Repository import Repository + + +class InstallationAuthorization(NonCompletableGithubObject): + """ + This class represents InstallationAuthorizations. + + The OpenAPI schema can be found at + - /components/schemas/installation-token + + """ + + def _initAttributes(self) -> None: + self._expires_at: Attribute[datetime] = NotSet + self._has_multiple_single_files: Attribute[bool] = NotSet + self._on_behalf_of: Attribute[NamedUser] = NotSet + self._permissions: Attribute[dict] = NotSet + self._repositories: Attribute[list[Repository]] = NotSet + self._repository_selection: Attribute[str] = NotSet + self._single_file: Attribute[str] = NotSet + self._single_file_paths: Attribute[list[str]] = NotSet + self._token: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"expires_at": self._expires_at.value}) + + @property + def expires_at(self) -> datetime: + return self._expires_at.value + + @property + def has_multiple_single_files(self) -> bool: + return self._has_multiple_single_files.value + + @property + def on_behalf_of(self) -> NamedUser: + return self._on_behalf_of.value + + @property + def permissions(self) -> dict: + return self._permissions.value + + @property + def repositories(self) -> list[Repository]: + return self._repositories.value + + @property + def repository_selection(self) -> str: + return self._repository_selection.value + + @property + def single_file(self) -> str: + return self._single_file.value + + @property + def single_file_paths(self) -> list[str]: + return self._single_file_paths.value + + @property + def token(self) -> str: + return self._token.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "expires_at" in attributes: # pragma no branch + self._expires_at = self._makeDatetimeAttribute(attributes["expires_at"]) + if "has_multiple_single_files" in attributes: # pragma no branch + self._has_multiple_single_files = self._makeBoolAttribute(attributes["has_multiple_single_files"]) + if "on_behalf_of" in attributes: # pragma no branch + self._on_behalf_of = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["on_behalf_of"]) + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeDictAttribute(attributes["permissions"]) + if "repositories" in attributes: # pragma no branch + self._repositories = self._makeListOfClassesAttribute( + github.Repository.Repository, attributes["repositories"] + ) + if "repository_selection" in attributes: # pragma no branch + self._repository_selection = self._makeStringAttribute(attributes["repository_selection"]) + if "single_file" in attributes: # pragma no branch + self._single_file = self._makeStringAttribute(attributes["single_file"]) + if "single_file_paths" in attributes: # pragma no branch + self._single_file_paths = self._makeListOfStringsAttribute(attributes["single_file_paths"]) + if "token" in attributes: # pragma no branch + self._token = self._makeStringAttribute(attributes["token"]) diff --git a/python_embeded/Lib/site-packages/github/Invitation.py b/python_embeded/Lib/site-packages/github/Invitation.py new file mode 100644 index 0000000000000000000000000000000000000000..824670e7292c7e7672d775b8b4bc6882994c7767 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Invitation.py @@ -0,0 +1,155 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Jannis Gebauer # +# Copyright 2017 Simon # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.GithubObject +import github.NamedUser +import github.Repository +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + from github.Repository import Repository + + +class Invitation(CompletableGithubObject): + """ + This class represents repository invitations. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#invitations + + The OpenAPI schema can be found at + - /components/schemas/repository-invitation + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._expired: Attribute[bool] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._invitee: Attribute[NamedUser] = NotSet + self._inviter: Attribute[NamedUser] = NotSet + self._node_id: Attribute[str] = NotSet + self._permissions: Attribute[str] = NotSet + self._repository: Attribute[Repository] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value}) + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def expired(self) -> bool: + self._completeIfNotSet(self._expired) + return self._expired.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def invitee(self) -> NamedUser: + self._completeIfNotSet(self._invitee) + return self._invitee.value + + @property + def inviter(self) -> NamedUser: + self._completeIfNotSet(self._inviter) + return self._inviter.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def permissions(self) -> str: + self._completeIfNotSet(self._permissions) + return self._permissions.value + + @property + def repository(self) -> Repository: + self._completeIfNotSet(self._repository) + return self._repository.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "expired" in attributes: # pragma no branch + self._expired = self._makeBoolAttribute(attributes["expired"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "invitee" in attributes: # pragma no branch + self._invitee = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["invitee"]) + if "inviter" in attributes: # pragma no branch + self._inviter = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["inviter"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeStringAttribute(attributes["permissions"]) + if "repository" in attributes: # pragma no branch + self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/Issue.py b/python_embeded/Lib/site-packages/github/Issue.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a8f21845d72412641b2c0fdb42e60edcd9740e --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Issue.py @@ -0,0 +1,673 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Andrew Bettison # +# Copyright 2012 Philip Kimmey # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 David Farr # +# Copyright 2013 Stuart Glaser # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Raja Reddy Karri # +# Copyright 2016 @tmshn # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Matt Babineau # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Nicolas Agustín Torres # +# Copyright 2017 Simon # +# Copyright 2018 Aaron L. Levine # +# Copyright 2018 Shinichi TAMURA # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 per1234 # +# Copyright 2018 sfdye # +# Copyright 2019 Filipe Laíns # +# Copyright 2019 Nick Campbell # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Huan-Cheng Chang # +# Copyright 2020 Huw Jones # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Nicolas Schweitzer # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Malik Shahzad Muzaffar # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import urllib.parse +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.GithubApp +import github.GithubObject +import github.IssueComment +import github.IssueEvent +import github.IssuePullRequest +import github.Label +import github.Milestone +import github.NamedUser +import github.PullRequest +import github.Reaction +import github.Repository +import github.TimelineEvent +from github import Consts +from github.GithubObject import ( + Attribute, + CompletableGithubObject, + NotSet, + Opt, + is_defined, + is_optional, + is_optional_list, + is_undefined, +) +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.GithubApp import GithubApp + from github.IssueComment import IssueComment + from github.IssueEvent import IssueEvent + from github.IssuePullRequest import IssuePullRequest + from github.Label import Label + from github.Milestone import Milestone + from github.NamedUser import NamedUser + from github.PullRequest import PullRequest + from github.Reaction import Reaction + from github.Repository import Repository + from github.TimelineEvent import TimelineEvent + + +class Issue(CompletableGithubObject): + """ + This class represents Issues. + + The reference can be found here + https://docs.github.com/en/rest/reference/issues + + The OpenAPI schema can be found at + - /components/schemas/issue + - /components/schemas/issue-search-result-item + - /components/schemas/nullable-issue + + """ + + def _initAttributes(self) -> None: + self._active_lock_reason: Attribute[str | None] = NotSet + self._assignee: Attribute[NamedUser | None] = NotSet + self._assignees: Attribute[list[NamedUser]] = NotSet + self._author_association: Attribute[str] = NotSet + self._body: Attribute[str] = NotSet + self._body_html: Attribute[str] = NotSet + self._body_text: Attribute[str] = NotSet + self._closed_at: Attribute[datetime] = NotSet + self._closed_by: Attribute[NamedUser] = NotSet + self._comments: Attribute[int] = NotSet + self._comments_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._draft: Attribute[bool] = NotSet + self._events_url: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._labels: Attribute[list[Label]] = NotSet + self._labels_url: Attribute[str] = NotSet + self._locked: Attribute[bool] = NotSet + self._milestone: Attribute[Milestone] = NotSet + self._node_id: Attribute[str] = NotSet + self._number: Attribute[int] = NotSet + self._performed_via_github_app: Attribute[GithubApp] = NotSet + self._pull_request: Attribute[IssuePullRequest] = NotSet + self._reactions: Attribute[dict] = NotSet + self._repository: Attribute[Repository] = NotSet + self._repository_url: Attribute[str] = NotSet + self._score: Attribute[float] = NotSet + self._state: Attribute[str] = NotSet + self._state_reason: Attribute[str | None] = NotSet + self._text_matches: Attribute[dict[str, Any]] = NotSet + self._timeline_url: Attribute[str] = NotSet + self._title: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._user: Attribute[NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"number": self._number.value, "title": self._title.value}) + + @property + def _identity(self) -> int: + return self.number + + @property + def active_lock_reason(self) -> str | None: + self._completeIfNotSet(self._active_lock_reason) + return self._active_lock_reason.value + + @property + def assignee(self) -> NamedUser | None: + self._completeIfNotSet(self._assignee) + return self._assignee.value + + @property + def assignees(self) -> list[NamedUser]: + self._completeIfNotSet(self._assignees) + return self._assignees.value + + @property + def author_association(self) -> str: + self._completeIfNotSet(self._author_association) + return self._author_association.value + + @property + def body(self) -> str: + self._completeIfNotSet(self._body) + return self._body.value + + @property + def body_html(self) -> str: + self._completeIfNotSet(self._body_html) + return self._body_html.value + + @property + def body_text(self) -> str: + self._completeIfNotSet(self._body_text) + return self._body_text.value + + @property + def closed_at(self) -> datetime: + self._completeIfNotSet(self._closed_at) + return self._closed_at.value + + @property + def closed_by(self) -> NamedUser | None: + self._completeIfNotSet(self._closed_by) + return self._closed_by.value + + @property + def comments(self) -> int: + self._completeIfNotSet(self._comments) + return self._comments.value + + @property + def comments_url(self) -> str: + self._completeIfNotSet(self._comments_url) + return self._comments_url.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def draft(self) -> bool: + self._completeIfNotSet(self._draft) + return self._draft.value + + @property + def events_url(self) -> str: + self._completeIfNotSet(self._events_url) + return self._events_url.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def labels(self) -> list[Label]: + self._completeIfNotSet(self._labels) + return self._labels.value + + @property + def labels_url(self) -> str: + self._completeIfNotSet(self._labels_url) + return self._labels_url.value + + @property + def locked(self) -> bool: + self._completeIfNotSet(self._locked) + return self._locked.value + + @property + def milestone(self) -> Milestone: + self._completeIfNotSet(self._milestone) + return self._milestone.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def number(self) -> int: + self._completeIfNotSet(self._number) + return self._number.value + + @property + def performed_via_github_app(self) -> GithubApp: + self._completeIfNotSet(self._performed_via_github_app) + return self._performed_via_github_app.value + + @property + def pull_request(self) -> IssuePullRequest | None: + self._completeIfNotSet(self._pull_request) + return self._pull_request.value + + @property + def reactions(self) -> dict: + self._completeIfNotSet(self._reactions) + return self._reactions.value + + @property + def repository(self) -> Repository: + self._completeIfNotSet(self._repository) + if is_undefined(self._repository): + # The repository was not set automatically, so it must be looked up by url. + repo_url = "/".join(self.url.split("/")[:-2]) + self._repository = github.GithubObject._ValuedAttribute( + github.Repository.Repository(self._requester, self._headers, {"url": repo_url}, completed=False) + ) + return self._repository.value + + @property + def repository_url(self) -> str: + self._completeIfNotSet(self._repository_url) + return self._repository_url.value + + @property + def score(self) -> float: + self._completeIfNotSet(self._score) + return self._score.value + + @property + def state(self) -> str: + self._completeIfNotSet(self._state) + return self._state.value + + @property + def state_reason(self) -> str | None: + self._completeIfNotSet(self._state_reason) + return self._state_reason.value + + @property + def text_matches(self) -> dict[str, Any]: + self._completeIfNotSet(self._text_matches) + return self._text_matches.value + + @property + def timeline_url(self) -> str: + self._completeIfNotSet(self._timeline_url) + return self._timeline_url.value + + @property + def title(self) -> str: + self._completeIfNotSet(self._title) + return self._title.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def user(self) -> NamedUser: + self._completeIfNotSet(self._user) + return self._user.value + + def as_pull_request(self) -> PullRequest: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number} `_ + """ + headers, data = self._requester.requestJsonAndCheck("GET", "/pulls/".join(self.url.rsplit("/issues/", 1))) + return github.PullRequest.PullRequest(self._requester, headers, data, completed=True) + + def add_to_assignees(self, *assignees: NamedUser | str) -> None: + """ + :calls: `POST /repos/{owner}/{repo}/issues/{number}/assignees `_ + """ + assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees + post_parameters = { + "assignees": [ + assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee + for assignee in assignees + ] + } + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/assignees", input=post_parameters) + self._useAttributes(data) + + def add_to_labels(self, *labels: Label | str) -> None: + """ + :calls: `POST /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels + post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels] + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/labels", input=post_parameters) + + def create_comment(self, body: str) -> IssueComment: + """ + :calls: `POST /repos/{owner}/{repo}/issues/{number}/comments `_ + """ + assert isinstance(body, str), body + post_parameters = { + "body": body, + } + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/comments", input=post_parameters) + return github.IssueComment.IssueComment(self._requester, headers, data, completed=True) + + def delete_labels(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/labels") + + def edit( + self, + title: Opt[str] = NotSet, + body: Opt[str] = NotSet, + assignee: Opt[str | NamedUser | None] = NotSet, + state: Opt[str] = NotSet, + milestone: Opt[Milestone | None] = NotSet, + labels: Opt[list[str]] = NotSet, + assignees: Opt[list[NamedUser | str]] = NotSet, + state_reason: Opt[str] = NotSet, + ) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/issues/{number} `_ + :param assignee: deprecated, use `assignees` instead. `assignee=None` means to remove current assignee. + :param milestone: `milestone=None` means to remove current milestone. + """ + assert is_optional(title, str), title + assert is_optional(body, str), body + assert assignee is None or is_optional(assignee, (github.NamedUser.NamedUser, str)), assignee + assert is_optional_list(assignees, (github.NamedUser.NamedUser, str)), assignees + assert is_optional(state, str), state + assert milestone is None or is_optional(milestone, github.Milestone.Milestone), milestone + assert is_optional_list(labels, str), labels + + post_parameters = NotSet.remove_unset_items( + { + "title": title, + "body": body, + "state": state, + "state_reason": state_reason, + "labels": labels, + "assignee": assignee._identity + if isinstance(assignee, github.NamedUser.NamedUser) + else (assignee or ""), + "milestone": milestone._identity + if isinstance(milestone, github.Milestone.Milestone) + else (milestone or ""), + } + ) + + if is_defined(assignees): + post_parameters["assignees"] = [ + element._identity if isinstance(element, github.NamedUser.NamedUser) else element + for element in assignees + ] + + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def lock(self, lock_reason: str) -> None: + """ + :calls: `PUT /repos/{owner}/{repo}/issues/{issue_number}/lock `_ + """ + assert isinstance(lock_reason, str), lock_reason + put_parameters = {"lock_reason": lock_reason} + headers, data = self._requester.requestJsonAndCheck( + "PUT", + f"{self.url}/lock", + input=put_parameters, + headers={"Accept": Consts.mediaTypeLockReasonPreview}, + ) + + def unlock(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/lock") + + def get_comment(self, id: int) -> IssueComment: + """ + :calls: `GET /repos/{owner}/{repo}/issues/comments/{id} `_ + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self._parentUrl(self.url)}/comments/{id}") + return github.IssueComment.IssueComment(self._requester, headers, data, completed=True) + + def get_comments(self, since: Opt[datetime] = NotSet) -> PaginatedList[IssueComment]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number}/comments `_ + """ + url_parameters = {} + if is_defined(since): + assert isinstance(since, datetime), since + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + + return PaginatedList( + github.IssueComment.IssueComment, + self._requester, + f"{self.url}/comments", + url_parameters, + ) + + def get_events(self) -> PaginatedList[IssueEvent]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{issue_number}/events `_ + """ + return PaginatedList( + github.IssueEvent.IssueEvent, + self._requester, + f"{self.url}/events", + None, + headers={"Accept": Consts.mediaTypeLockReasonPreview}, + ) + + def get_labels(self) -> PaginatedList[Label]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + return PaginatedList(github.Label.Label, self._requester, f"{self.url}/labels", None) + + def remove_from_assignees(self, *assignees: NamedUser | str) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{number}/assignees `_ + """ + assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees + post_parameters = { + "assignees": [ + assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee + for assignee in assignees + ] + } + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/assignees", input=post_parameters) + self._useAttributes(data) + + def remove_from_labels(self, label: Label | str) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name} `_ + """ + assert isinstance(label, (github.Label.Label, str)), label + if isinstance(label, github.Label.Label): + label = label._identity + else: + label = urllib.parse.quote(label) + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/labels/{label}") + + def set_labels(self, *labels: Label | str) -> None: + """ + :calls: `PUT /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels + post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels] + headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/labels", input=post_parameters) + + def get_reactions(self) -> PaginatedList[Reaction]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number}/reactions `_ + """ + return PaginatedList( + github.Reaction.Reaction, + self._requester, + f"{self.url}/reactions", + None, + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + + def create_reaction(self, reaction_type: str) -> Reaction: + """ + :calls: `POST /repos/{owner}/{repo}/issues/{number}/reactions `_ + """ + assert isinstance(reaction_type, str), reaction_type + post_parameters = { + "content": reaction_type, + } + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/reactions", + input=post_parameters, + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + return github.Reaction.Reaction(self._requester, headers, data, completed=True) + + def delete_reaction(self, reaction_id: int) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id} `_ + """ + assert isinstance(reaction_id, int), reaction_id + status, _, _ = self._requester.requestJson( + "DELETE", + f"{self.url}/reactions/{reaction_id}", + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + return status == 204 + + def get_timeline(self) -> PaginatedList[TimelineEvent]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number}/timeline `_ + """ + return PaginatedList( + github.TimelineEvent.TimelineEvent, + self._requester, + f"{self.url}/timeline", + None, + headers={"Accept": Consts.issueTimelineEventsPreview}, + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "active_lock_reason" in attributes: # pragma no branch + self._active_lock_reason = self._makeStringAttribute(attributes["active_lock_reason"]) + if "assignee" in attributes: # pragma no branch + self._assignee = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["assignee"]) + if "assignees" in attributes: # pragma no branch + self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, attributes["assignees"]) + elif "assignee" in attributes: + if attributes["assignee"] is not None: + self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, [attributes["assignee"]]) + else: + self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, []) + if "author_association" in attributes: # pragma no branch + self._author_association = self._makeStringAttribute(attributes["author_association"]) + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "body_html" in attributes: # pragma no branch + self._body_html = self._makeStringAttribute(attributes["body_html"]) + if "body_text" in attributes: # pragma no branch + self._body_text = self._makeStringAttribute(attributes["body_text"]) + if "closed_at" in attributes: # pragma no branch + self._closed_at = self._makeDatetimeAttribute(attributes["closed_at"]) + if "closed_by" in attributes: # pragma no branch + self._closed_by = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["closed_by"]) + if "comments" in attributes: # pragma no branch + self._comments = self._makeIntAttribute(attributes["comments"]) + if "comments_url" in attributes: # pragma no branch + self._comments_url = self._makeStringAttribute(attributes["comments_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "draft" in attributes: # pragma no branch + self._draft = self._makeBoolAttribute(attributes["draft"]) + if "events_url" in attributes: # pragma no branch + self._events_url = self._makeStringAttribute(attributes["events_url"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "labels" in attributes: # pragma no branch + self._labels = self._makeListOfClassesAttribute(github.Label.Label, attributes["labels"]) + if "labels_url" in attributes: # pragma no branch + self._labels_url = self._makeStringAttribute(attributes["labels_url"]) + if "locked" in attributes: # pragma no branch + self._locked = self._makeBoolAttribute(attributes["locked"]) + if "milestone" in attributes: # pragma no branch + self._milestone = self._makeClassAttribute(github.Milestone.Milestone, attributes["milestone"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "number" in attributes: # pragma no branch + self._number = self._makeIntAttribute(attributes["number"]) + if "performed_via_github_app" in attributes: # pragma no branch + self._performed_via_github_app = self._makeClassAttribute( + github.GithubApp.GithubApp, attributes["performed_via_github_app"] + ) + if "pull_request" in attributes: # pragma no branch + self._pull_request = self._makeClassAttribute( + github.IssuePullRequest.IssuePullRequest, attributes["pull_request"] + ) + if "reactions" in attributes: + self._reactions = self._makeDictAttribute(attributes["reactions"]) + if "repository" in attributes: # pragma no branch + self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"]) + if "repository_url" in attributes: # pragma no branch + self._repository_url = self._makeStringAttribute(attributes["repository_url"]) + if "score" in attributes: # pragma no branch + self._score = self._makeFloatAttribute(attributes["score"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "state_reason" in attributes: # pragma no branch + self._state_reason = self._makeStringAttribute(attributes["state_reason"]) + if "text_matches" in attributes: # pragma no branch + self._text_matches = self._makeDictAttribute(attributes["text_matches"]) + if "timeline_url" in attributes: # pragma no branch + self._timeline_url = self._makeStringAttribute(attributes["timeline_url"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/IssueComment.py b/python_embeded/Lib/site-packages/github/IssueComment.py new file mode 100644 index 0000000000000000000000000000000000000000..018d97b8c0fceae395c25dd1ac9d1845757951cf --- /dev/null +++ b/python_embeded/Lib/site-packages/github/IssueComment.py @@ -0,0 +1,289 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Michael Stead # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Nicolas Agustín Torres # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 per1234 # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Huan-Cheng Chang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Malik Shahzad Muzaffar # +# Copyright 2023 Trim21 # +# Copyright 2024 Arash Kadkhodaei # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.GithubApp +import github.GithubObject +import github.NamedUser +from github import Consts +from github.GithubObject import Attribute, CompletableGithubObject, NotSet +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.GithubApp import GithubApp + from github.NamedUser import NamedUser + from github.Reaction import Reaction + + +class IssueComment(CompletableGithubObject): + """ + This class represents IssueComments. + + The reference can be found here + https://docs.github.com/en/rest/reference/issues#comments + + The OpenAPI schema can be found at + - /components/schemas/issue-comment + + """ + + def _initAttributes(self) -> None: + self._author_association: Attribute[str] = NotSet + self._body: Attribute[str] = NotSet + self._body_html: Attribute[str] = NotSet + self._body_text: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._issue_url: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._performed_via_github_app: Attribute[GithubApp] = NotSet + self._reactions: Attribute[dict] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._user: Attribute[NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "user": self._user.value}) + + @property + def author_association(self) -> str: + self._completeIfNotSet(self._author_association) + return self._author_association.value + + @property + def body(self) -> str: + self._completeIfNotSet(self._body) + return self._body.value + + @property + def body_html(self) -> str: + self._completeIfNotSet(self._body_html) + return self._body_html.value + + @property + def body_text(self) -> str: + self._completeIfNotSet(self._body_text) + return self._body_text.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def issue_url(self) -> str: + self._completeIfNotSet(self._issue_url) + return self._issue_url.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def performed_via_github_app(self) -> GithubApp: + self._completeIfNotSet(self._performed_via_github_app) + return self._performed_via_github_app.value + + @property + def reactions(self) -> dict: + self._completeIfNotSet(self._reactions) + return self._reactions.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def user(self) -> NamedUser: + self._completeIfNotSet(self._user) + return self._user.value + + def delete(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/comments/{id} `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def edit(self, body: str) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/issues/comments/{id} `_ + """ + assert isinstance(body, str), body + post_parameters = { + "body": body, + } + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def get_reactions(self) -> PaginatedList[Reaction]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/comments/{id}/reactions + `_ + """ + return PaginatedList( + github.Reaction.Reaction, + self._requester, + f"{self.url}/reactions", + None, + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + + def create_reaction(self, reaction_type: str) -> Reaction: + """ + :calls: `POST /repos/{owner}/{repo}/issues/comments/{id}/reactions + `_ + """ + assert isinstance(reaction_type, str), reaction_type + post_parameters = { + "content": reaction_type, + } + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/reactions", + input=post_parameters, + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + return github.Reaction.Reaction(self._requester, headers, data, completed=True) + + def delete_reaction(self, reaction_id: int) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id} + `_ + """ + assert isinstance(reaction_id, int), reaction_id + status, _, _ = self._requester.requestJson( + "DELETE", + f"{self.url}/reactions/{reaction_id}", + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + return status == 204 + + def minimize(self, reason: str = "OUTDATED") -> bool: + """ + :calls: `POST /graphql `_ with a mutation to minimize comment + + """ + assert isinstance(reason, str), reason + variables = { + "subjectId": self.node_id, + "classifier": reason, + } + _, data = self._requester.graphql_named_mutation( + mutation_name="minimizeComment", + mutation_input=NotSet.remove_unset_items(variables), + output_schema="minimizedComment { isMinimized }", + ) + return data["minimizedComment"]["isMinimized"] is True + + def unminimize(self) -> bool: + """ + :calls: `POST /graphql `_ with a mutation to unminimize comment + + """ + variables = { + "subjectId": self.node_id, + } + _, data = self._requester.graphql_named_mutation( + mutation_name="unminimizeComment", + mutation_input=NotSet.remove_unset_items(variables), + output_schema="unminimizedComment { isMinimized }", + ) + return data["unminimizedComment"]["isMinimized"] is False + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "author_association" in attributes: # pragma no branch + self._author_association = self._makeStringAttribute(attributes["author_association"]) + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "body_html" in attributes: # pragma no branch + self._body_html = self._makeStringAttribute(attributes["body_html"]) + if "body_text" in attributes: # pragma no branch + self._body_text = self._makeStringAttribute(attributes["body_text"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "issue_url" in attributes: # pragma no branch + self._issue_url = self._makeStringAttribute(attributes["issue_url"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "performed_via_github_app" in attributes: # pragma no branch + self._performed_via_github_app = self._makeClassAttribute( + github.GithubApp.GithubApp, attributes["performed_via_github_app"] + ) + if "reactions" in attributes: + self._reactions = self._makeDictAttribute(attributes["reactions"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/IssueEvent.py b/python_embeded/Lib/site-packages/github/IssueEvent.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea4bb2aace98b986224005f37a9b8dfb29d8b01 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/IssueEvent.py @@ -0,0 +1,266 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Simon # +# Copyright 2018 Aaron L. Levine # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.GithubApp +import github.GithubObject +import github.Issue +import github.Label +import github.Milestone +import github.NamedUser +import github.Team +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.GithubApp import GithubApp + from github.Issue import Issue + from github.Label import Label + from github.Milestone import Milestone + from github.NamedUser import NamedUser + from github.Team import Team + + +class IssueEvent(CompletableGithubObject): + """ + This class represents IssueEvents. + + The reference can be found here + https://docs.github.com/en/rest/reference/issues#events + + The OpenAPI schema can be found at + - /components/schemas/issue-event + - /components/schemas/issue-event-for-issue + + """ + + def _initAttributes(self) -> None: + self._actor: Attribute[NamedUser] = NotSet + self._assignee: Attribute[NamedUser] = NotSet + self._assigner: Attribute[NamedUser] = NotSet + self._author_association: Attribute[dict[str, Any]] = NotSet + self._commit_id: Attribute[str] = NotSet + self._commit_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._dismissed_review: Attribute[dict] = NotSet + self._event: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._issue: Attribute[Issue] = NotSet + self._label: Attribute[Label] = NotSet + self._lock_reason: Attribute[str] = NotSet + self._milestone: Attribute[Milestone] = NotSet + self._node_id: Attribute[str] = NotSet + self._performed_via_github_app: Attribute[GithubApp] = NotSet + self._project_card: Attribute[dict[str, Any]] = NotSet + self._rename: Attribute[dict] = NotSet + self._requested_reviewer: Attribute[NamedUser] = NotSet + self._requested_team: Attribute[Team] = NotSet + self._review_requester: Attribute[NamedUser] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value}) + + @property + def actor(self) -> NamedUser: + self._completeIfNotSet(self._actor) + return self._actor.value + + @property + def assignee(self) -> NamedUser: + self._completeIfNotSet(self._assignee) + return self._assignee.value + + @property + def assigner(self) -> NamedUser: + self._completeIfNotSet(self._assigner) + return self._assigner.value + + @property + def author_association(self) -> dict[str, Any]: + self._completeIfNotSet(self._author_association) + return self._author_association.value + + @property + def commit_id(self) -> str: + self._completeIfNotSet(self._commit_id) + return self._commit_id.value + + @property + def commit_url(self) -> str: + self._completeIfNotSet(self._commit_url) + return self._commit_url.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def dismissed_review(self) -> dict: + self._completeIfNotSet(self._dismissed_review) + return self._dismissed_review.value + + @property + def event(self) -> str: + self._completeIfNotSet(self._event) + return self._event.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def issue(self) -> Issue: + self._completeIfNotSet(self._issue) + return self._issue.value + + @property + def label(self) -> Label: + self._completeIfNotSet(self._label) + return self._label.value + + @property + def lock_reason(self) -> str: + self._completeIfNotSet(self._lock_reason) + return self._lock_reason.value + + @property + def milestone(self) -> Milestone: + self._completeIfNotSet(self._milestone) + return self._milestone.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def performed_via_github_app(self) -> GithubApp: + self._completeIfNotSet(self._performed_via_github_app) + return self._performed_via_github_app.value + + @property + def project_card(self) -> dict[str, Any]: + self._completeIfNotSet(self._project_card) + return self._project_card.value + + @property + def rename(self) -> dict: + self._completeIfNotSet(self._rename) + return self._rename.value + + @property + def requested_reviewer(self) -> NamedUser: + self._completeIfNotSet(self._requested_reviewer) + return self._requested_reviewer.value + + @property + def requested_team(self) -> Team: + self._completeIfNotSet(self._requested_team) + return self._requested_team.value + + @property + def review_requester(self) -> NamedUser: + self._completeIfNotSet(self._review_requester) + return self._review_requester.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "actor" in attributes: # pragma no branch + self._actor = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["actor"]) + if "assignee" in attributes: # pragma no branch + self._assignee = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["assignee"]) + if "assigner" in attributes: # pragma no branch + self._assigner = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["assigner"]) + if "author_association" in attributes: # pragma no branch + self._author_association = self._makeDictAttribute(attributes["author_association"]) + if "commit_id" in attributes: # pragma no branch + self._commit_id = self._makeStringAttribute(attributes["commit_id"]) + if "commit_url" in attributes: # pragma no branch + self._commit_url = self._makeStringAttribute(attributes["commit_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "dismissed_review" in attributes: # pragma no branch + self._dismissed_review = self._makeDictAttribute(attributes["dismissed_review"]) + if "event" in attributes: # pragma no branch + self._event = self._makeStringAttribute(attributes["event"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "issue" in attributes: # pragma no branch + self._issue = self._makeClassAttribute(github.Issue.Issue, attributes["issue"]) + if "label" in attributes: # pragma no branch + self._label = self._makeClassAttribute(github.Label.Label, attributes["label"]) + if "lock_reason" in attributes: # pragma no branch + self._lock_reason = self._makeStringAttribute(attributes["lock_reason"]) + if "milestone" in attributes: # pragma no branch + self._milestone = self._makeClassAttribute(github.Milestone.Milestone, attributes["milestone"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "performed_via_github_app" in attributes: # pragma no branch + self._performed_via_github_app = self._makeClassAttribute( + github.GithubApp.GithubApp, attributes["performed_via_github_app"] + ) + if "project_card" in attributes: # pragma no branch + self._project_card = self._makeDictAttribute(attributes["project_card"]) + if "rename" in attributes: # pragma no branch + self._rename = self._makeDictAttribute(attributes["rename"]) + if "requested_reviewer" in attributes: # pragma no branch + self._requested_reviewer = self._makeClassAttribute( + github.NamedUser.NamedUser, attributes["requested_reviewer"] + ) + if "requested_team" in attributes: # pragma no branch + self._requested_team = self._makeClassAttribute(github.Team.Team, attributes["requested_team"]) + if "review_requester" in attributes: # pragma no branch + self._review_requester = self._makeClassAttribute( + github.NamedUser.NamedUser, attributes["review_requester"] + ) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/IssuePullRequest.py b/python_embeded/Lib/site-packages/github/IssuePullRequest.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd4f8c31c64aee471a684861ef79b39217bb22f --- /dev/null +++ b/python_embeded/Lib/site-packages/github/IssuePullRequest.py @@ -0,0 +1,95 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class IssuePullRequest(NonCompletableGithubObject): + """ + This class represents IssuePullRequests. + + The OpenAPI schema can be found at + - /components/schemas/issue-search-result-item/properties/pull_request + - /components/schemas/issue/properties/pull_request + - /components/schemas/nullable-issue/properties/pull_request + + """ + + def _initAttributes(self) -> None: + self._diff_url: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._merged_at: Attribute[datetime] = NotSet + self._patch_url: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + + @property + def diff_url(self) -> str: + return self._diff_url.value + + @property + def html_url(self) -> str: + return self._html_url.value + + @property + def merged_at(self) -> datetime: + return self._merged_at.value + + @property + def patch_url(self) -> str: + return self._patch_url.value + + @property + def url(self) -> str: + return self._url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "diff_url" in attributes: # pragma no branch + self._diff_url = self._makeStringAttribute(attributes["diff_url"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "merged_at" in attributes: # pragma no branch + self._merged_at = self._makeDatetimeAttribute(attributes["merged_at"]) + if "patch_url" in attributes: # pragma no branch + self._patch_url = self._makeStringAttribute(attributes["patch_url"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/Label.py b/python_embeded/Lib/site-packages/github/Label.py new file mode 100644 index 0000000000000000000000000000000000000000..02aec3539d41089c6659b31374fb0580cd7f0d9b --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Label.py @@ -0,0 +1,158 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Mateusz Loskot # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import urllib.parse +from typing import Any + +from github import Consts +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_optional + + +class Label(CompletableGithubObject): + """ + This class represents Labels. + + The reference can be found here + https://docs.github.com/en/rest/reference/issues#labels + + The OpenAPI schema can be found at + - /components/schemas/issue-event-label + - /components/schemas/issue-search-result-item/properties/labels/items + - /components/schemas/issue/properties/labels/items/oneOf/1 + - /components/schemas/label + - /components/schemas/nullable-issue/properties/labels/items/oneOf/1 + - /components/schemas/pull-request-simple/properties/labels/items + - /components/schemas/pull-request/properties/labels/items + + """ + + def _initAttributes(self) -> None: + self._color: Attribute[str] = NotSet + self._default: Attribute[bool] = NotSet + self._description: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value}) + + @property + def _identity(self) -> str: + return urllib.parse.quote(self.name) + + @property + def color(self) -> str: + self._completeIfNotSet(self._color) + return self._color.value + + @property + def default(self) -> bool: + self._completeIfNotSet(self._default) + return self._default.value + + @property + def description(self) -> str: + self._completeIfNotSet(self._description) + return self._description.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def delete(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/labels/{name} `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def edit(self, name: str, color: str, description: Opt[str] = NotSet) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/labels/{name} `_ + """ + assert isinstance(name, str), name + assert isinstance(color, str), color + assert is_optional(description, str), description + post_parameters = NotSet.remove_unset_items({"new_name": name, "color": color, "description": description}) + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=post_parameters, + headers={"Accept": Consts.mediaTypeLabelDescriptionSearchPreview}, + ) + self._useAttributes(data) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "color" in attributes: # pragma no branch + self._color = self._makeStringAttribute(attributes["color"]) + if "default" in attributes: # pragma no branch + self._default = self._makeBoolAttribute(attributes["default"]) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/License.py b/python_embeded/Lib/site-packages/github/License.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a1c2257e8e7c67258d22c72925fb47e9f68ebb --- /dev/null +++ b/python_embeded/Lib/site-packages/github/License.py @@ -0,0 +1,167 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Aaron Levine # +# Copyright 2017 Mike Miller # +# Copyright 2018 Darragh Bailey # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class License(CompletableGithubObject): + """ + This class represents Licenses. + + The reference can be found here + https://docs.github.com/en/rest/reference/licenses + + The OpenAPI schema can be found at + - /components/schemas/license-simple + - /components/schemas/minimal-repository/properties/license + - /components/schemas/nullable-license-simple + + """ + + def _initAttributes(self) -> None: + self._body: Attribute[str] = NotSet + self._conditions: Attribute[list[str]] = NotSet + self._description: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._implementation: Attribute[str] = NotSet + self._key: Attribute[str] = NotSet + self._limitations: Attribute[list[str]] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._permissions: Attribute[list[str]] = NotSet + self._spdx_id: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value}) + + @property + def body(self) -> str: + self._completeIfNotSet(self._body) + return self._body.value + + @property + def conditions(self) -> list[str]: + self._completeIfNotSet(self._conditions) + return self._conditions.value + + @property + def description(self) -> str: + self._completeIfNotSet(self._description) + return self._description.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def implementation(self) -> str: + self._completeIfNotSet(self._implementation) + return self._implementation.value + + @property + def key(self) -> str: + self._completeIfNotSet(self._key) + return self._key.value + + @property + def limitations(self) -> list[str]: + self._completeIfNotSet(self._limitations) + return self._limitations.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def permissions(self) -> list[str]: + self._completeIfNotSet(self._permissions) + return self._permissions.value + + @property + def spdx_id(self) -> str: + self._completeIfNotSet(self._spdx_id) + return self._spdx_id.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "conditions" in attributes: # pragma no branch + self._conditions = self._makeListOfStringsAttribute(attributes["conditions"]) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "implementation" in attributes: # pragma no branch + self._implementation = self._makeStringAttribute(attributes["implementation"]) + if "key" in attributes: # pragma no branch + self._key = self._makeStringAttribute(attributes["key"]) + if "limitations" in attributes: # pragma no branch + self._limitations = self._makeListOfStringsAttribute(attributes["limitations"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeListOfStringsAttribute(attributes["permissions"]) + if "spdx_id" in attributes: # pragma no branch + self._spdx_id = self._makeStringAttribute(attributes["spdx_id"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/MainClass.py b/python_embeded/Lib/site-packages/github/MainClass.py new file mode 100644 index 0000000000000000000000000000000000000000..19838573664f5b95c8bac0ce0d6a9a769429fb29 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/MainClass.py @@ -0,0 +1,1058 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Dima Kukushkin # +# Copyright 2012 Luke Cawood # +# Copyright 2012 Michael Woodworth # +# Copyright 2012 Steve English # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Ed Jackson # +# Copyright 2013 Jonathan J Hunt # +# Copyright 2013 Steve Brown # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 C. R. Oldham # +# Copyright 2014 Thialfihar # +# Copyright 2014 Tyler Treat # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Daniel Pocock # +# Copyright 2015 Joseph Rawson # +# Copyright 2015 Uriel Corfa # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Colin Hoglund # +# Copyright 2017 Jannis Gebauer # +# Copyright 2018 Agor Maxime # +# Copyright 2018 Arda Kuyumcu # +# Copyright 2018 Benoit Latinier # +# Copyright 2018 Bruce Richardson # +# Copyright 2018 Joshua Hoblitt # +# Copyright 2018 Maarten Fonville # +# Copyright 2018 Mike Miller # +# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Svend Sorensen # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 Yossarian King # +# Copyright 2018 h.shi <10385628+AnYeMoWang@users.noreply.github.com> # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Caleb Sweeney # +# Copyright 2019 Hamel Husain # +# Copyright 2019 Isac Souza # +# Copyright 2019 Jake Klingensmith # +# Copyright 2019 Jake Wilkins # +# Copyright 2019 Rigas Papathanasopoulos # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Tomas Tomecek # +# Copyright 2019 Wan Liuyang # +# Copyright 2019 chillipeper # +# Copyright 2019 秋葉 # +# Copyright 2020 Alice GIRARD # +# Copyright 2020 Denis Blanchette # +# Copyright 2020 Florent Clarret # +# Copyright 2020 Mahesh Raju # +# Copyright 2020 Nikolay Edigaryev # +# Copyright 2020 Omar Brikaa # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Amador Pahim # +# Copyright 2021 Mark Walker # +# Copyright 2021 Sachi King # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Denis Blanchette # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Hemslo Wang # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> # +# Copyright 2023 Joseph Henrich # +# Copyright 2023 Mark Amery # +# Copyright 2023 Trim21 # +# Copyright 2023 YugoHino # +# Copyright 2023 chantra # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Min RK # +# Copyright 2025 Enrico Minack # +# Copyright 2025 blyedev <63808441+blyedev@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import pickle +import urllib.parse +import warnings +from datetime import datetime +from typing import TYPE_CHECKING, Any, BinaryIO, TypeVar + +import urllib3 +from urllib3.util import Retry + +import github.ApplicationOAuth +import github.Auth +import github.AuthenticatedUser +import github.Enterprise +import github.Event +import github.Gist +import github.GithubApp +import github.GithubIntegration +import github.GithubRetry +import github.GitignoreTemplate +import github.GlobalAdvisory +import github.License +import github.NamedUser +import github.Topic +from github import Consts +from github.GithubIntegration import GithubIntegration +from github.GithubObject import CompletableGithubObject, GithubObject, NotSet, Opt, is_defined +from github.GithubRetry import GithubRetry +from github.HookDelivery import HookDelivery, HookDeliverySummary +from github.HookDescription import HookDescription +from github.PaginatedList import PaginatedList +from github.RateLimit import RateLimit +from github.Requester import Requester + +if TYPE_CHECKING: + from github.AppAuthentication import AppAuthentication + from github.ApplicationOAuth import ApplicationOAuth + from github.AuthenticatedUser import AuthenticatedUser + from github.Commit import Commit + from github.ContentFile import ContentFile + from github.Event import Event + from github.Gist import Gist + from github.GithubApp import GithubApp + from github.GitignoreTemplate import GitignoreTemplate + from github.GlobalAdvisory import GlobalAdvisory + from github.Issue import Issue + from github.License import License + from github.NamedUser import NamedUser + from github.Organization import Organization + from github.Project import Project + from github.ProjectColumn import ProjectColumn + from github.Repository import Repository + from github.RepositoryDiscussion import RepositoryDiscussion + from github.Topic import Topic + +TGithubObject = TypeVar("TGithubObject", bound=GithubObject) + + +class Github: + """ + This is the main class you instantiate to access the Github API v3. + + Optional parameters allow different authentication methods. + + """ + + __requester: Requester + + default_retry = GithubRetry() + + # keep non-deprecated arguments in-sync with Requester + # v3: remove login_or_token, password, jwt and app_auth + # v3: move auth to the front of arguments + # v3: add * before first argument so all arguments must be named, + # allows to reorder / add new arguments / remove deprecated arguments without breaking user code + def __init__( + self, + login_or_token: str | None = None, + password: str | None = None, + jwt: str | None = None, + app_auth: AppAuthentication | None = None, + base_url: str = Consts.DEFAULT_BASE_URL, + timeout: int = Consts.DEFAULT_TIMEOUT, + user_agent: str = Consts.DEFAULT_USER_AGENT, + per_page: int = Consts.DEFAULT_PER_PAGE, + verify: bool | str = True, + retry: int | Retry | None = default_retry, + pool_size: int | None = None, + seconds_between_requests: float | None = Consts.DEFAULT_SECONDS_BETWEEN_REQUESTS, + seconds_between_writes: float | None = Consts.DEFAULT_SECONDS_BETWEEN_WRITES, + auth: github.Auth.Auth | None = None, + # v3: set lazy = True as the default + lazy: bool = False, + ) -> None: + """ + :param login_or_token: string deprecated, use auth=github.Auth.Login(...) or auth=github.Auth.Token(...) instead + :param password: string deprecated, use auth=github.Auth.Login(...) instead + :param jwt: string deprecated, use auth=github.Auth.AppAuth(...) or auth=github.Auth.AppAuthToken(...) instead + :param app_auth: github.AppAuthentication deprecated, use auth=github.Auth.AppInstallationAuth(...) instead + :param base_url: string + :param timeout: integer + :param user_agent: string + :param per_page: int + :param verify: boolean or string + :param retry: int or urllib3.util.retry.Retry object, + defaults to github.Github.default_retry, + set to None to disable retries + :param pool_size: int + :param seconds_between_requests: float + :param seconds_between_writes: float + :param auth: authentication method + :param lazy: completable objects created from this instance are lazy, + as well as completable objects created from those, and so on + """ + + assert login_or_token is None or isinstance(login_or_token, str), login_or_token + assert password is None or isinstance(password, str), password + assert jwt is None or isinstance(jwt, str), jwt + assert isinstance(base_url, str), base_url + assert isinstance(timeout, int), timeout + assert user_agent is None or isinstance(user_agent, str), user_agent + assert isinstance(per_page, int), per_page + assert isinstance(verify, (bool, str)), verify + assert retry is None or isinstance(retry, int) or isinstance(retry, urllib3.util.Retry), retry + assert pool_size is None or isinstance(pool_size, int), pool_size + assert seconds_between_requests is None or seconds_between_requests >= 0 + assert seconds_between_writes is None or seconds_between_writes >= 0 + assert auth is None or isinstance(auth, github.Auth.Auth), auth + assert isinstance(lazy, bool), lazy + + if password is not None: + warnings.warn( + "Arguments login_or_token and password are deprecated, please use " + "auth=github.Auth.Login(...) instead", + category=DeprecationWarning, + ) + auth = github.Auth.Login(login_or_token, password) # type: ignore + elif login_or_token is not None: + warnings.warn( + "Argument login_or_token is deprecated, please use " "auth=github.Auth.Token(...) instead", + category=DeprecationWarning, + ) + auth = github.Auth.Token(login_or_token) + elif jwt is not None: + warnings.warn( + "Argument jwt is deprecated, please use " + "auth=github.Auth.AppAuth(...) or " + "auth=github.Auth.AppAuthToken(...) instead", + category=DeprecationWarning, + ) + auth = github.Auth.AppAuthToken(jwt) + elif app_auth is not None: + warnings.warn( + "Argument app_auth is deprecated, please use " "auth=github.Auth.AppInstallationAuth(...) instead", + category=DeprecationWarning, + ) + auth = app_auth + + self.__requester = Requester( + auth, + base_url, + timeout, + user_agent, + per_page, + verify, + retry, + pool_size, + seconds_between_requests, + seconds_between_writes, + lazy, + ) + + def withLazy(self, lazy: bool) -> Github: + """ + Create a Github instance with identical configuration but the given lazy setting. + + :param lazy: completable objects created from this instance are lazy, as well as completable objects created + from those, and so on + :return: new Github instance + + """ + kwargs = self.__requester.kwargs + kwargs.update(lazy=lazy) + return Github(**kwargs) + + def close(self) -> None: + """Close connections to the server. Alternatively, use the Github + object as a context manager: + + .. code-block:: python + + with github.Github(...) as gh: + # do something + """ + self.__requester.close() + + def __enter__(self) -> Github: + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.close() + + @property + def requester(self) -> Requester: + """ + Return my Requester object. + + For example, to make requests to API endpoints not yet supported by PyGitHub. + + """ + return self.__requester + + @property + def FIX_REPO_GET_GIT_REF(self) -> bool: + return self.__requester.FIX_REPO_GET_GIT_REF + + @FIX_REPO_GET_GIT_REF.setter + def FIX_REPO_GET_GIT_REF(self, value: bool) -> None: + self.__requester.FIX_REPO_GET_GIT_REF = value + + # v3: Remove this property? Why should it be necessary to read/modify it after construction + @property + def per_page(self) -> int: + return self.__requester.per_page + + @per_page.setter + def per_page(self, value: int) -> None: + self.__requester.per_page = value + + # v3: Provide a unified way to access values of headers of last response + # v3: (and add/keep ad hoc properties for specific useful headers like rate limiting, oauth scopes, etc.) + # v3: Return an instance of a class: using a tuple did not allow to add a field "resettime" + @property + def rate_limiting(self) -> tuple[int, int]: + """ + First value is requests remaining, second value is request limit. + """ + remaining, limit = self.__requester.rate_limiting + if limit < 0: + self.get_rate_limit() + return self.__requester.rate_limiting + + @property + def rate_limiting_resettime(self) -> int: + """ + Unix timestamp indicating when rate limiting will reset. + """ + if self.__requester.rate_limiting_resettime == 0: + self.get_rate_limit() + return self.__requester.rate_limiting_resettime + + def get_rate_limit(self) -> RateLimit: + """ + Rate limit status for different resources (core/search/graphql). + + :calls:`GET /rate_limit `_ + + """ + headers, data = self.__requester.requestJsonAndCheck("GET", "/rate_limit") + return RateLimit(self.__requester, headers, data["resources"]) + + @property + def oauth_scopes(self) -> list[str] | None: + """ + :type: list of string + """ + return self.__requester.oauth_scopes + + def get_license(self, key: Opt[str] = NotSet) -> License: + """ + :calls: `GET /license/{license} `_ + """ + + assert isinstance(key, str), key + key = urllib.parse.quote(key) + headers, data = self.__requester.requestJsonAndCheck("GET", f"/licenses/{key}") + return github.License.License(self.__requester, headers, data, completed=True) + + def get_licenses(self) -> PaginatedList[License]: + """ + :calls: `GET /licenses `_ + """ + + url_parameters: dict[str, Any] = {} + + return PaginatedList(github.License.License, self.__requester, "/licenses", url_parameters) + + def get_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /events `_ + """ + + return PaginatedList(github.Event.Event, self.__requester, "/events", None) + + def get_user(self, login: Opt[str] = NotSet) -> NamedUser | AuthenticatedUser: + """ + :calls: `GET /users/{user} `_ or `GET /user `_ + """ + if login is NotSet: + url = "/user" + # always return a lazy completable AuthenticatedUser + # v3: given github.Github(lazy=True) is now default, remove completed=False here + return github.AuthenticatedUser.AuthenticatedUser(self.__requester, url=url, completed=False) + else: + assert isinstance(login, str), login + login = urllib.parse.quote(login) + url = f"/users/{login}" + # always return a completed NamedUser + # v3: remove complete() here and make this as lazy as github.Github is + return github.NamedUser.NamedUser(self.__requester, url=url).complete() + + def get_user_by_id(self, user_id: int) -> NamedUser: + """ + :calls: `GET /user/{id} `_ + :param user_id: int + :rtype: :class:`github.NamedUser.NamedUser` + """ + assert isinstance(user_id, int), user_id + headers, data = self.__requester.requestJsonAndCheck("GET", f"/user/{user_id}") + return github.NamedUser.NamedUser(self.__requester, headers, data, completed=True) + + def get_users(self, since: Opt[int] = NotSet) -> PaginatedList[NamedUser]: + """ + :calls: `GET /users `_ + """ + assert since is NotSet or isinstance(since, int), since + url_parameters = dict() + if since is not NotSet: + url_parameters["since"] = since + return PaginatedList(github.NamedUser.NamedUser, self.__requester, "/users", url_parameters) + + def get_organization(self, org: str) -> Organization: + """ + :calls: `GET /orgs/{org} `_ + """ + assert isinstance(org, str), org + org = urllib.parse.quote(org) + headers, data = self.__requester.requestJsonAndCheck("GET", f"/orgs/{org}") + return github.Organization.Organization(self.__requester, headers, data, completed=True) + + def get_organizations(self, since: Opt[int] = NotSet) -> PaginatedList[Organization]: + """ + :calls: `GET /organizations `_ + """ + assert since is NotSet or isinstance(since, int), since + url_parameters = dict() + if since is not NotSet: + url_parameters["since"] = since + return PaginatedList( + github.Organization.Organization, + self.__requester, + "/organizations", + url_parameters, + ) + + def get_enterprise(self, enterprise: str) -> github.Enterprise.Enterprise: + """ + :calls: `GET /enterprises/{enterprise} `_ + :param enterprise: string + :rtype: :class:`Enterprise` + """ + assert isinstance(enterprise, str), enterprise + # There is no native "/enterprises/{enterprise}" api, so this function is a hub for apis that start with "/enterprise/{enterprise}". + return github.Enterprise.Enterprise(self.__requester, enterprise) + + def get_repo(self, full_name_or_id: int | str, lazy: bool = False) -> Repository: + """ + :calls: `GET /repos/{owner}/{repo} `_ or `GET /repositories/{id} `_ + """ + assert isinstance(full_name_or_id, (str, int)), full_name_or_id + url_base = "/repositories/" if isinstance(full_name_or_id, int) else "/repos/" + url = f"{url_base}{full_name_or_id}" + if lazy: + return github.Repository.Repository(self.__requester, {}, {"url": url}, completed=False) + headers, data = self.__requester.requestJsonAndCheck("GET", url) + return github.Repository.Repository(self.__requester, headers, data, completed=True) + + def get_repos( + self, + since: Opt[int] = NotSet, + visibility: Opt[str] = NotSet, + ) -> PaginatedList[Repository]: + """ + :calls: `GET /repositories `_ + :param since: integer + :param visibility: string ('all','public') + """ + assert since is NotSet or isinstance(since, int), since + url_parameters: dict[str, Any] = {} + if since is not NotSet: + url_parameters["since"] = since + if visibility is not NotSet: + assert visibility in ("public", "all"), visibility + url_parameters["visibility"] = visibility + return PaginatedList( + github.Repository.Repository, + self.__requester, + "/repositories", + url_parameters, + ) + + def get_repository_discussion(self, node_id: str, discussion_graphql_schema: str) -> RepositoryDiscussion: + return self.__requester.graphql_node_class( + node_id, discussion_graphql_schema, github.RepositoryDiscussion.RepositoryDiscussion, "Discussion" + ) + + def get_project(self, id: int) -> Project: + """ + :calls: `GET /projects/{project_id} `_ + """ + headers, data = self.__requester.requestJsonAndCheck( + "GET", + f"/projects/{id:d}", + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + return github.Project.Project(self.__requester, headers, data, completed=True) + + def get_project_column(self, id: int) -> ProjectColumn: + """ + :calls: `GET /projects/columns/{column_id} `_ + """ + headers, data = self.__requester.requestJsonAndCheck( + "GET", + "/projects/columns/%d" % id, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + return github.ProjectColumn.ProjectColumn(self.__requester, headers, data, completed=True) + + def get_gist(self, id: str) -> Gist: + """ + :calls: `GET /gists/{id} `_ + """ + assert isinstance(id, str), id + headers, data = self.__requester.requestJsonAndCheck("GET", f"/gists/{id}") + return github.Gist.Gist(self.__requester, headers, data, completed=True) + + def get_gists(self, since: Opt[datetime] = NotSet) -> PaginatedList[Gist]: + """ + :calls: `GET /gists/public `_ + """ + assert since is NotSet or isinstance(since, datetime), since + url_parameters = dict() + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + return PaginatedList(github.Gist.Gist, self.__requester, "/gists/public", url_parameters) + + def get_global_advisory(self, ghsa_id: str) -> GlobalAdvisory: + """ + :calls: `GET /advisories/{ghsa_id} `_ + :param ghsa_id: string + :rtype: :class:`github.GlobalAdvisory.GlobalAdvisory` + """ + assert isinstance(ghsa_id, str), ghsa_id + ghsa_id = urllib.parse.quote(ghsa_id) + headers, data = self.__requester.requestJsonAndCheck("GET", f"/advisories/{ghsa_id}") + return github.GlobalAdvisory.GlobalAdvisory(self.__requester, headers, data) + + def get_global_advisories( + self, + type: Opt[str] = NotSet, + ghsa_id: Opt[str] = NotSet, + cve_id: Opt[str] = NotSet, + ecosystem: Opt[str] = NotSet, + severity: Opt[str] = NotSet, + cwes: list[Opt[str]] | Opt[str] = NotSet, + is_withdrawn: Opt[bool] = NotSet, + affects: list[str] | Opt[str] = NotSet, + published: Opt[str] = NotSet, + updated: Opt[str] = NotSet, + modified: Opt[str] = NotSet, + keywords: Opt[str] = NotSet, + before: Opt[str] = NotSet, + after: Opt[str] = NotSet, + per_page: Opt[str] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + ) -> PaginatedList[GlobalAdvisory]: + """ + :calls: `GET /advisories ` + :param type: Optional string + :param ghsa_id: Optional string + :param cve_id: Optional string + :param ecosystem: Optional string + :param severity: Optional string + :param cwes: Optional comma separated string or list of integer or string + :param is_withdrawn: Optional bool + :param affects: Optional comma separated string or list of string + :param published: Optional string + :param updated: Optional string + :param modified: Optional string + :param before: Optional string + :param after: Optional string + :param sort: Optional string + :param direction: Optional string + :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GlobalAdvisory.GlobalAdvisory` + """ + assert type is github.GithubObject.NotSet or isinstance(type, str), type + assert ghsa_id is github.GithubObject.NotSet or isinstance(ghsa_id, str) + assert cve_id is github.GithubObject.NotSet or isinstance(cve_id, str), cve_id + assert ecosystem is github.GithubObject.NotSet or isinstance(ecosystem, str), ecosystem + assert severity is github.GithubObject.NotSet or isinstance(severity, str), severity + assert cwes is github.GithubObject.NotSet or isinstance(cwes, list) or isinstance(cwes, str), cwes + assert is_withdrawn is github.GithubObject.NotSet or isinstance(is_withdrawn, bool), is_withdrawn + assert affects is github.GithubObject.NotSet or isinstance(affects, list) or isinstance(affects, str), affects + assert published is github.GithubObject.NotSet or isinstance(published, str), published + assert updated is github.GithubObject.NotSet or isinstance(updated, str), updated + assert modified is github.GithubObject.NotSet or isinstance(modified, str), modified + assert before is github.GithubObject.NotSet or isinstance(before, str), before + assert after is github.GithubObject.NotSet or isinstance(after, str), after + assert sort is github.GithubObject.NotSet or isinstance(sort, str), sort + assert direction is github.GithubObject.NotSet or isinstance(direction, str), direction + + url_parameters: dict[str, Opt[str | bool]] = dict() + if type is not github.GithubObject.NotSet: # pragma no branch (Should be covered) + assert type in ("reviewed", "unreviewed", "malware"), type + url_parameters["type"] = type + if ghsa_id is not github.GithubObject.NotSet: + url_parameters["ghsa_id"] = ghsa_id + if cve_id is not github.GithubObject.NotSet: + url_parameters["cve_id"] = cve_id + # Can be one of: actions, composer, erlang, go, maven, npm, nuget, other, pip, pub, rubygems, rust + # Not asserting in that list so that the package doesn't need to be updated when a new ecosystem is added + if ecosystem is not github.GithubObject.NotSet: + url_parameters["ecosystem"] = ecosystem + if severity is not github.GithubObject.NotSet: + assert severity in ("null", "low", "medium", "high", "critical"), severity + url_parameters["severity"] = severity + if cwes is not github.GithubObject.NotSet: + if isinstance(cwes, list): + cwes = ",".join([str(cwe) for cwe in cwes]) + url_parameters["cwes"] = cwes + if is_withdrawn is not github.GithubObject.NotSet: + url_parameters["is_withdrawn"] = is_withdrawn + if affects is not github.GithubObject.NotSet: + if isinstance(affects, list): + affects = ",".join(affects) + url_parameters["affects"] = affects + if published is not github.GithubObject.NotSet: + url_parameters["published"] = published + if updated is not github.GithubObject.NotSet: + url_parameters["updated"] = updated + if modified is not github.GithubObject.NotSet: + url_parameters["modified"] = modified + if before is not github.GithubObject.NotSet: + url_parameters["before"] = before + if after is not github.GithubObject.NotSet: + url_parameters["after"] = after + if sort is not github.GithubObject.NotSet: + assert sort in ("published", "updated"), sort + url_parameters["sort"] = sort + if direction is not github.GithubObject.NotSet: + assert direction in ("asc", "desc"), direction + url_parameters["direction"] = direction + return github.PaginatedList.PaginatedList( + github.GlobalAdvisory.GlobalAdvisory, + self.__requester, + "/advisories", + url_parameters, + ) + + def search_repositories( + self, + query: str, + sort: Opt[str] = NotSet, + order: Opt[str] = NotSet, + **qualifiers: Any, + ) -> PaginatedList[Repository]: + """ + :calls: `GET /search/repositories `_ + :param query: string + :param sort: string ('stars', 'forks', 'updated') + :param order: string ('asc', 'desc') + :param qualifiers: keyword dict query qualifiers + """ + assert isinstance(query, str), query + url_parameters = dict() + if sort is not NotSet: # pragma no branch (Should be covered) + assert sort in ("stars", "forks", "updated"), sort + url_parameters["sort"] = sort + if order is not NotSet: # pragma no branch (Should be covered) + assert order in ("asc", "desc"), order + url_parameters["order"] = order + + query_chunks = [] + if query: # pragma no branch (Should be covered) + query_chunks.append(query) + + for qualifier, value in qualifiers.items(): + query_chunks.append(f"{qualifier}:{value}") + + url_parameters["q"] = " ".join(query_chunks) + assert url_parameters["q"], "need at least one qualifier" + + return PaginatedList( + github.Repository.Repository, + self.__requester, + "/search/repositories", + url_parameters, + ) + + def search_users( + self, + query: str, + sort: Opt[str] = NotSet, + order: Opt[str] = NotSet, + **qualifiers: Any, + ) -> PaginatedList[NamedUser]: + """ + :calls: `GET /search/users `_ + :param query: string + :param sort: string ('followers', 'repositories', 'joined') + :param order: string ('asc', 'desc') + :param qualifiers: keyword dict query qualifiers + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + assert isinstance(query, str), query + url_parameters = dict() + if sort is not NotSet: + assert sort in ("followers", "repositories", "joined"), sort + url_parameters["sort"] = sort + if order is not NotSet: + assert order in ("asc", "desc"), order + url_parameters["order"] = order + + query_chunks = [] + if query: + query_chunks.append(query) + + for qualifier, value in qualifiers.items(): + query_chunks.append(f"{qualifier}:{value}") + + url_parameters["q"] = " ".join(query_chunks) + assert url_parameters["q"], "need at least one qualifier" + + return PaginatedList( + github.NamedUser.NamedUser, + self.__requester, + "/search/users", + url_parameters, + ) + + def search_issues( + self, + query: str, + sort: Opt[str] = NotSet, + order: Opt[str] = NotSet, + **qualifiers: Any, + ) -> PaginatedList[Issue]: + """ + :calls: `GET /search/issues `_ + :param query: string + :param sort: string ('comments', 'created', 'updated') + :param order: string ('asc', 'desc') + :param qualifiers: keyword dict query qualifiers + :rtype: :class:`PaginatedList` of :class:`github.Issue.Issue` + """ + assert isinstance(query, str), query + url_parameters = dict() + if sort is not NotSet: + assert sort in ("comments", "created", "updated"), sort + url_parameters["sort"] = sort + if order is not NotSet: + assert order in ("asc", "desc"), order + url_parameters["order"] = order + + query_chunks = [] + if query: # pragma no branch (Should be covered) + query_chunks.append(query) + + for qualifier, value in qualifiers.items(): + query_chunks.append(f"{qualifier}:{value}") + + url_parameters["q"] = " ".join(query_chunks) + assert url_parameters["q"], "need at least one qualifier" + + return PaginatedList(github.Issue.Issue, self.__requester, "/search/issues", url_parameters) + + def search_code( + self, + query: str, + sort: Opt[str] = NotSet, + order: Opt[str] = NotSet, + highlight: bool = False, + **qualifiers: Any, + ) -> PaginatedList[ContentFile]: + """ + :calls: `GET /search/code `_ + :param query: string + :param sort: string ('indexed') + :param order: string ('asc', 'desc') + :param highlight: boolean (True, False) + :param qualifiers: keyword dict query qualifiers + :rtype: :class:`PaginatedList` of :class:`github.ContentFile.ContentFile` + """ + assert isinstance(query, str), query + url_parameters = dict() + if sort is not NotSet: # pragma no branch (Should be covered) + assert sort in ("indexed",), sort + url_parameters["sort"] = sort + if order is not NotSet: # pragma no branch (Should be covered) + assert order in ("asc", "desc"), order + url_parameters["order"] = order + + query_chunks = [] + if query: # pragma no branch (Should be covered) + query_chunks.append(query) + + for qualifier, value in qualifiers.items(): + query_chunks.append(f"{qualifier}:{value}") + + url_parameters["q"] = " ".join(query_chunks) + assert url_parameters["q"], "need at least one qualifier" + + headers = {"Accept": Consts.highLightSearchPreview} if highlight else None + + return PaginatedList( + github.ContentFile.ContentFile, + self.__requester, + "/search/code", + url_parameters, + headers=headers, + ) + + def search_commits( + self, + query: str, + sort: Opt[str] = NotSet, + order: Opt[str] = NotSet, + **qualifiers: Any, + ) -> PaginatedList[Commit]: + """ + :calls: `GET /search/commits `_ + :param query: string + :param sort: string ('author-date', 'committer-date') + :param order: string ('asc', 'desc') + :param qualifiers: keyword dict query qualifiers + :rtype: :class:`PaginatedList` of :class:`github.Commit.Commit` + """ + assert isinstance(query, str), query + url_parameters = dict() + if sort is not NotSet: + assert sort in ("author-date", "committer-date"), sort + url_parameters["sort"] = sort + if order is not NotSet: + assert order in ("asc", "desc"), order + url_parameters["order"] = order + + query_chunks = [] + if query: + query_chunks.append(query) + + for qualifier, value in qualifiers.items(): + query_chunks.append(f"{qualifier}:{value}") + + url_parameters["q"] = " ".join(query_chunks) + assert url_parameters["q"], "need at least one qualifier" + + return PaginatedList( + github.Commit.Commit, + self.__requester, + "/search/commits", + url_parameters, + headers={"Accept": Consts.mediaTypeCommitSearchPreview}, + ) + + def search_topics(self, query: str, **qualifiers: Any) -> PaginatedList[Topic]: + """ + :calls: `GET /search/topics `_ + :param query: string + :param qualifiers: keyword dict query qualifiers + :rtype: :class:`PaginatedList` of :class:`github.Topic.Topic` + """ + assert isinstance(query, str), query + url_parameters = dict() + + query_chunks = [] + if query: # pragma no branch (Should be covered) + query_chunks.append(query) + + for qualifier, value in qualifiers.items(): + query_chunks.append(f"{qualifier}:{value}") + + url_parameters["q"] = " ".join(query_chunks) + assert url_parameters["q"], "need at least one qualifier" + + return PaginatedList( + github.Topic.Topic, + self.__requester, + "/search/topics", + url_parameters, + headers={"Accept": Consts.mediaTypeTopicsPreview}, + ) + + def render_markdown(self, text: str, context: Opt[Repository] = NotSet) -> str: + """ + :calls: `POST /markdown `_ + :param text: string + :param context: :class:`github.Repository.Repository` + :rtype: string + """ + assert isinstance(text, str), text + assert context is NotSet or isinstance(context, github.Repository.Repository), context + post_parameters = {"text": text} + if is_defined(context): + post_parameters["mode"] = "gfm" + post_parameters["context"] = context._identity + status, headers, data = self.__requester.requestJson("POST", "/markdown", input=post_parameters) + return data + + def get_hook(self, name: str) -> HookDescription: + """ + :calls: `GET /hooks/{name} `_ + """ + assert isinstance(name, str), name + name = urllib.parse.quote(name) + headers, attributes = self.__requester.requestJsonAndCheck("GET", f"/hooks/{name}") + return HookDescription(self.__requester, headers, attributes) + + def get_hooks(self) -> list[HookDescription]: + """ + :calls: `GET /hooks `_ + :rtype: list of :class:`github.HookDescription.HookDescription` + """ + headers, data = self.__requester.requestJsonAndCheck("GET", "/hooks") + return [HookDescription(self.__requester, headers, attributes) for attributes in data] + + def get_hook_delivery(self, hook_id: int, delivery_id: int) -> HookDelivery: + """ + :calls: `GET /hooks/{hook_id}/deliveries/{delivery_id} `_ + :param hook_id: integer + :param delivery_id: integer + :rtype: :class:`HookDelivery` + """ + assert isinstance(hook_id, int), hook_id + assert isinstance(delivery_id, int), delivery_id + headers, attributes = self.__requester.requestJsonAndCheck("GET", f"/hooks/{hook_id}/deliveries/{delivery_id}") + return HookDelivery(self.__requester, headers, attributes) + + def get_hook_deliveries(self, hook_id: int) -> list[HookDeliverySummary]: + """ + :calls: `GET /hooks/{hook_id}/deliveries `_ + :param hook_id: integer + :rtype: list of :class:`HookDeliverySummary` + """ + assert isinstance(hook_id, int), hook_id + headers, data = self.__requester.requestJsonAndCheck("GET", f"/hooks/{hook_id}/deliveries") + return [HookDeliverySummary(self.__requester, headers, attributes) for attributes in data] + + def get_gitignore_templates(self) -> list[str]: + """ + :calls: `GET /gitignore/templates `_ + """ + headers, data = self.__requester.requestJsonAndCheck("GET", "/gitignore/templates") + return data + + def get_gitignore_template(self, name: str) -> GitignoreTemplate: + """ + :calls: `GET /gitignore/templates/{name} `_ + """ + assert isinstance(name, str), name + name = urllib.parse.quote(name) + headers, attributes = self.__requester.requestJsonAndCheck("GET", f"/gitignore/templates/{name}") + return github.GitignoreTemplate.GitignoreTemplate(self.__requester, headers, attributes) + + def get_emojis(self) -> dict[str, str]: + """ + :calls: `GET /emojis `_ + :rtype: dictionary of type => url for emoji` + """ + headers, attributes = self.__requester.requestJsonAndCheck("GET", "/emojis") + return attributes + + def create_from_raw_data( + self, klass: type[TGithubObject], raw_data: dict[str, Any], headers: dict[str, str | int] | None = None + ) -> TGithubObject: + """ + Creates an object from raw_data previously obtained by :attr:`GithubObject.raw_data`, and optionally headers + previously obtained by :attr:`GithubObject.raw_headers`. + + :param klass: the class of the object to create + :param raw_data: dict + :param headers: dict + :rtype: instance of class ``klass`` + + """ + if headers is None: + headers = {} + + if issubclass(klass, CompletableGithubObject): + return klass(self.__requester, headers, raw_data, completed=True) # type: ignore + return klass(self.__requester, headers, raw_data) + + def dump(self, obj: GithubObject, file: BinaryIO, protocol: int = 0) -> None: + """ + Dumps (pickles) a PyGithub object to a file-like object. Some effort is made to not pickle sensitive + information like the Github credentials used in the :class:`Github` instance. But NO EFFORT is made to remove + sensitive information from the object's attributes. + + :param obj: the object to pickle :param file: the file-like object to pickle to :param protocol: the + `pickling protocol `_ + :param obj: the object to pickle :param file: the file-like object to pickle to :param protocol: the + `pickling protocol `_ :param obj: the object to pickle :param file: the file-like object to pickle to :param + protocol: the + `pickling protocol `_ + :param obj: the object to pickle + :param file: the file-like object to pickle to + :param protocol: the `pickling protocol `_ + :param obj: the object to pickle + :param file: the file-like object to pickle to + :param protocol: the `pickling protocol `_ + + """ + pickle.dump((obj.__class__, obj.raw_data, obj.raw_headers), file, protocol) + + def load(self, f: BinaryIO) -> Any: + """ + Loads (unpickles) a PyGithub object from a file-like object. + + :param f: the file-like object to unpickle from + :return: the unpickled object + + """ + return self.create_from_raw_data(*pickle.load(f)) + + def get_oauth_application(self, client_id: str, client_secret: str) -> ApplicationOAuth: + return github.ApplicationOAuth.ApplicationOAuth( + self.__requester, + headers={}, + attributes={"client_id": client_id, "client_secret": client_secret}, + ) + + def get_app(self, slug: Opt[str] = NotSet) -> GithubApp: + """ + :calls: `GET /apps/{slug} `_ or `GET /app `_ + """ + + if slug is NotSet: + # with no slug given, calling /app returns the authenticated app, + # including the actual /apps/{slug} + warnings.warn( + "Argument slug is mandatory, calling this method without the slug argument is deprecated, please use " + "github.GithubIntegration(auth=github.Auth.AppAuth(...)).get_app() instead", + category=DeprecationWarning, + ) + return GithubIntegration(**self.__requester.kwargs).get_app() + else: + assert isinstance(slug, str), slug + # with a slug given, we can lazily load the GithubApp + slug = urllib.parse.quote(slug) + return github.GithubApp.GithubApp(self.__requester, {}, {"url": f"/apps/{slug}"}, completed=False) diff --git a/python_embeded/Lib/site-packages/github/Membership.py b/python_embeded/Lib/site-packages/github/Membership.py new file mode 100644 index 0000000000000000000000000000000000000000..900fd94db7c132fd81391fd84ce9f56d584de55c --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Membership.py @@ -0,0 +1,131 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Matt Babineau # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Martijn Koster # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Pavan Kunisetty # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.NamedUser +import github.Organization +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + from github.Organization import Organization + + +class Membership(CompletableGithubObject): + """ + This class represents Membership of an organization. + + The reference can be found here + https://docs.github.com/en/rest/reference/orgs + + The OpenAPI schema can be found at + - /components/schemas/org-membership + + """ + + def _initAttributes(self) -> None: + self._organization: Attribute[Organization] = NotSet + self._organization_url: Attribute[str] = NotSet + self._permissions: Attribute[dict[str, Any]] = NotSet + self._role: Attribute[str] = NotSet + self._state: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + self._user: Attribute[NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"url": self._url.value}) + + @property + def organization(self) -> Organization: + self._completeIfNotSet(self._organization) + return self._organization.value + + @property + def organization_url(self) -> str: + self._completeIfNotSet(self._organization_url) + return self._organization_url.value + + @property + def permissions(self) -> dict[str, Any]: + self._completeIfNotSet(self._permissions) + return self._permissions.value + + @property + def role(self) -> str: + self._completeIfNotSet(self._role) + return self._role.value + + @property + def state(self) -> str: + self._completeIfNotSet(self._state) + return self._state.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def user(self) -> NamedUser: + self._completeIfNotSet(self._user) + return self._user.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "organization" in attributes: # pragma no branch + self._organization = self._makeClassAttribute(github.Organization.Organization, attributes["organization"]) + if "organization_url" in attributes: # pragma no branch + self._organization_url = self._makeStringAttribute(attributes["organization_url"]) + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeDictAttribute(attributes["permissions"]) + if "role" in attributes: # pragma no branch + self._role = self._makeStringAttribute(attributes["role"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/MergedUpstream.py b/python_embeded/Lib/site-packages/github/MergedUpstream.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb0390432ae2559bf15cfbb5cce415f69ec63db --- /dev/null +++ b/python_embeded/Lib/site-packages/github/MergedUpstream.py @@ -0,0 +1,68 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Thomas Cooper # +# Copyright 2025 Enrico Minack # +# Copyright 2025 Mikhail f. Shiryaev # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class MergedUpstream(NonCompletableGithubObject): + """ + This class represents a result of merge-upstream call. + + The OpenAPI schema can be found at + - /components/schemas/merged-upstream + + """ + + def _initAttributes(self) -> None: + self._merge_type: Attribute[str] = NotSet + self._base_branch: Attribute[str] = NotSet + self._message: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"message": self._message.value}) + + @property + def merge_type(self) -> str: + return self._merge_type.value + + @property + def base_branch(self) -> str: + return self._base_branch.value + + @property + def message(self) -> str: + return self._message.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "merge_type" in attributes: # pragma no branch + self._merge_type = self._makeStringAttribute(attributes["merge_type"]) + if "base_branch" in attributes: # pragma no branch + self._base_branch = self._makeStringAttribute(attributes["base_branch"]) + if "message" in attributes: # pragma no branch + self._message = self._makeStringAttribute(attributes["message"]) diff --git a/python_embeded/Lib/site-packages/github/Migration.py b/python_embeded/Lib/site-packages/github/Migration.py new file mode 100644 index 0000000000000000000000000000000000000000..f5de8e692330b2fffec68721b20f101ae33f585a --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Migration.py @@ -0,0 +1,266 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Michael Stead # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Nicolas Agustín Torres # +# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 per1234 # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Mark Amery # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import urllib.parse +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.NamedUser +import github.PaginatedList +import github.Repository +from github import Consts +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class Migration(CompletableGithubObject): + """ + This class represents Migrations. + + The reference can be found here + https://docs.github.com/en/rest/reference/migrations + + The OpenAPI schema can be found at + - /components/schemas/migration + + """ + + def _initAttributes(self) -> None: + self._archive_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._exclude: Attribute[list[str]] = NotSet + self._exclude_attachments: Attribute[bool] = NotSet + self._exclude_git_data: Attribute[bool] = NotSet + self._exclude_metadata: Attribute[bool] = NotSet + self._exclude_owner_projects: Attribute[bool] = NotSet + self._exclude_releases: Attribute[bool] = NotSet + self._guid: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._lock_repositories: Attribute[bool] = NotSet + self._node_id: Attribute[str] = NotSet + self._org_metadata_only: Attribute[bool] = NotSet + self._owner: Attribute[github.NamedUser.NamedUser] = NotSet + self._repositories: Attribute[list[github.Repository.Repository]] = NotSet + self._state: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"state": self._state.value, "url": self._url.value}) + + @property + def archive_url(self) -> str: + self._completeIfNotSet(self._archive_url) + return self._archive_url.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def exclude(self) -> list[str]: + self._completeIfNotSet(self._exclude) + return self._exclude.value + + @property + def exclude_attachments(self) -> bool: + self._completeIfNotSet(self._exclude_attachments) + return self._exclude_attachments.value + + @property + def exclude_git_data(self) -> bool: + self._completeIfNotSet(self._exclude_git_data) + return self._exclude_git_data.value + + @property + def exclude_metadata(self) -> bool: + self._completeIfNotSet(self._exclude_metadata) + return self._exclude_metadata.value + + @property + def exclude_owner_projects(self) -> bool: + self._completeIfNotSet(self._exclude_owner_projects) + return self._exclude_owner_projects.value + + @property + def exclude_releases(self) -> bool: + self._completeIfNotSet(self._exclude_releases) + return self._exclude_releases.value + + @property + def guid(self) -> str: + self._completeIfNotSet(self._guid) + return self._guid.value + + @property + def id(self) -> int: + return self._id.value + + @property + def lock_repositories(self) -> bool: + self._completeIfNotSet(self._repositories) + return self._lock_repositories.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def org_metadata_only(self) -> bool: + self._completeIfNotSet(self._org_metadata_only) + return self._org_metadata_only.value + + @property + def owner(self) -> github.NamedUser.NamedUser: + self._completeIfNotSet(self._owner) + return self._owner.value + + @property + def repositories(self) -> list[github.Repository.Repository]: + self._completeIfNotSet(self._repositories) + return self._repositories.value + + @property + def state(self) -> str: + self._completeIfNotSet(self._guid) + return self._state.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def get_status(self) -> str: + """ + :calls: `GET /user/migrations/{migration_id} `_ + """ + headers, data = self._requester.requestJsonAndCheck( + "GET", self.url, headers={"Accept": Consts.mediaTypeMigrationPreview} + ) + self._useAttributes(data) + return self.state + + def get_archive_url(self) -> str: + """ + :calls: `GET /user/migrations/{migration_id}/archive `_ + """ + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/archive", + headers={"Accept": Consts.mediaTypeMigrationPreview}, + ) + return data["data"] + + def delete(self) -> None: + """ + :calls: `DELETE /user/migrations/{migration_id}/archive `_ + """ + headers, data = self._requester.requestJsonAndCheck( + "DELETE", + f"{self.url}/archive", + headers={"Accept": Consts.mediaTypeMigrationPreview}, + ) + + def unlock_repo(self, repo_name: str) -> None: + """ + :calls: `DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock `_ + """ + assert isinstance(repo_name, str), repo_name + repo_name = urllib.parse.quote(repo_name) + headers, data = self._requester.requestJsonAndCheck( + "DELETE", + f"{self.url}/repos/{repo_name}/lock", + headers={"Accept": Consts.mediaTypeMigrationPreview}, + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "archive_url" in attributes: # pragma no branch + self._archive_url = self._makeStringAttribute(attributes["archive_url"]) + if "created_at" in attributes: + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "exclude" in attributes: # pragma no branch + self._exclude = self._makeListOfStringsAttribute(attributes["exclude"]) + if "exclude_attachments" in attributes: + self._exclude_attachments = self._makeBoolAttribute(attributes["exclude_attachments"]) + if "exclude_git_data" in attributes: # pragma no branch + self._exclude_git_data = self._makeBoolAttribute(attributes["exclude_git_data"]) + if "exclude_metadata" in attributes: # pragma no branch + self._exclude_metadata = self._makeBoolAttribute(attributes["exclude_metadata"]) + if "exclude_owner_projects" in attributes: # pragma no branch + self._exclude_owner_projects = self._makeBoolAttribute(attributes["exclude_owner_projects"]) + if "exclude_releases" in attributes: # pragma no branch + self._exclude_releases = self._makeBoolAttribute(attributes["exclude_releases"]) + if "guid" in attributes: + self._guid = self._makeStringAttribute(attributes["guid"]) + if "id" in attributes: + self._id = self._makeIntAttribute(attributes["id"]) + if "lock_repositories" in attributes: + self._lock_repositories = self._makeBoolAttribute(attributes["lock_repositories"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "org_metadata_only" in attributes: # pragma no branch + self._org_metadata_only = self._makeBoolAttribute(attributes["org_metadata_only"]) + if "owner" in attributes: + self._owner = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["owner"]) + if "repositories" in attributes: + self._repositories = self._makeListOfClassesAttribute( + github.Repository.Repository, attributes["repositories"] + ) + if "state" in attributes: + self._state = self._makeStringAttribute(attributes["state"]) + if "updated_at" in attributes: + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/Milestone.py b/python_embeded/Lib/site-packages/github/Milestone.py new file mode 100644 index 0000000000000000000000000000000000000000..844f8e35b09d6c9ee9e9e25f7eeb78f904ad0a9b --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Milestone.py @@ -0,0 +1,243 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Michell Stuttgart # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import date, datetime +from typing import Any + +import github.GithubObject +import github.Label +import github.NamedUser +import github.PaginatedList +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_defined +from github.PaginatedList import PaginatedList + + +class Milestone(CompletableGithubObject): + """ + This class represents Milestones. + + The reference can be found here + https://docs.github.com/en/rest/reference/issues#milestones + + The OpenAPI schema can be found at + - /components/schemas/issue-event-milestone + - /components/schemas/milestone + - /components/schemas/nullable-milestone + + """ + + def _initAttributes(self) -> None: + self._closed_at: Attribute[datetime] = NotSet + self._closed_issues: Attribute[int] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._creator: Attribute[github.NamedUser.NamedUser] = NotSet + self._description: Attribute[str] = NotSet + self._due_on: Attribute[datetime] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._labels_url: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._number: Attribute[int] = NotSet + self._open_issues: Attribute[int] = NotSet + self._state: Attribute[str] = NotSet + self._title: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"number": self._number.value, "title": self._title.value}) + + @property + def _identity(self) -> int: + return self.number + + @property + def closed_at(self) -> datetime: + self._completeIfNotSet(self._closed_at) + return self._closed_at.value + + @property + def closed_issues(self) -> int: + self._completeIfNotSet(self._closed_issues) + return self._closed_issues.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def creator(self) -> github.NamedUser.NamedUser: + self._completeIfNotSet(self._creator) + return self._creator.value + + @property + def description(self) -> str: + self._completeIfNotSet(self._description) + return self._description.value + + @property + def due_on(self) -> datetime | None: + self._completeIfNotSet(self._due_on) + return self._due_on.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def labels_url(self) -> str: + self._completeIfNotSet(self._labels_url) + return self._labels_url.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def number(self) -> int: + self._completeIfNotSet(self._number) + return self._number.value + + @property + def open_issues(self) -> int: + self._completeIfNotSet(self._open_issues) + return self._open_issues.value + + @property + def state(self) -> str: + self._completeIfNotSet(self._state) + return self._state.value + + @property + def title(self) -> str: + self._completeIfNotSet(self._title) + return self._title.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def delete(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/milestones/{number} `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def edit( + self, title: str, state: Opt[str] = NotSet, description: Opt[str] = NotSet, due_on: Opt[date] = NotSet + ) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/milestones/{number} `_ + """ + assert isinstance(title, str), title + assert state is NotSet or isinstance(state, str), state + assert description is NotSet or isinstance(description, str), description + assert due_on is NotSet or isinstance(due_on, date), due_on + post_parameters = NotSet.remove_unset_items( + { + "title": title, + "state": state, + "description": description, + } + ) + + if is_defined(due_on): + post_parameters["due_on"] = due_on.strftime("%Y-%m-%d") + + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def get_labels(self) -> PaginatedList[github.Label.Label]: + """ + :calls: `GET /repos/{owner}/{repo}/milestones/{number}/labels `_ + """ + return PaginatedList(github.Label.Label, self._requester, f"{self.url}/labels", None) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "closed_at" in attributes: # pragma no branch + self._closed_at = self._makeDatetimeAttribute(attributes["closed_at"]) + if "closed_issues" in attributes: # pragma no branch + self._closed_issues = self._makeIntAttribute(attributes["closed_issues"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "creator" in attributes: # pragma no branch + self._creator = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["creator"]) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "due_on" in attributes: # pragma no branch + self._due_on = self._makeDatetimeAttribute(attributes["due_on"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "labels_url" in attributes: # pragma no branch + self._labels_url = self._makeStringAttribute(attributes["labels_url"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "number" in attributes: # pragma no branch + self._number = self._makeIntAttribute(attributes["number"]) + if "open_issues" in attributes: # pragma no branch + self._open_issues = self._makeIntAttribute(attributes["open_issues"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/NamedEnterpriseUser.py b/python_embeded/Lib/site-packages/github/NamedEnterpriseUser.py new file mode 100644 index 0000000000000000000000000000000000000000..f0f1100eba49a8e83983ebfdc17bd378acbadc82 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/NamedEnterpriseUser.py @@ -0,0 +1,204 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2023 Enrico Minack # +# Copyright 2023 YugoHino # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class NamedEnterpriseUser(CompletableGithubObject): + """ + This class represents NamedEnterpriseUsers. + + The reference can be found here + https://docs.github.com/en/enterprise-cloud@latest/rest/enterprise-admin/license#list-enterprise-consumed-licenses + + """ + + def _initAttributes(self) -> None: + self._enterprise_server_primary_emails: Attribute[list] = NotSet + self._enterprise_server_user: Attribute[bool] = NotSet + self._enterprise_server_user_ids: Attribute[list] = NotSet + self._github_com_enterprise_roles: Attribute[list] = NotSet + self._github_com_login: Attribute[str] = NotSet + self._github_com_member_roles: Attribute[list] = NotSet + self._github_com_name: Attribute[str] = NotSet + self._github_com_orgs_with_pending_invites: Attribute[list] = NotSet + self._github_com_profile: Attribute[str] = NotSet + self._github_com_saml_name_id: Attribute[str] = NotSet + self._github_com_two_factor_auth: Attribute[bool] = NotSet + self._github_com_user: Attribute[bool] = NotSet + self._github_com_verified_domain_emails: Attribute[list] = NotSet + self._license_type: Attribute[str] = NotSet + self._total_user_accounts: Attribute[int] = NotSet + self._visual_studio_license_status: Attribute[str] = NotSet + self._visual_studio_subscription_email: Attribute[str] = NotSet + self._visual_studio_subscription_user: Attribute[bool] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"login": self._github_com_login.value}) + + @property + def enterprise_server_primary_emails(self) -> list: + self._completeIfNotSet(self._enterprise_server_primary_emails) + return self._enterprise_server_primary_emails.value + + @property + def enterprise_server_user(self) -> bool: + self._completeIfNotSet(self._enterprise_server_user) + return self._enterprise_server_user.value + + @property + def enterprise_server_user_ids(self) -> list: + self._completeIfNotSet(self._enterprise_server_user_ids) + return self._enterprise_server_user_ids.value + + @property + def github_com_enterprise_roles(self) -> list: + self._completeIfNotSet(self._github_com_enterprise_roles) + return self._github_com_enterprise_roles.value + + @property + def github_com_login(self) -> str: + self._completeIfNotSet(self._github_com_login) + return self._github_com_login.value + + @property + def github_com_member_roles(self) -> list: + self._completeIfNotSet(self._github_com_member_roles) + return self._github_com_member_roles.value + + @property + def github_com_name(self) -> str: + self._completeIfNotSet(self._github_com_name) + return self._github_com_name.value + + @property + def github_com_orgs_with_pending_invites(self) -> list: + self._completeIfNotSet(self._github_com_orgs_with_pending_invites) + return self._github_com_orgs_with_pending_invites.value + + @property + def github_com_profile(self) -> str: + self._completeIfNotSet(self._github_com_profile) + return self._github_com_profile.value + + @property + def github_com_saml_name_id(self) -> str: + self._completeIfNotSet(self._github_com_saml_name_id) + return self._github_com_saml_name_id.value + + @property + def github_com_two_factor_auth(self) -> bool: + self._completeIfNotSet(self._github_com_two_factor_auth) + return self._github_com_two_factor_auth.value + + @property + def github_com_user(self) -> bool: + self._completeIfNotSet(self._github_com_user) + return self._github_com_user.value + + @property + def github_com_verified_domain_emails(self) -> list: + self._completeIfNotSet(self._github_com_verified_domain_emails) + return self._github_com_verified_domain_emails.value + + @property + def license_type(self) -> str: + self._completeIfNotSet(self._license_type) + return self._license_type.value + + @property + def total_user_accounts(self) -> int: + self._completeIfNotSet(self._total_user_accounts) + return self._total_user_accounts.value + + @property + def visual_studio_license_status(self) -> str: + self._completeIfNotSet(self._visual_studio_license_status) + return self._visual_studio_license_status.value + + @property + def visual_studio_subscription_email(self) -> str: + self._completeIfNotSet(self._visual_studio_subscription_email) + return self._visual_studio_subscription_email.value + + @property + def visual_studio_subscription_user(self) -> bool: + self._completeIfNotSet(self._visual_studio_subscription_user) + return self._visual_studio_subscription_user.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "enterprise_server_primary_emails" in attributes: # pragma no branch + self._enterprise_server_primary_emails = self._makeListOfStringsAttribute( + attributes["enterprise_server_primary_emails"] + ) + if "enterprise_server_user" in attributes: # pragma no branch + self._enterprise_server_user = self._makeBoolAttribute(attributes["enterprise_server_user"]) + if "enterprise_server_user_ids" in attributes: # pragma no branch + self._enterprise_server_user_ids = self._makeListOfStringsAttribute( + attributes["enterprise_server_user_ids"] + ) + if "github_com_enterprise_roles" in attributes: # pragma no branch + self._github_com_enterprise_roles = self._makeListOfStringsAttribute( + attributes["github_com_enterprise_roles"] + ) + if "github_com_login" in attributes: # pragma no branch + self._github_com_login = self._makeStringAttribute(attributes["github_com_login"]) + if "github_com_member_roles" in attributes: # pragma no branch + self._github_com_member_roles = self._makeListOfStringsAttribute(attributes["github_com_member_roles"]) + if "github_com_name" in attributes: # pragma no branch + self._github_com_name = self._makeStringAttribute(attributes["github_com_name"]) + if "github_com_orgs_with_pending_invites" in attributes: # pragma no branch + self._github_com_orgs_with_pending_invites = self._makeListOfStringsAttribute( + attributes["github_com_orgs_with_pending_invites"] + ) + if "github_com_profile" in attributes: # pragma no branch + self._github_com_profile = self._makeStringAttribute(attributes["github_com_profile"]) + if "github_com_saml_name_id" in attributes: # pragma no branch + self._github_com_saml_name_id = self._makeStringAttribute(attributes["github_com_saml_name_id"]) + if "github_com_two_factor_auth" in attributes: # pragma no branch + self._github_com_two_factor_auth = self._makeBoolAttribute(attributes["github_com_two_factor_auth"]) + if "github_com_user" in attributes: # pragma no branch + self._github_com_user = self._makeBoolAttribute(attributes["github_com_user"]) + if "github_com_verified_domain_emails" in attributes: # pragma no branch + self._github_com_verified_domain_emails = self._makeListOfStringsAttribute( + attributes["github_com_verified_domain_emails"] + ) + if "license_type" in attributes: # pragma no branch + self._license_type = self._makeStringAttribute(attributes["license_type"]) + if "total_user_accounts" in attributes: # pragma no branch + self._total_user_accounts = self._makeIntAttribute(attributes["total_user_accounts"]) + if "visual_studio_license_status" in attributes: # pragma no branch + self._visual_studio_license_status = self._makeStringAttribute(attributes["visual_studio_license_status"]) + if "visual_studio_subscription_email" in attributes: # pragma no branch + self._visual_studio_subscription_email = self._makeStringAttribute( + attributes["visual_studio_subscription_email"] + ) + if "visual_studio_subscription_user" in attributes: # pragma no branch + self._visual_studio_subscription_user = self._makeBoolAttribute( + attributes["visual_studio_subscription_user"] + ) diff --git a/python_embeded/Lib/site-packages/github/NamedUser.py b/python_embeded/Lib/site-packages/github/NamedUser.py new file mode 100644 index 0000000000000000000000000000000000000000..d79229c2bebed9bbd7f06edde620ccde84196bbc --- /dev/null +++ b/python_embeded/Lib/site-packages/github/NamedUser.py @@ -0,0 +1,693 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Steve English # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Simon # +# Copyright 2018 Bruce Richardson # +# Copyright 2018 Iraquitan Cordeiro Filho # +# Copyright 2018 Riccardo Pittau # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Victor Granic # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 namc # +# Copyright 2018 sfdye # +# Copyright 2019 Pavan Kunisetty # +# Copyright 2019 Shibasis Patel # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Surya Teja <94suryateja@gmail.com> # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Anuj Bansal # +# Copyright 2020 Daniel Haas # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Mark Amery # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import urllib.parse +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.Event +import github.Gist +import github.GithubObject +import github.Organization +import github.PaginatedList +import github.Permissions +import github.Plan +import github.Repository +from github import Consts +from github.GithubObject import Attribute, NotSet, Opt, is_defined +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.Event import Event + from github.Gist import Gist + from github.Membership import Membership + from github.Organization import Organization + from github.Permissions import Permissions + from github.Plan import Plan + from github.Project import Project + from github.Repository import Repository + from github.UserKey import UserKey + + +class NamedUser(github.GithubObject.CompletableGithubObject): + """ + This class represents NamedUsers. + + The reference can be found here + https://docs.github.com/en/rest/reference/users#get-a-user + + The OpenAPI schema can be found at + - /components/schemas/actor + - /components/schemas/collaborator + - /components/schemas/contributor + - /components/schemas/nullable-simple-user + - /components/schemas/public-user + - /components/schemas/simple-user + - /components/schemas/user-search-result-item + + """ + + def _initAttributes(self) -> None: + self._avatar_url: Attribute[str] = NotSet + self._bio: Attribute[str | None] = NotSet + self._blog: Attribute[str | None] = NotSet + self._collaborators: Attribute[int] = NotSet + self._company: Attribute[str | None] = NotSet + self._contributions: Attribute[int] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._disk_usage: Attribute[int] = NotSet + self._display_login: Attribute[str] = NotSet + self._email: Attribute[str | None] = NotSet + self._events_url: Attribute[str] = NotSet + self._followers: Attribute[int] = NotSet + self._followers_url: Attribute[str] = NotSet + self._following: Attribute[int] = NotSet + self._following_url: Attribute[str] = NotSet + self._gists_url: Attribute[str] = NotSet + self._gravatar_id: Attribute[str | None] = NotSet + self._hireable: Attribute[bool | None] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._invitation_teams_url: Attribute[str] = NotSet + self._inviter: Attribute[NamedUser] = NotSet + self._location: Attribute[str | None] = NotSet + self._login: Attribute[str] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._notification_email: Attribute[str] = NotSet + self._organizations_url: Attribute[str] = NotSet + self._owned_private_repos: Attribute[int] = NotSet + self._permissions: Attribute[Permissions] = NotSet + self._plan: Attribute[Plan] = NotSet + self._private_gists: Attribute[int] = NotSet + self._public_gists: Attribute[int] = NotSet + self._public_repos: Attribute[int] = NotSet + self._received_events_url: Attribute[str] = NotSet + self._repos_url: Attribute[str] = NotSet + self._role: Attribute[str] = NotSet + self._role_name: Attribute[str] = NotSet + self._score: Attribute[float] = NotSet + self._site_admin: Attribute[bool] = NotSet + self._starred_at: Attribute[str] = NotSet + self._starred_url: Attribute[str] = NotSet + self._subscriptions_url: Attribute[str] = NotSet + self._suspended_at: Attribute[datetime | None] = NotSet + self._team_count: Attribute[int] = NotSet + self._text_matches: Attribute[dict[str, Any]] = NotSet + self._total_private_repos: Attribute[int] = NotSet + self._twitter_username: Attribute[str | None] = NotSet + self._type: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._user_view_type: Attribute[str] = NotSet + + def __eq__(self, other: Any) -> bool: + return isinstance(other, type(self)) and self.login == other.login and self.id == other.id + + def __hash__(self) -> int: + return hash((self.id, self.login)) + + def __repr__(self) -> str: + return self.get__repr__({"login": self._login.value}) + + @property + def _identity(self) -> str: + return self.login + + @property + def avatar_url(self) -> str: + self._completeIfNotSet(self._avatar_url) + return self._avatar_url.value + + @property + def bio(self) -> str | None: + self._completeIfNotSet(self._bio) + return self._bio.value + + @property + def blog(self) -> str | None: + self._completeIfNotSet(self._blog) + return self._blog.value + + @property + def collaborators(self) -> int | None: + self._completeIfNotSet(self._collaborators) + return self._collaborators.value + + @property + def company(self) -> str | None: + self._completeIfNotSet(self._company) + return self._company.value + + @property + def contributions(self) -> int: + self._completeIfNotSet(self._contributions) + return self._contributions.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def disk_usage(self) -> int: + self._completeIfNotSet(self._disk_usage) + return self._disk_usage.value + + @property + def display_login(self) -> str: + return self._display_login.value + + @property + def email(self) -> str | None: + self._completeIfNotSet(self._email) + return self._email.value + + @property + def events_url(self) -> str: + self._completeIfNotSet(self._events_url) + return self._events_url.value + + @property + def followers(self) -> int: + self._completeIfNotSet(self._followers) + return self._followers.value + + @property + def followers_url(self) -> str: + self._completeIfNotSet(self._followers_url) + return self._followers_url.value + + @property + def following(self) -> int: + self._completeIfNotSet(self._following) + return self._following.value + + @property + def following_url(self) -> str: + self._completeIfNotSet(self._following_url) + return self._following_url.value + + @property + def gists_url(self) -> str: + self._completeIfNotSet(self._gists_url) + return self._gists_url.value + + @property + def gravatar_id(self) -> str | None: + self._completeIfNotSet(self._gravatar_id) + return self._gravatar_id.value + + @property + def hireable(self) -> bool | None: + self._completeIfNotSet(self._hireable) + return self._hireable.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def invitation_teams_url(self) -> str: + self._completeIfNotSet(self._invitation_teams_url) + return self._invitation_teams_url.value + + @property + def inviter(self) -> NamedUser: + self._completeIfNotSet(self._inviter) + return self._inviter.value + + @property + def location(self) -> str | None: + self._completeIfNotSet(self._location) + return self._location.value + + @property + def login(self) -> str: + self._completeIfNotSet(self._login) + return self._login.value + + @property + def name(self) -> str | None: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def notification_email(self) -> str: + return self._notification_email.value + + @property + def organizations_url(self) -> str: + self._completeIfNotSet(self._organizations_url) + return self._organizations_url.value + + @property + def owned_private_repos(self) -> int | None: + self._completeIfNotSet(self._owned_private_repos) + return self._owned_private_repos.value + + @property + def permissions(self) -> Permissions: + self._completeIfNotSet(self._permissions) + return self._permissions.value + + @property + def plan(self) -> Plan | None: + self._completeIfNotSet(self._plan) + return self._plan.value + + @property + def private_gists(self) -> int | None: + self._completeIfNotSet(self._private_gists) + return self._private_gists.value + + @property + def public_gists(self) -> int: + self._completeIfNotSet(self._public_gists) + return self._public_gists.value + + @property + def public_repos(self) -> int: + self._completeIfNotSet(self._public_repos) + return self._public_repos.value + + @property + def received_events_url(self) -> str: + self._completeIfNotSet(self._received_events_url) + return self._received_events_url.value + + @property + def repos_url(self) -> str: + self._completeIfNotSet(self._repos_url) + return self._repos_url.value + + @property + def role(self) -> str: + self._completeIfNotSet(self._role) + return self._role.value + + @property + def role_name(self) -> str: + return self._role_name.value + + @property + def score(self) -> float: + return self._score.value + + @property + def site_admin(self) -> bool: + self._completeIfNotSet(self._site_admin) + return self._site_admin.value + + @property + def starred_at(self) -> str: + return self._starred_at.value + + @property + def starred_url(self) -> str: + self._completeIfNotSet(self._starred_url) + return self._starred_url.value + + @property + def subscriptions_url(self) -> str: + self._completeIfNotSet(self._subscriptions_url) + return self._subscriptions_url.value + + @property + def suspended_at(self) -> datetime | None: + self._completeIfNotSet(self._suspended_at) + return self._suspended_at.value + + @property + def team_count(self) -> int: + self._completeIfNotSet(self._team_count) + return self._team_count.value + + @property + def text_matches(self) -> dict[str, Any]: + return self._text_matches.value + + @property + def total_private_repos(self) -> int | None: + self._completeIfNotSet(self._total_private_repos) + return self._total_private_repos.value + + @property + def twitter_username(self) -> str | None: + self._completeIfNotSet(self._twitter_username) + return self._twitter_username.value + + @property + def type(self) -> str: + self._completeIfNotSet(self._type) + return self._type.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def user_view_type(self) -> str: + return self._user_view_type.value + + def get_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /users/{user}/events `_ + """ + return github.PaginatedList.PaginatedList(github.Event.Event, self._requester, f"{self.url}/events", None) + + def get_followers(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /users/{user}/followers `_ + """ + return github.PaginatedList.PaginatedList(NamedUser, self._requester, f"{self.url}/followers", None) + + def get_following(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /users/{user}/following `_ + """ + return github.PaginatedList.PaginatedList(NamedUser, self._requester, f"{self.url}/following", None) + + def get_gists(self, since: Opt[datetime] = NotSet) -> PaginatedList[Gist]: + """ + :calls: `GET /users/{user}/gists `_ + """ + assert since is NotSet or isinstance(since, datetime), since + url_parameters = dict() + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + return github.PaginatedList.PaginatedList( + github.Gist.Gist, self._requester, f"{self.url}/gists", url_parameters + ) + + def get_keys(self) -> PaginatedList[UserKey]: + """ + :calls: `GET /users/{user}/keys `_ + """ + return github.PaginatedList.PaginatedList(github.UserKey.UserKey, self._requester, f"{self.url}/keys", None) + + def get_orgs(self) -> PaginatedList[Organization]: + """ + :calls: `GET /users/{user}/orgs `_ + """ + return github.PaginatedList.PaginatedList( + github.Organization.Organization, self._requester, f"{self.url}/orgs", None + ) + + def get_projects(self, state: str = "open") -> PaginatedList[Project]: + """ + :calls: `GET /users/{user}/projects `_ + """ + assert isinstance(state, str), state + url_parameters = {"state": state} + return github.PaginatedList.PaginatedList( + github.Project.Project, + self._requester, + f"{self.url}/projects", + url_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + + def get_public_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /users/{user}/events/public `_ + """ + return github.PaginatedList.PaginatedList( + github.Event.Event, self._requester, f"{self.url}/events/public", None + ) + + def get_public_received_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /users/{user}/received_events/public `_ + """ + return github.PaginatedList.PaginatedList( + github.Event.Event, + self._requester, + f"{self.url}/received_events/public", + None, + ) + + def get_received_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /users/{user}/received_events `_ + """ + return github.PaginatedList.PaginatedList( + github.Event.Event, self._requester, f"{self.url}/received_events", None + ) + + def get_repo(self, name: str) -> Repository: + """ + :calls: `GET /repos/{owner}/{repo} `_ + """ + assert isinstance(name, str), name + headers, data = self._requester.requestJsonAndCheck("GET", f"/repos/{self.login}/{name}") + return github.Repository.Repository(self._requester, headers, data, completed=True) + + def get_repos( + self, + type: Opt[str] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + ) -> PaginatedList[Repository]: + """ + :calls: `GET /users/{user}/repos `_ + """ + assert type is NotSet or isinstance(type, str), type + assert sort is NotSet or isinstance(sort, str), sort + assert direction is NotSet or isinstance(direction, str), direction + url_parameters = dict() + if type is not NotSet: + url_parameters["type"] = type + if sort is not NotSet: + url_parameters["sort"] = sort + if direction is not NotSet: + url_parameters["direction"] = direction + return github.PaginatedList.PaginatedList( + github.Repository.Repository, + self._requester, + f"{self.url}/repos", + url_parameters, + ) + + def get_starred(self) -> PaginatedList[Repository]: + """ + :calls: `GET /users/{user}/starred `_ + """ + return github.PaginatedList.PaginatedList( + github.Repository.Repository, self._requester, f"{self.url}/starred", None + ) + + def get_subscriptions(self) -> PaginatedList[Repository]: + """ + :calls: `GET /users/{user}/subscriptions `_ + """ + return github.PaginatedList.PaginatedList( + github.Repository.Repository, + self._requester, + f"{self.url}/subscriptions", + None, + ) + + def get_watched(self) -> PaginatedList[Repository]: + """ + :calls: `GET /users/{user}/watched `_ + """ + return github.PaginatedList.PaginatedList( + github.Repository.Repository, self._requester, f"{self.url}/watched", None + ) + + def has_in_following(self, following: NamedUser) -> bool: + """ + :calls: `GET /users/{user}/following/{target_user} `_ + """ + assert isinstance(following, github.NamedUser.NamedUser), following + status, headers, data = self._requester.requestJson("GET", f"{self.url}/following/{following._identity}") + return status == 204 + + def get_organization_membership(self, org: str | Organization) -> Membership: + """ + :calls: `GET /orgs/{org}/memberships/{username} `_ + """ + assert isinstance(org, str) or isinstance(org, github.Organization.Organization), org + if isinstance(org, github.Organization.Organization): + org = org.login # type: ignore + org = urllib.parse.quote(org) + headers, data = self._requester.requestJsonAndCheck("GET", f"/orgs/{org}/memberships/{self.login}") + return github.Membership.Membership(self._requester, headers, data, completed=True) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "avatar_url" in attributes: # pragma no branch + self._avatar_url = self._makeStringAttribute(attributes["avatar_url"]) + if "bio" in attributes: # pragma no branch + self._bio = self._makeStringAttribute(attributes["bio"]) + if "blog" in attributes: # pragma no branch + self._blog = self._makeStringAttribute(attributes["blog"]) + if "collaborators" in attributes: # pragma no branch + self._collaborators = self._makeIntAttribute(attributes["collaborators"]) + if "company" in attributes: # pragma no branch + self._company = self._makeStringAttribute(attributes["company"]) + if "contributions" in attributes: # pragma no branch + self._contributions = self._makeIntAttribute(attributes["contributions"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "disk_usage" in attributes: # pragma no branch + self._disk_usage = self._makeIntAttribute(attributes["disk_usage"]) + if "display_login" in attributes: # pragma no branch + self._display_login = self._makeStringAttribute(attributes["display_login"]) + if "email" in attributes: # pragma no branch + self._email = self._makeStringAttribute(attributes["email"]) + if "events_url" in attributes: # pragma no branch + self._events_url = self._makeStringAttribute(attributes["events_url"]) + if "followers" in attributes: # pragma no branch + self._followers = self._makeIntAttribute(attributes["followers"]) + if "followers_url" in attributes: # pragma no branch + self._followers_url = self._makeStringAttribute(attributes["followers_url"]) + if "following" in attributes: # pragma no branch + self._following = self._makeIntAttribute(attributes["following"]) + if "following_url" in attributes: # pragma no branch + self._following_url = self._makeStringAttribute(attributes["following_url"]) + if "gists_url" in attributes: # pragma no branch + self._gists_url = self._makeStringAttribute(attributes["gists_url"]) + if "gravatar_id" in attributes: # pragma no branch + self._gravatar_id = self._makeStringAttribute(attributes["gravatar_id"]) + if "hireable" in attributes: # pragma no branch + self._hireable = self._makeBoolAttribute(attributes["hireable"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "invitation_teams_url" in attributes: # pragma no branch + self._invitation_teams_url = self._makeStringAttribute(attributes["invitation_teams_url"]) + if "inviter" in attributes: # pragma no branch + self._inviter = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["inviter"]) + if "location" in attributes: # pragma no branch + self._location = self._makeStringAttribute(attributes["location"]) + if "login" in attributes: # pragma no branch + self._login = self._makeStringAttribute(attributes["login"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "notification_email" in attributes: # pragma no branch + self._notification_email = self._makeStringAttribute(attributes["notification_email"]) + if "organizations_url" in attributes: # pragma no branch + self._organizations_url = self._makeStringAttribute(attributes["organizations_url"]) + if "owned_private_repos" in attributes: # pragma no branch + self._owned_private_repos = self._makeIntAttribute(attributes["owned_private_repos"]) + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeClassAttribute(github.Permissions.Permissions, attributes["permissions"]) + if "plan" in attributes: # pragma no branch + self._plan = self._makeClassAttribute(github.Plan.Plan, attributes["plan"]) + if "private_gists" in attributes: # pragma no branch + self._private_gists = self._makeIntAttribute(attributes["private_gists"]) + if "public_gists" in attributes: # pragma no branch + self._public_gists = self._makeIntAttribute(attributes["public_gists"]) + if "public_repos" in attributes: # pragma no branch + self._public_repos = self._makeIntAttribute(attributes["public_repos"]) + if "received_events_url" in attributes: # pragma no branch + self._received_events_url = self._makeStringAttribute(attributes["received_events_url"]) + if "repos_url" in attributes: # pragma no branch + self._repos_url = self._makeStringAttribute(attributes["repos_url"]) + if "role" in attributes: # pragma no branch + self._role = self._makeStringAttribute(attributes["role"]) + if "role_name" in attributes: # pragma no branch + self._role_name = self._makeStringAttribute(attributes["role_name"]) + if "score" in attributes: # pragma no branch + self._score = self._makeFloatAttribute(attributes["score"]) + if "site_admin" in attributes: # pragma no branch + self._site_admin = self._makeBoolAttribute(attributes["site_admin"]) + if "starred_at" in attributes: # pragma no branch + self._starred_at = self._makeStringAttribute(attributes["starred_at"]) + if "starred_url" in attributes: # pragma no branch + self._starred_url = self._makeStringAttribute(attributes["starred_url"]) + if "subscriptions_url" in attributes: # pragma no branch + self._subscriptions_url = self._makeStringAttribute(attributes["subscriptions_url"]) + if "suspended_at" in attributes: # pragma no branch + self._suspended_at = self._makeDatetimeAttribute(attributes["suspended_at"]) + if "team_count" in attributes: + self._team_count = self._makeIntAttribute(attributes["team_count"]) + if "text_matches" in attributes: # pragma no branch + self._text_matches = self._makeDictAttribute(attributes["text_matches"]) + if "total_private_repos" in attributes: # pragma no branch + self._total_private_repos = self._makeIntAttribute(attributes["total_private_repos"]) + if "twitter_username" in attributes: # pragma no branch + self._twitter_username = self._makeStringAttribute(attributes["twitter_username"]) + if "type" in attributes: # pragma no branch + self._type = self._makeStringAttribute(attributes["type"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "user_view_type" in attributes: # pragma no branch + self._user_view_type = self._makeStringAttribute(attributes["user_view_type"]) diff --git a/python_embeded/Lib/site-packages/github/Notification.py b/python_embeded/Lib/site-packages/github/Notification.py new file mode 100644 index 0000000000000000000000000000000000000000..24333b818826296b83972e74e2284adfb9b05f7e --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Notification.py @@ -0,0 +1,175 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2013 AKFish # +# Copyright 2013 Peter Golm # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Alice GIRARD # +# Copyright 2018 sfdye # +# Copyright 2019 Olof-Joachim Frahm (欧雅福) # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Alice GIRARD # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Matthias Bilger # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.Issue +import github.NotificationSubject +import github.PullRequest +import github.Repository +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class Notification(CompletableGithubObject): + """ + This class represents Notifications. + + The reference can be found here + https://docs.github.com/en/rest/reference/activity#notifications + + The OpenAPI schema can be found at + - /components/schemas/thread + + """ + + def _initAttributes(self) -> None: + self._id: Attribute[str] = NotSet + self._last_read_at: Attribute[datetime] = NotSet + self._reason: Attribute[str] = NotSet + self._repository: Attribute[github.Repository.Repository] = NotSet + self._subject: Attribute[github.NotificationSubject.NotificationSubject] = NotSet + self._subscription_url: Attribute[str] = NotSet + self._unread: Attribute[bool] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "subject": self._subject.value}) + + @property + def id(self) -> str: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def last_read_at(self) -> datetime: + self._completeIfNotSet(self._last_read_at) + return self._last_read_at.value + + @property + def reason(self) -> str: + self._completeIfNotSet(self._reason) + return self._reason.value + + @property + def repository(self) -> github.Repository.Repository: + self._completeIfNotSet(self._repository) + return self._repository.value + + @property + def subject(self) -> github.NotificationSubject.NotificationSubject: + self._completeIfNotSet(self._subject) + return self._subject.value + + @property + def subscription_url(self) -> str: + self._completeIfNotSet(self._subscription_url) + return self._subscription_url.value + + @property + def unread(self) -> bool: + self._completeIfNotSet(self._unread) + return self._unread.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def mark_as_read(self) -> None: + """ + :calls: `PATCH /notifications/threads/{id} `_ + """ + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + ) + + def mark_as_done(self) -> None: + """ + :calls: `DELETE /notifications/threads/{id} `_ + """ + headers, data = self._requester.requestJsonAndCheck( + "DELETE", + self.url, + ) + + def get_pull_request(self) -> github.PullRequest.PullRequest: + headers, data = self._requester.requestJsonAndCheck("GET", self.subject.url) + return github.PullRequest.PullRequest(self._requester, headers, data, completed=True) + + def get_issue(self) -> github.Issue.Issue: + headers, data = self._requester.requestJsonAndCheck("GET", self.subject.url) + return github.Issue.Issue(self._requester, headers, data, completed=True) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "id" in attributes: # pragma no branch + self._id = self._makeStringAttribute(attributes["id"]) + if "last_read_at" in attributes: # pragma no branch + self._last_read_at = self._makeDatetimeAttribute(attributes["last_read_at"]) + if "reason" in attributes: # pragma no branch + self._reason = self._makeStringAttribute(attributes["reason"]) + if "repository" in attributes: # pragma no branch + self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"]) + if "subject" in attributes: # pragma no branch + self._subject = self._makeClassAttribute( + github.NotificationSubject.NotificationSubject, attributes["subject"] + ) + if "subscription_url" in attributes: # pragma no branch + self._subscription_url = self._makeStringAttribute(attributes["subscription_url"]) + if "unread" in attributes: # pragma no branch + self._unread = self._makeBoolAttribute(attributes["unread"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/NotificationSubject.py b/python_embeded/Lib/site-packages/github/NotificationSubject.py new file mode 100644 index 0000000000000000000000000000000000000000..38ab68bd93d289bfa3b3d21ae9ee341ddf471692 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/NotificationSubject.py @@ -0,0 +1,93 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class NotificationSubject(NonCompletableGithubObject): + """ + This class represents Subjects of Notifications. + + The reference can be found here + https://docs.github.com/en/rest/reference/activity#list-notifications-for-the-authenticated-user + + The OpenAPI schema can be found at + - /components/schemas/thread/properties/subject + + """ + + def _initAttributes(self) -> None: + self._latest_comment_url: Attribute[str] = NotSet + self._title: Attribute[str] = NotSet + self._type: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"title": self._title.value}) + + @property + def latest_comment_url(self) -> str: + return self._latest_comment_url.value + + @property + def title(self) -> str: + return self._title.value + + @property + def type(self) -> str: + return self._type.value + + @property + def url(self) -> str: + return self._url.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "latest_comment_url" in attributes: # pragma no branch + self._latest_comment_url = self._makeStringAttribute(attributes["latest_comment_url"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "type" in attributes: # pragma no branch + self._type = self._makeStringAttribute(attributes["type"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/Organization.py b/python_embeded/Lib/site-packages/github/Organization.py new file mode 100644 index 0000000000000000000000000000000000000000..105597548c563103880dbabc3ed8e18f1ad7e057 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Organization.py @@ -0,0 +1,1997 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Steve English # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Sebastien Besson # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Matthew Neal # +# Copyright 2016 Michael Pereira # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Balázs Rostás # +# Copyright 2018 Anton Nguyen # +# Copyright 2018 Jacopo Notarstefano # +# Copyright 2018 Jasper van Wanrooy # +# Copyright 2018 Raihaan <31362124+res0nance@users.noreply.github.com> # +# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Tim Boring # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 Yossarian King # +# Copyright 2018 sfdye # +# Copyright 2019 Brian Choy # +# Copyright 2019 Geoffroy Jabouley # +# Copyright 2019 Pascal Bach # +# Copyright 2019 Raihaan <31362124+res0nance@users.noreply.github.com> # +# Copyright 2019 Shibasis Patel # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2019 ebrown # +# Copyright 2020 Anuj Bansal # +# Copyright 2020 Glenn McDonald # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 latacora-daniel <71085674+latacora-daniel@users.noreply.github.com># +# Copyright 2020 ton-katsu # +# Copyright 2021 James Simpson # +# Copyright 2021 Marina Peresypkina # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2021 Tanner <51724788+lightningboltemoji@users.noreply.github.com> # +# Copyright 2022 KimSia Sim <245021+simkimsia@users.noreply.github.com> # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Felipe Peter # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> # +# Copyright 2023 Jonathan Leitschuh # +# Copyright 2023 Mark Amery # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2023 Oliver Mannion <125105+tekumara@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Andrii Kezikov # +# Copyright 2024 Bill Napier # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jacky Lam # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Mohamed Mostafa <112487260+mohy01@users.noreply.github.com> # +# Copyright 2024 Oskar Jansson <56458534+janssonoskar@users.noreply.github.com># +# Copyright 2024 Pasha Fateev # +# Copyright 2024 Thomas Cooper # +# Copyright 2024 Thomas Crowley <15927917+thomascrowley@users.noreply.github.com># +# Copyright 2025 Bill Napier # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import urllib.parse +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.CodeSecurityConfig +import github.CodeSecurityConfigRepository +import github.Copilot +import github.DefaultCodeSecurityConfig +import github.Event +import github.GithubObject +import github.HookDelivery +import github.NamedUser +import github.OrganizationCustomProperty +import github.OrganizationDependabotAlert +import github.OrganizationSecret +import github.OrganizationVariable +import github.Plan +import github.Project +import github.Repository +import github.Team +from github import Consts +from github.GithubObject import ( + Attribute, + CompletableGithubObject, + NotSet, + Opt, + is_defined, + is_optional, + is_optional_list, + is_undefined, +) +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.CodeSecurityConfig import CodeSecurityConfig + from github.CodeSecurityConfigRepository import CodeSecurityConfigRepository + from github.Copilot import Copilot + from github.DefaultCodeSecurityConfig import DefaultCodeSecurityConfig + from github.Event import Event + from github.Hook import Hook + from github.Installation import Installation + from github.Issue import Issue + from github.Label import Label + from github.Migration import Migration + from github.NamedUser import NamedUser + from github.OrganizationCustomProperty import ( + CustomProperty, + OrganizationCustomProperty, + RepositoryCustomPropertyValues, + ) + from github.OrganizationDependabotAlert import OrganizationDependabotAlert + from github.OrganizationSecret import OrganizationSecret + from github.OrganizationVariable import OrganizationVariable + from github.Plan import Plan + from github.Project import Project + from github.PublicKey import PublicKey + from github.Repository import Repository + from github.Team import Team + + +class Organization(CompletableGithubObject): + """ + This class represents Organizations. + + The reference can be found here + https://docs.github.com/en/rest/reference/orgs + + The OpenAPI schema can be found at + - /components/schemas/actor + - /components/schemas/organization-full + - /components/schemas/organization-simple + - /components/schemas/team-organization + + """ + + def _initAttributes(self) -> None: + self._advanced_security_enabled_for_new_repositories: Attribute[bool] = NotSet + self._archived_at: Attribute[datetime] = NotSet + self._avatar_url: Attribute[str] = NotSet + self._billing_email: Attribute[str] = NotSet + self._blog: Attribute[str | None] = NotSet + self._collaborators: Attribute[int] = NotSet + self._company: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._default_repository_permission: Attribute[str] = NotSet + self._dependabot_alerts_enabled_for_new_repositories: Attribute[bool] = NotSet + self._dependabot_security_updates_enabled_for_new_repositories: Attribute[bool] = NotSet + self._dependency_graph_enabled_for_new_repositories: Attribute[bool] = NotSet + self._description: Attribute[str] = NotSet + self._disk_usage: Attribute[int] = NotSet + self._display_login: Attribute[str] = NotSet + self._email: Attribute[str] = NotSet + self._events_url: Attribute[str] = NotSet + self._followers: Attribute[int] = NotSet + self._following: Attribute[int] = NotSet + self._gravatar_id: Attribute[str] = NotSet + self._has_organization_projects: Attribute[bool] = NotSet + self._has_repository_projects: Attribute[bool] = NotSet + self._hooks_url: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._is_verified: Attribute[bool] = NotSet + self._issues_url: Attribute[str] = NotSet + self._location: Attribute[str] = NotSet + self._login: Attribute[str] = NotSet + self._members_allowed_repository_creation_type: Attribute[str] = NotSet + self._members_can_create_internal_repositories: Attribute[bool] = NotSet + self._members_can_create_pages: Attribute[bool] = NotSet + self._members_can_create_private_pages: Attribute[bool] = NotSet + self._members_can_create_private_repositories: Attribute[bool] = NotSet + self._members_can_create_public_pages: Attribute[bool] = NotSet + self._members_can_create_public_repositories: Attribute[bool] = NotSet + self._members_can_create_repositories: Attribute[bool] = NotSet + self._members_can_fork_private_repositories: Attribute[bool] = NotSet + self._members_url: Attribute[str] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._owned_private_repos: Attribute[int] = NotSet + self._plan: Attribute[Plan] = NotSet + self._private_gists: Attribute[int] = NotSet + self._public_gists: Attribute[int] = NotSet + self._public_members_url: Attribute[str] = NotSet + self._public_repos: Attribute[int] = NotSet + self._repos_url: Attribute[str] = NotSet + self._secret_scanning_enabled_for_new_repositories: Attribute[bool] = NotSet + self._secret_scanning_push_protection_custom_link: Attribute[str] = NotSet + self._secret_scanning_push_protection_custom_link_enabled: Attribute[bool] = NotSet + self._secret_scanning_push_protection_enabled_for_new_repositories: Attribute[bool] = NotSet + self._total_private_repos: Attribute[int] = NotSet + self._twitter_username: Attribute[str] = NotSet + self._two_factor_requirement_enabled: Attribute[bool] = NotSet + self._type: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._web_commit_signoff_required: Attribute[bool] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"login": self._login.value}) + + @property + def advanced_security_enabled_for_new_repositories(self) -> bool: + self._completeIfNotSet(self._advanced_security_enabled_for_new_repositories) + return self._advanced_security_enabled_for_new_repositories.value + + @property + def archived_at(self) -> datetime: + self._completeIfNotSet(self._archived_at) + return self._archived_at.value + + @property + def avatar_url(self) -> str: + self._completeIfNotSet(self._avatar_url) + return self._avatar_url.value + + @property + def billing_email(self) -> str: + self._completeIfNotSet(self._billing_email) + return self._billing_email.value + + @property + def blog(self) -> str | None: + self._completeIfNotSet(self._blog) + return self._blog.value + + @property + def collaborators(self) -> int: + self._completeIfNotSet(self._collaborators) + return self._collaborators.value + + @property + def company(self) -> str | None: + self._completeIfNotSet(self._company) + return self._company.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def default_repository_permission(self) -> str: + self._completeIfNotSet(self._default_repository_permission) + return self._default_repository_permission.value + + @property + def dependabot_alerts_enabled_for_new_repositories(self) -> bool: + self._completeIfNotSet(self._dependabot_alerts_enabled_for_new_repositories) + return self._dependabot_alerts_enabled_for_new_repositories.value + + @property + def dependabot_security_updates_enabled_for_new_repositories(self) -> bool: + self._completeIfNotSet(self._dependabot_security_updates_enabled_for_new_repositories) + return self._dependabot_security_updates_enabled_for_new_repositories.value + + @property + def dependency_graph_enabled_for_new_repositories(self) -> bool: + self._completeIfNotSet(self._dependency_graph_enabled_for_new_repositories) + return self._dependency_graph_enabled_for_new_repositories.value + + @property + def description(self) -> str: + self._completeIfNotSet(self._description) + return self._description.value + + @property + def disk_usage(self) -> int: + self._completeIfNotSet(self._disk_usage) + return self._disk_usage.value + + @property + def display_login(self) -> str: + self._completeIfNotSet(self._display_login) + return self._display_login.value + + @property + def email(self) -> str | None: + self._completeIfNotSet(self._email) + return self._email.value + + @property + def events_url(self) -> str: + self._completeIfNotSet(self._events_url) + return self._events_url.value + + @property + def followers(self) -> int: + self._completeIfNotSet(self._followers) + return self._followers.value + + @property + def following(self) -> int: + self._completeIfNotSet(self._following) + return self._following.value + + @property + def gravatar_id(self) -> str: + self._completeIfNotSet(self._gravatar_id) + return self._gravatar_id.value + + @property + def has_organization_projects(self) -> bool: + self._completeIfNotSet(self._has_organization_projects) + return self._has_organization_projects.value + + @property + def has_repository_projects(self) -> bool: + self._completeIfNotSet(self._has_repository_projects) + return self._has_repository_projects.value + + @property + def hooks_url(self) -> str: + self._completeIfNotSet(self._hooks_url) + return self._hooks_url.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def is_verified(self) -> bool: + self._completeIfNotSet(self._is_verified) + return self._is_verified.value + + @property + def issues_url(self) -> str: + self._completeIfNotSet(self._issues_url) + return self._issues_url.value + + @property + def location(self) -> str: + self._completeIfNotSet(self._location) + return self._location.value + + @property + def login(self) -> str: + self._completeIfNotSet(self._login) + return self._login.value + + @property + def members_allowed_repository_creation_type(self) -> str: + self._completeIfNotSet(self._members_allowed_repository_creation_type) + return self._members_allowed_repository_creation_type.value + + @property + def members_can_create_internal_repositories(self) -> bool: + self._completeIfNotSet(self._members_can_create_internal_repositories) + return self._members_can_create_internal_repositories.value + + @property + def members_can_create_pages(self) -> bool: + self._completeIfNotSet(self._members_can_create_pages) + return self._members_can_create_pages.value + + @property + def members_can_create_private_pages(self) -> bool: + self._completeIfNotSet(self._members_can_create_private_pages) + return self._members_can_create_private_pages.value + + @property + def members_can_create_private_repositories(self) -> bool: + self._completeIfNotSet(self._members_can_create_private_repositories) + return self._members_can_create_private_repositories.value + + @property + def members_can_create_public_pages(self) -> bool: + self._completeIfNotSet(self._members_can_create_public_pages) + return self._members_can_create_public_pages.value + + @property + def members_can_create_public_repositories(self) -> bool: + self._completeIfNotSet(self._members_can_create_public_repositories) + return self._members_can_create_public_repositories.value + + @property + def members_can_create_repositories(self) -> bool: + self._completeIfNotSet(self._members_can_create_repositories) + return self._members_can_create_repositories.value + + @property + def members_can_fork_private_repositories(self) -> bool: + self._completeIfNotSet(self._members_can_fork_private_repositories) + return self._members_can_fork_private_repositories.value + + @property + def members_url(self) -> str: + self._completeIfNotSet(self._members_url) + return self._members_url.value + + @property + def name(self) -> str | None: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def owned_private_repos(self) -> int: + self._completeIfNotSet(self._owned_private_repos) + return self._owned_private_repos.value + + @property + def plan(self) -> Plan: + self._completeIfNotSet(self._plan) + return self._plan.value + + @property + def private_gists(self) -> int: + self._completeIfNotSet(self._private_gists) + return self._private_gists.value + + @property + def public_gists(self) -> int: + self._completeIfNotSet(self._public_gists) + return self._public_gists.value + + @property + def public_members_url(self) -> str: + self._completeIfNotSet(self._public_members_url) + return self._public_members_url.value + + @property + def public_repos(self) -> int: + self._completeIfNotSet(self._public_repos) + return self._public_repos.value + + @property + def repos_url(self) -> str: + self._completeIfNotSet(self._repos_url) + return self._repos_url.value + + @property + def secret_scanning_enabled_for_new_repositories(self) -> bool: + self._completeIfNotSet(self._secret_scanning_enabled_for_new_repositories) + return self._secret_scanning_enabled_for_new_repositories.value + + @property + def secret_scanning_push_protection_custom_link(self) -> str: + self._completeIfNotSet(self._secret_scanning_push_protection_custom_link) + return self._secret_scanning_push_protection_custom_link.value + + @property + def secret_scanning_push_protection_custom_link_enabled(self) -> bool: + self._completeIfNotSet(self._secret_scanning_push_protection_custom_link_enabled) + return self._secret_scanning_push_protection_custom_link_enabled.value + + @property + def secret_scanning_push_protection_enabled_for_new_repositories(self) -> bool: + self._completeIfNotSet(self._secret_scanning_push_protection_enabled_for_new_repositories) + return self._secret_scanning_push_protection_enabled_for_new_repositories.value + + @property + def total_private_repos(self) -> int: + self._completeIfNotSet(self._total_private_repos) + return self._total_private_repos.value + + @property + def twitter_username(self) -> str: + self._completeIfNotSet(self._twitter_username) + return self._twitter_username.value + + @property + def two_factor_requirement_enabled(self) -> bool: + self._completeIfNotSet(self._two_factor_requirement_enabled) + return self._two_factor_requirement_enabled.value + + @property + def type(self) -> str: + self._completeIfNotSet(self._type) + return self._type.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def web_commit_signoff_required(self) -> bool: + self._completeIfNotSet(self._web_commit_signoff_required) + return self._web_commit_signoff_required.value + + def add_to_members(self, member: NamedUser, role: Opt[str] = NotSet) -> None: + """ + :calls: `PUT /orgs/{org}/memberships/{user} `_ + """ + assert is_optional(role, str), role + assert isinstance(member, github.NamedUser.NamedUser), member + put_parameters = NotSet.remove_unset_items({"role": role}) + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/memberships/{member._identity}", input=put_parameters + ) + + def add_to_public_members(self, public_member: NamedUser) -> None: + """ + :calls: `PUT /orgs/{org}/public_members/{user} `_ + """ + assert isinstance(public_member, github.NamedUser.NamedUser), public_member + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/public_members/{public_member._identity}" + ) + + def create_fork( + self, + repo: Repository, + name: Opt[str] = NotSet, + default_branch_only: Opt[bool] = NotSet, + ) -> Repository: + """ + :calls: `POST /repos/{owner}/{repo}/forks `_ + """ + assert isinstance(repo, github.Repository.Repository), repo + return repo.create_fork( + self, + name=name, + default_branch_only=default_branch_only, + ) + + def create_repo_from_template( + self, + name: str, + repo: Repository, + description: Opt[str] = NotSet, + include_all_branches: Opt[bool] = NotSet, + private: Opt[bool] = NotSet, + ) -> Repository: + """self.name + :calls: `POST /repos/{template_owner}/{template_repo}/generate `_ + """ + assert isinstance(name, str), name + assert isinstance(repo, github.Repository.Repository), repo + assert is_optional(description, str), description + assert is_optional(include_all_branches, bool), include_all_branches + assert is_optional(private, bool), private + post_parameters: dict[str, Any] = NotSet.remove_unset_items( + { + "name": name, + "owner": self.login, + "description": description, + "include_all_branches": include_all_branches, + "private": private, + } + ) + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"/repos/{repo.owner.login}/{repo.name}/generate", + input=post_parameters, + headers={"Accept": "application/vnd.github.v3+json"}, + ) + return github.Repository.Repository(self._requester, headers, data, completed=True) + + def create_hook( + self, + name: str, + config: dict[str, str], + events: Opt[list[str]] = NotSet, + active: Opt[bool] = NotSet, + ) -> Hook: + """ + :calls: `POST /orgs/{owner}/hooks `_ + :param name: string + :param config: dict + :param events: list of string + :param active: bool + :rtype: :class:`github.Hook.Hook` + """ + assert isinstance(name, str), name + assert isinstance(config, dict), config + assert is_optional_list(events, str), events + assert is_optional(active, bool), active + post_parameters: dict[str, Any] = NotSet.remove_unset_items( + { + "name": name, + "config": config, + "events": events, + "active": active, + } + ) + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/hooks", input=post_parameters) + return github.Hook.Hook(self._requester, headers, data, completed=True) + + def create_project(self, name: str, body: Opt[str] = NotSet) -> github.Project.Project: + """ + :calls: `POST /orgs/{org}/projects `_ + """ + assert isinstance(name, str), name + assert is_optional(body, str), body + post_parameters: dict[str, Any] = NotSet.remove_unset_items({"name": name, "body": body}) + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/projects", + input=post_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + return github.Project.Project(self._requester, headers, data, completed=True) + + def create_repo( + self, + name: str, + description: Opt[str] = NotSet, + homepage: Opt[str] = NotSet, + private: Opt[bool] = NotSet, + visibility: Opt[str] = NotSet, + has_issues: Opt[bool] = NotSet, + has_wiki: Opt[bool] = NotSet, + has_downloads: Opt[bool] = NotSet, + has_projects: Opt[bool] = NotSet, + team_id: Opt[int] = NotSet, + auto_init: Opt[bool] = NotSet, + license_template: Opt[str] = NotSet, + gitignore_template: Opt[str] = NotSet, + allow_squash_merge: Opt[bool] = NotSet, + allow_merge_commit: Opt[bool] = NotSet, + allow_rebase_merge: Opt[bool] = NotSet, + delete_branch_on_merge: Opt[bool] = NotSet, + allow_update_branch: Opt[bool] = NotSet, + is_template: Opt[bool] = NotSet, + allow_auto_merge: Opt[bool] = NotSet, + use_squash_pr_title_as_default: Opt[bool] = NotSet, + squash_merge_commit_title: Opt[str] = NotSet, + squash_merge_commit_message: Opt[str] = NotSet, + merge_commit_title: Opt[str] = NotSet, + merge_commit_message: Opt[str] = NotSet, + custom_properties: Opt[dict[str, Any]] = NotSet, + ) -> github.Repository.Repository: + """ + :calls: `POST /orgs/{org}/repos `_ + """ + assert isinstance(name, str), name + assert is_optional(description, str), description + assert is_optional(homepage, str), homepage + assert is_optional(private, bool), private + assert is_optional(visibility, str), visibility + assert is_optional(has_issues, bool), has_issues + assert is_optional(has_wiki, bool), has_wiki + assert is_optional(has_downloads, bool), has_downloads + assert is_optional(has_projects, bool), has_projects + assert is_optional(team_id, int), team_id + assert is_optional(auto_init, bool), auto_init + assert is_optional(license_template, str), license_template + assert is_optional(gitignore_template, str), gitignore_template + assert is_optional(allow_squash_merge, bool), allow_squash_merge + assert is_optional(allow_merge_commit, bool), allow_merge_commit + assert is_optional(allow_rebase_merge, bool), allow_rebase_merge + assert is_optional(delete_branch_on_merge, bool), delete_branch_on_merge + assert is_optional(allow_update_branch, bool), allow_update_branch + assert is_optional(is_template, bool), is_template + assert is_optional(allow_auto_merge, bool), allow_auto_merge + assert is_optional(use_squash_pr_title_as_default, bool), use_squash_pr_title_as_default + assert squash_merge_commit_title in ["PR_TITLE", "COMMIT_OR_PR_TITLE", NotSet], squash_merge_commit_title + assert squash_merge_commit_message in [ + "PR_BODY", + "COMMIT_MESSAGES", + "BLANK", + NotSet, + ], squash_merge_commit_message + assert merge_commit_title in ["PR_TITLE", "MERGE_MESSAGE", NotSet], merge_commit_title + assert merge_commit_message in ["PR_TITLE", "PR_BODY", "BLANK", NotSet], merge_commit_message + assert is_optional(custom_properties, dict), custom_properties + post_parameters = NotSet.remove_unset_items( + { + "name": name, + "description": description, + "homepage": homepage, + "private": private, + "visibility": visibility, + "has_issues": has_issues, + "has_wiki": has_wiki, + "has_downloads": has_downloads, + "has_projects": has_projects, + "team_id": team_id, + "auto_init": auto_init, + "license_template": license_template, + "gitignore_template": gitignore_template, + "allow_squash_merge": allow_squash_merge, + "allow_merge_commit": allow_merge_commit, + "allow_rebase_merge": allow_rebase_merge, + "delete_branch_on_merge": delete_branch_on_merge, + "allow_update_branch": allow_update_branch, + "is_template": is_template, + "allow_auto_merge": allow_auto_merge, + "use_squash_pr_title_as_default": use_squash_pr_title_as_default, + "squash_merge_commit_title": squash_merge_commit_title, + "squash_merge_commit_message": squash_merge_commit_message, + "merge_commit_title": merge_commit_title, + "merge_commit_message": merge_commit_message, + "custom_properties": custom_properties, + } + ) + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/repos", + input=post_parameters, + headers={"Accept": Consts.repoVisibilityPreview}, + ) + return github.Repository.Repository(self._requester, headers, data, completed=True) + + def create_secret( + self, + secret_name: str, + unencrypted_value: str, + visibility: str = "all", + selected_repositories: Opt[list[github.Repository.Repository]] = NotSet, + secret_type: str = "actions", + ) -> github.OrganizationSecret.OrganizationSecret: + """ + :param secret_name: string name of the secret + :param unencrypted_value: string plain text value of the secret + :param visibility: string options all or selected + :param selected_repositories: list of repositrories that the secret will be available in + :param secret_type: string options actions or dependabot + + :calls: `PUT /orgs/{org}/{secret_type}/secrets/{secret_name} `_ + """ + assert isinstance(secret_name, str), secret_name + assert isinstance(unencrypted_value, str), unencrypted_value + assert isinstance(visibility, str), visibility + assert is_optional_list(selected_repositories, github.Repository.Repository), selected_repositories + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + + if visibility == "selected": + assert isinstance(selected_repositories, list) and all( + isinstance(element, github.Repository.Repository) for element in selected_repositories + ), selected_repositories + else: + assert selected_repositories is NotSet + + public_key = self.get_public_key(secret_type=secret_type) + payload = public_key.encrypt(unencrypted_value) + put_parameters: dict[str, Any] = { + "key_id": public_key.key_id, + "encrypted_value": payload, + "visibility": visibility, + } + if is_defined(selected_repositories): + # Dependbot and Actions endpoint expects different types + # https://docs.github.com/en/rest/dependabot/secrets?apiVersion=2022-11-28#create-or-update-an-organization-secret + # https://docs.github.com/en/rest/actions/secrets?apiVersion=2022-11-28#create-or-update-an-organization-secret + if secret_type == "actions": + put_parameters["selected_repository_ids"] = [element.id for element in selected_repositories] + if secret_type == "dependabot": + put_parameters["selected_repository_ids"] = [str(element.id) for element in selected_repositories] + + self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/{secret_type}/secrets/{urllib.parse.quote(secret_name)}", input=put_parameters + ) + + return github.OrganizationSecret.OrganizationSecret( + requester=self._requester, + headers={}, + attributes={ + "name": secret_name, + "visibility": visibility, + "selected_repositories_url": f"{self.url}/{secret_type}/secrets/{urllib.parse.quote(secret_name)}/repositories", + "url": f"{self.url}/{secret_type}/secrets/{urllib.parse.quote(secret_name)}", + }, + completed=False, + ) + + def get_secrets(self, secret_type: str = "actions") -> PaginatedList[OrganizationSecret]: + """ + Gets all organization secrets :param secret_type: string options actions or dependabot :rtype: + + :class:`PaginatedList` of :class:`github.OrganizationSecret.OrganizationSecret` + + """ + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + return PaginatedList( + github.OrganizationSecret.OrganizationSecret, + self._requester, + f"{self.url}/{secret_type}/secrets", + None, + list_item="secrets", + ) + + def get_secret(self, secret_name: str, secret_type: str = "actions") -> OrganizationSecret: + """ + :calls: 'GET /orgs/{org}/{secret_type}/secrets/{secret_name} `_ + :param secret_name: string + :param secret_type: string options actions or dependabot + :rtype: github.OrganizationSecret.OrganizationSecret + """ + assert isinstance(secret_name, str), secret_name + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + return github.OrganizationSecret.OrganizationSecret( + requester=self._requester, + headers={}, + attributes={"url": f"{self.url}/{secret_type}/secrets/{urllib.parse.quote(secret_name)}"}, + completed=False, + ) + + def create_team( + self, + name: str, + repo_names: Opt[list[Repository]] = NotSet, + permission: Opt[str] = NotSet, + privacy: Opt[str] = NotSet, + description: Opt[str] = NotSet, + parent_team_id: Opt[int] = NotSet, + maintainers: Opt[list[int]] = NotSet, + notification_setting: Opt[str] = NotSet, + ) -> Team: + """ + :calls: `POST /orgs/{org}/teams `_ + :param name: string + :param repo_names: list of :class:`github.Repository.Repository` + :param permission: string + :param privacy: string + :param description: string + :param parent_team_id: integer + :param maintainers: list of: integer + :param notification_setting: string + :rtype: :class:`github.Team.Team` + """ + assert isinstance(name, str), name + assert is_optional_list(repo_names, github.Repository.Repository), repo_names + assert is_optional_list(maintainers, int), maintainers + assert is_optional(parent_team_id, int), parent_team_id + assert is_optional(permission, str), permission + assert is_optional(privacy, str), privacy + assert is_optional(description, str), description + assert notification_setting in ["notifications_enabled", "notifications_disabled", NotSet], notification_setting + post_parameters: dict[str, Any] = NotSet.remove_unset_items( + { + "name": name, + "permission": permission, + "privacy": privacy, + "description": description, + "parent_team_id": parent_team_id, + "maintainers": maintainers, + "notification_setting": notification_setting, + } + ) + if is_defined(repo_names): + post_parameters["repo_names"] = [element._identity for element in repo_names] + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/teams", input=post_parameters) + return github.Team.Team(self._requester, headers, data, completed=True) + + def create_variable( + self, + variable_name: str, + value: str, + visibility: str = "all", + selected_repositories: github.GithubObject.Opt[list[github.Repository.Repository]] = NotSet, + ) -> github.OrganizationVariable.OrganizationVariable: + """ + :calls: `POST /orgs/{org}/actions/variables/ `_ + :param variable_name: string + :param value: string + :param visibility: string + :param selected_repositories: list of :class:`github.Repository.Repository` + :rtype: github.OrganizationVariable.OrganizationVariable + """ + assert isinstance(variable_name, str), variable_name + assert isinstance(value, str), value + assert isinstance(visibility, str), visibility + if visibility == "selected": + assert isinstance(selected_repositories, list) and all( + isinstance(element, github.Repository.Repository) for element in selected_repositories + ), selected_repositories + else: + assert selected_repositories is NotSet + + post_parameters: dict[str, Any] = { + "name": variable_name, + "value": value, + "visibility": visibility, + } + if is_defined(selected_repositories): + post_parameters["selected_repository_ids"] = [element.id for element in selected_repositories] + + self._requester.requestJsonAndCheck("POST", f"{self.url}/actions/variables", input=post_parameters) + + return github.OrganizationVariable.OrganizationVariable( + requester=self._requester, + headers={}, + attributes={ + "name": variable_name, + "visibility": visibility, + "value": value, + "selected_repositories_url": f"{self.url}/actions/variables/{urllib.parse.quote(variable_name)}/repositories", + "url": self.url, + }, + completed=False, + ) + + def get_variables(self) -> PaginatedList[OrganizationVariable]: + """ + Gets all organization variables :rtype: :class:`PaginatedList` of + :class:`github.OrganizationVariable.OrganizationVariable` + """ + return PaginatedList( + github.OrganizationVariable.OrganizationVariable, + self._requester, + f"{self.url}/actions/variables", + None, + list_item="variables", + ) + + def get_variable(self, variable_name: str) -> OrganizationVariable: + """ + :calls: 'GET /orgs/{org}/actions/variables/{variable_name} `_ + :param variable_name: string + :rtype: github.OrganizationVariable.OrganizationVariable + """ + assert isinstance(variable_name, str), variable_name + return github.OrganizationVariable.OrganizationVariable( + requester=self._requester, + headers={}, + attributes={"url": f"{self.url}/actions/variables/{urllib.parse.quote(variable_name)}"}, + completed=False, + ) + + def delete_hook(self, id: int) -> None: + """ + :calls: `DELETE /orgs/{owner}/hooks/{id} `_ + :param id: integer + :rtype: None` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/hooks/{id}") + + def edit( + self, + billing_email: Opt[str] = NotSet, + blog: Opt[str] = NotSet, + company: Opt[str] = NotSet, + description: Opt[str] = NotSet, + email: Opt[str] = NotSet, + location: Opt[str] = NotSet, + name: Opt[str] = NotSet, + ) -> None: + """ + :calls: `PATCH /orgs/{org} `_ + """ + assert is_optional(billing_email, str), billing_email + assert is_optional(blog, str), blog + assert is_optional(company, str), company + assert is_optional(description, str), description + assert is_optional(email, str), email + assert is_optional(location, str), location + assert is_optional(name, str), name + post_parameters = NotSet.remove_unset_items( + { + "billing_email": billing_email, + "blog": blog, + "company": company, + "description": description, + "email": email, + "location": location, + "name": name, + } + ) + + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def edit_hook( + self, + id: int, + name: str, + config: dict[str, str], + events: Opt[list[str]] = NotSet, + active: Opt[bool] = NotSet, + ) -> Hook: + """ + :calls: `PATCH /orgs/{owner}/hooks/{id} `_ + """ + assert isinstance(id, int), id + assert isinstance(name, str), name + assert isinstance(config, dict), config + assert is_optional_list(events, str), events + assert is_optional(active, bool), active + post_parameters: dict[str, Any] = NotSet.remove_unset_items( + {"name": name, "config": config, "events": events, "active": active} + ) + + headers, data = self._requester.requestJsonAndCheck("PATCH", f"{self.url}/hooks/{id}", input=post_parameters) + return github.Hook.Hook(self._requester, headers, data, completed=True) + + def get_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /orgs/{org}/events `_ + :rtype: :class:`PaginatedList` of :class:`github.Event.Event` + """ + return PaginatedList(github.Event.Event, self._requester, f"{self.url}/events", None) + + def get_hook(self, id: int) -> github.Hook.Hook: + """ + :calls: `GET /orgs/{owner}/hooks/{id} `_ + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/hooks/{id}") + return github.Hook.Hook(self._requester, headers, data, completed=True) + + def get_hooks(self) -> PaginatedList[Hook]: + """ + :calls: `GET /orgs/{owner}/hooks `_ + """ + return PaginatedList(github.Hook.Hook, self._requester, f"{self.url}/hooks", None) + + def get_hook_delivery(self, hook_id: int, delivery_id: int) -> github.HookDelivery.HookDelivery: + """ + :calls: `GET /orgs/{owner}/hooks/{hook_id}/deliveries/{delivery_id} `_ + :param hook_id: integer + :param delivery_id: integer + :rtype: :class:`github.HookDelivery.HookDelivery` + """ + assert isinstance(hook_id, int), hook_id + assert isinstance(delivery_id, int), delivery_id + headers, data = self._requester.requestJsonAndCheck( + "GET", f"{self.url}/hooks/{hook_id}/deliveries/{delivery_id}" + ) + return github.HookDelivery.HookDelivery(self._requester, headers, data) + + def get_hook_deliveries(self, hook_id: int) -> PaginatedList[github.HookDelivery.HookDeliverySummary]: + """ + :calls: `GET /orgs/{owner}/hooks/{hook_id}/deliveries `_ + :param hook_id: integer + :rtype: :class:`PaginatedList` of :class:`github.HookDelivery.HookDeliverySummary` + """ + assert isinstance(hook_id, int), hook_id + return PaginatedList( + github.HookDelivery.HookDeliverySummary, + self._requester, + f"{self.url}/hooks/{hook_id}/deliveries", + None, + ) + + def get_issues( + self, + filter: Opt[str] = NotSet, + state: Opt[str] = NotSet, + labels: Opt[list[Label]] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + ) -> PaginatedList[Issue]: + """ + :calls: `GET /orgs/{org}/issues `_ + :rtype: :class:`PaginatedList` of :class:`github.Issue.Issue` + :param filter: string + :param state: string + :param labels: list of :class:`github.Label.Label` + :param sort: string + :param direction: string + :param since: datetime + :rtype: :class:`PaginatedList` of :class:`github.Issue.Issue` + """ + assert is_optional(filter, str), filter + assert is_optional(state, str), state + assert is_optional_list(labels, github.Label.Label), labels + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + assert is_optional(since, datetime), since + url_parameters: dict[str, Any] = NotSet.remove_unset_items( + {"filter": filter, "state": state, "sort": sort, "direction": direction} + ) + if is_defined(labels): + url_parameters["labels"] = ",".join(label.name for label in labels) + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + return PaginatedList(github.Issue.Issue, self._requester, f"{self.url}/issues", url_parameters) + + def get_members( + self, + filter_: Opt[str] = NotSet, + role: Opt[str] = NotSet, + ) -> PaginatedList[NamedUser]: + """ + :calls: `GET /orgs/{org}/members `_ + """ + assert is_optional(filter_, str), filter_ + assert is_optional(role, str), role + + url_parameters = NotSet.remove_unset_items({"filter": filter_, "role": role}) + + return PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/members", + url_parameters, + ) + + def get_projects(self, state: Opt[str] = NotSet) -> PaginatedList[Project]: + """ + :calls: `GET /orgs/{org}/projects `_ + """ + + url_parameters = NotSet.remove_unset_items({"state": state}) + + return PaginatedList( + github.Project.Project, + self._requester, + f"{self.url}/projects", + url_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + + def get_public_members(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /orgs/{org}/public_members `_ + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + return PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/public_members", + None, + ) + + def get_outside_collaborators(self, filter_: Opt[str] = NotSet) -> PaginatedList[NamedUser]: + """ + :calls: `GET /orgs/{org}/outside_collaborators `_ + """ + assert is_optional(filter_, str), filter_ + + url_parameters = NotSet.remove_unset_items({"filter": filter_}) + return PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/outside_collaborators", + url_parameters, + ) + + def remove_outside_collaborator(self, collaborator: NamedUser) -> None: + """ + :calls: `DELETE /orgs/{org}/outside_collaborators/{username} `_ + :param collaborator: :class:`github.NamedUser.NamedUser` + :rtype: None + """ + assert isinstance(collaborator, github.NamedUser.NamedUser), collaborator + headers, data = self._requester.requestJsonAndCheck( + "DELETE", f"{self.url}/outside_collaborators/{collaborator._identity}" + ) + + def convert_to_outside_collaborator(self, member: NamedUser) -> None: + """ + :calls: `PUT /orgs/{org}/outside_collaborators/{username} `_ + :param member: :class:`github.NamedUser.NamedUser` + :rtype: None + """ + assert isinstance(member, github.NamedUser.NamedUser), member + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/outside_collaborators/{member._identity}" + ) + + def get_public_key(self, secret_type: str = "actions") -> PublicKey: + """ + :calls: `GET /orgs/{org}/{secret_type}/secrets/public-key `_ + :param secret_type: string options actions or dependabot + :rtype: :class:`github.PublicKey.PublicKey` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/{secret_type}/secrets/public-key") + return github.PublicKey.PublicKey(self._requester, headers, data, completed=True) + + def get_copilot(self) -> Copilot: + """ + :calls: Various Copilot-related endpoints for this organization :rtype: :class:`github.Copilot.Copilot` + """ + return github.Copilot.Copilot(self._requester, self.login) + + def get_repo(self, name: str) -> Repository: + """ + :calls: `GET /repos/{owner}/{repo} `_ + :param name: string + :rtype: :class:`github.Repository.Repository` + """ + assert isinstance(name, str), name + name = urllib.parse.quote(name) + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"/repos/{self.login}/{name}", + headers={"Accept": Consts.repoVisibilityPreview}, + ) + return github.Repository.Repository(self._requester, headers, data, completed=True) + + def get_repos( + self, + type: Opt[str] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + ) -> PaginatedList[Repository]: + """ + :calls: `GET /orgs/{org}/repos `_ + :param type: string ('all', 'public', 'private', 'forks', 'sources', 'member') + :param sort: string ('created', 'updated', 'pushed', 'full_name') + :param direction: string ('asc', desc') + """ + assert is_optional(type, str), type + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + + url_parameters = NotSet.remove_unset_items({"type": type, "sort": sort, "direction": direction}) + + return PaginatedList( + github.Repository.Repository, + self._requester, + f"{self.url}/repos", + url_parameters, + headers={"Accept": Consts.repoVisibilityPreview}, + ) + + def get_team(self, id: int) -> Team: + """ + :calls: `GET /teams/{id} `_ + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"/teams/{id}") + return github.Team.Team(self._requester, headers, data, completed=True) + + def get_team_by_slug(self, slug: str) -> Team: + """ + :calls: `GET /orgs/{org}/teams/{team_slug} `_ + """ + assert isinstance(slug, str), slug + slug = urllib.parse.quote(slug) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/teams/{slug}") + return github.Team.Team(self._requester, headers, data, completed=True) + + def get_teams(self) -> PaginatedList[Team]: + """ + :calls: `GET /orgs/{org}/teams `_ + """ + return PaginatedList(github.Team.Team, self._requester, f"{self.url}/teams", None) + + def invitations(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /orgs/{org}/invitations `_ + """ + return PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/invitations", + None, + headers={"Accept": Consts.mediaTypeOrganizationInvitationPreview}, + ) + + def invite_user( + self, + user: Opt[NamedUser] = NotSet, + email: Opt[str] = NotSet, + role: Opt[str] = NotSet, + teams: Opt[list[Team]] = NotSet, + ) -> None: + """ + :calls: `POST /orgs/{org}/invitations `_ + :param user: :class:`github.NamedUser.NamedUser` + :param email: string + :param role: string + :param teams: array of :class:`github.Team.Team` + :rtype: None + """ + assert is_optional(user, github.NamedUser.NamedUser), user + assert is_optional(email, str), email + assert is_defined(email) != is_defined(user), "specify only one of email or user" + + assert is_undefined(role) or role in ["admin", "direct_member", "billing_manager"], role + assert is_optional_list(teams, github.Team.Team), teams + + parameters: dict[str, Any] = NotSet.remove_unset_items({"email": email, "role": role}) + + if is_defined(user): + parameters["invitee_id"] = user.id + if is_defined(teams): + parameters["team_ids"] = [t.id for t in teams] + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/invitations", + headers={"Accept": Consts.mediaTypeOrganizationInvitationPreview}, + input=parameters, + ) + + def cancel_invitation(self, invitee: NamedUser) -> bool: + """ + :calls: `DELETE /orgs/{org}/invitations/{invitation_id} `_ + :param invitee: :class:`github.NamedUser.NamedUser` + :rtype: None + """ + assert isinstance(invitee, github.NamedUser.NamedUser), invitee + status, headers, data = self._requester.requestJson("DELETE", f"{self.url}/invitations/{invitee.id}") + return status == 204 + + def has_in_members(self, member: NamedUser) -> bool: + """ + :calls: `GET /orgs/{org}/members/{user} `_ + :param member: :class:`github.NamedUser.NamedUser` + :rtype: bool + """ + assert isinstance(member, github.NamedUser.NamedUser), member + status, headers, data = self._requester.requestJson("GET", f"{self.url}/members/{member._identity}") + if status == 302: + status, headers, data = self._requester.requestJson("GET", headers["location"]) + return status == 204 + + def has_in_public_members(self, public_member: NamedUser) -> bool: + """ + :calls: `GET /orgs/{org}/public_members/{user} `_ + :param public_member: :class:`github.NamedUser.NamedUser` + :rtype: bool + """ + assert isinstance(public_member, github.NamedUser.NamedUser), public_member + status, headers, data = self._requester.requestJson( + "GET", f"{self.url}/public_members/{public_member._identity}" + ) + return status == 204 + + def remove_from_membership(self, member: NamedUser) -> None: + """ + :calls: `DELETE /orgs/{org}/memberships/{user} `_ + :param member: :class:`github.NamedUser.NamedUser` + :rtype: None + """ + assert isinstance(member, github.NamedUser.NamedUser), member + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/memberships/{member._identity}") + + def remove_from_members(self, member: NamedUser) -> None: + """ + :calls: `DELETE /orgs/{org}/members/{user} `_ + :param member: :class:`github.NamedUser.NamedUser` + :rtype: None + """ + assert isinstance(member, github.NamedUser.NamedUser), member + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/members/{member._identity}") + + def remove_from_public_members(self, public_member: NamedUser) -> None: + """ + :calls: `DELETE /orgs/{org}/public_members/{user} `_ + :param public_member: :class:`github.NamedUser.NamedUser` + :rtype: None + """ + assert isinstance(public_member, github.NamedUser.NamedUser), public_member + headers, data = self._requester.requestJsonAndCheck( + "DELETE", f"{self.url}/public_members/{public_member._identity}" + ) + + def create_migration( + self, + repos: list[str], + lock_repositories: Opt[bool] = NotSet, + exclude_attachments: Opt[bool] = NotSet, + ) -> Migration: + """ + :calls: `POST /orgs/{org}/migrations `_ + :param repos: list or tuple of str + :param lock_repositories: bool + :param exclude_attachments: bool + :rtype: :class:`github.Migration.Migration` + """ + assert isinstance(repos, (list, tuple)), repos + assert all(isinstance(repo, str) for repo in repos), repos + assert is_optional(lock_repositories, bool), lock_repositories + assert is_optional(exclude_attachments, bool), exclude_attachments + post_parameters = NotSet.remove_unset_items( + { + "repositories": repos, + "lock_repositories": lock_repositories, + "exclude_attachments": exclude_attachments, + } + ) + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"/orgs/{self.login}/migrations", + input=post_parameters, + headers={"Accept": Consts.mediaTypeMigrationPreview}, + ) + return github.Migration.Migration(self._requester, headers, data, completed=True) + + def get_migrations(self) -> PaginatedList[Migration]: + """ + :calls: `GET /orgs/{org}/migrations `_ + :rtype: :class:`PaginatedList` of :class:`github.Migration.Migration` + """ + return PaginatedList( + github.Migration.Migration, + self._requester, + f"/orgs/{self.login}/migrations", + None, + headers={"Accept": Consts.mediaTypeMigrationPreview}, + ) + + def get_installations(self) -> PaginatedList[Installation]: + """ + :calls: `GET /orgs/{org}/installations `_ + :rtype: :class:`PaginatedList` of :class:`github.Installation.Installation` + """ + + return PaginatedList( + github.Installation.Installation, + self._requester, + f"{self.url}/installations", + None, + headers=None, + list_item="installations", + ) + + def get_dependabot_alerts( + self, + state: Opt[str] = NotSet, + severity: Opt[str] = NotSet, + ecosystem: Opt[str] = NotSet, + package: Opt[str] = NotSet, + scope: Opt[str] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + ) -> PaginatedList[OrganizationDependabotAlert]: + """ + :calls: `GET /orgs/{org}/dependabot/alerts `_ + :param state: Optional string + :param severity: Optional string + :param ecosystem: Optional string + :param package: Optional string + :param scope: Optional string + :param sort: Optional string + :param direction: Optional string + :rtype: :class:`PaginatedList` of :class:`github.DependabotAlert.DependabotAlert` + """ + allowed_states = ["auto_dismissed", "dismissed", "fixed", "open"] + allowed_severities = ["low", "medium", "high", "critical"] + allowed_ecosystems = ["composer", "go", "maven", "npm", "nuget", "pip", "pub", "rubygems", "rust"] + allowed_scopes = ["development", "runtime"] + allowed_sorts = ["created", "updated"] + allowed_directions = ["asc", "desc"] + assert state in allowed_states + [NotSet], f"State can be one of {', '.join(allowed_states)}" + assert severity in allowed_severities + [NotSet], f"Severity can be one of {', '.join(allowed_severities)}" + assert ecosystem in allowed_ecosystems + [NotSet], f"Ecosystem can be one of {', '.join(allowed_ecosystems)}" + assert scope in allowed_scopes + [NotSet], f"Scope can be one of {', '.join(allowed_scopes)}" + assert sort in allowed_sorts + [NotSet], f"Sort can be one of {', '.join(allowed_sorts)}" + assert direction in allowed_directions + [NotSet], f"Direction can be one of {', '.join(allowed_directions)}" + url_parameters = NotSet.remove_unset_items( + { + "state": state, + "severity": severity, + "ecosystem": ecosystem, + "package": package, + "scope": scope, + "sort": sort, + "direction": direction, + } + ) + return PaginatedList( + github.OrganizationDependabotAlert.OrganizationDependabotAlert, + self._requester, + f"{self.url}/dependabot/alerts", + url_parameters, + ) + + def get_custom_properties(self) -> PaginatedList[OrganizationCustomProperty]: + """ + :calls: `GET /orgs/{org}/properties/schema `_ + :rtype: :class:`PaginatedList` of :class:`github.OrganizationCustomProperty.OrganizationCustomProperty` + """ + return PaginatedList( + contentClass=github.OrganizationCustomProperty.OrganizationCustomProperty, + requester=self._requester, + firstUrl=f"{self.url}/properties/schema", + firstParams=None, + ) + + def get_custom_property(self, property_name: str) -> OrganizationCustomProperty: + """ + :calls: `GET /orgs/{org}/properties/schema/{property_name} `_ + :param property_name: string + :rtype: :class:`github.OrganizationCustomProperty.OrganizationCustomProperty` + """ + assert isinstance(property_name, str), property_name + headers, data = self._requester.requestJsonAndCheck( + "GET", f"{self.url}/properties/schema/{urllib.parse.quote(property_name)}" + ) + return github.OrganizationCustomProperty.OrganizationCustomProperty( + requester=self._requester, + headers=headers, + attributes=data, + ) + + def create_custom_properties(self, properties: list[CustomProperty]) -> list[OrganizationCustomProperty]: + """ + Create or update custom properties for an organization + :calls: `PATCH /orgs/{org}/properties/schema `_ + :param properties: list of :class:`github.OrganizationCustomProperty.CustomProperty` + :rtype: list of :class:`github.OrganizationCustomProperty.OrganizationCustomProperty` + """ + assert isinstance(properties, list), properties + assert all(isinstance(p, github.OrganizationCustomProperty.CustomProperty) for p in properties), properties + patch_parameters = {"properties": [p.to_dict() for p in properties]} + headers, data = self._requester.requestJsonAndCheck( + "PATCH", f"{self.url}/properties/schema", input=patch_parameters + ) + return [ + github.OrganizationCustomProperty.OrganizationCustomProperty( + requester=self._requester, headers=headers, attributes=property + ) + for property in data + ] + + def create_custom_property(self, property: CustomProperty) -> OrganizationCustomProperty: + """ + Create or update a custom property for an organization + :calls: `PUT /orgs/{org}/properties/schema/{property_name} `_ + :param property: :class:`github.OrganizationCustomProperty.CustomProperty` + :rtype: :class:`github.OrganizationCustomProperty.OrganizationCustomProperty` + """ + assert isinstance(property, github.OrganizationCustomProperty.CustomProperty), property + assert property.values_editable_by is NotSet + + post_parameters = property.to_dict() + property_name = post_parameters.pop("property_name") + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/properties/schema/{property_name}", input=post_parameters + ) + return github.OrganizationCustomProperty.OrganizationCustomProperty( + requester=self._requester, headers=headers, attributes=data + ) + + def remove_custom_property(self, property_name: str) -> None: + """ + :calls: `DELETE /orgs/{org}/properties/schema/{property_name} `_ + :param property_name: string + :rtype: None + """ + assert isinstance(property_name, str), property_name + self._requester.requestJsonAndCheck("DELETE", f"{self.url}/properties/schema/{property_name}") + + def list_custom_property_values( + self, repository_query: Opt[str] = NotSet + ) -> PaginatedList[RepositoryCustomPropertyValues]: + """ + :calls: `GET /orgs/{org}/properties `_ + :rtype: :class:`PaginatedList` of dict + """ + return PaginatedList( + contentClass=github.OrganizationCustomProperty.RepositoryCustomPropertyValues, + requester=self._requester, + firstUrl=f"{self.url}/properties/values", + firstParams=NotSet.remove_unset_items({"repository_query": repository_query}), + ) + + def create_custom_property_values( + self, repository_names: list[str], properties: dict[str, str | list | None] + ) -> None: + """ + Create or update custom property values for organization repositories + :calls: `PATCH /orgs/{org}/properties `_ + :param repository_names: list of strings + :param properties: dict of string to string, list or None + :rtype: None + """ + assert isinstance(repository_names, list), repository_names + assert all(isinstance(repo, str) for repo in repository_names), repository_names + assert isinstance(properties, dict), properties + assert all(isinstance(value, (str, list, type(None))) for value in properties.values()), properties + patch_parameters = { + "repository_names": repository_names, + "properties": [{"property_name": k, "value": v} for k, v in properties.items()], + } + self._requester.requestJsonAndCheck("PATCH", f"{self.url}/properties/values", input=patch_parameters) + + def get_code_security_configs(self, target_type: Opt[str] = NotSet) -> PaginatedList[CodeSecurityConfig]: + """ + :calls: `GET /orgs/{org}/code-security/configurations `_ + :rtype: :class:`CodeSecurityConfig` + """ + return PaginatedList( + contentClass=github.CodeSecurityConfig.CodeSecurityConfig, + requester=self._requester, + firstUrl=f"{self.url}/code-security/configurations", + firstParams=NotSet.remove_unset_items({"target_type": target_type}), + ) + + def create_code_security_config( + self, + name: str, + description: str, + advanced_security: Opt[str] = NotSet, + dependency_graph: Opt[str] = NotSet, + dependency_graph_autosubmit_action: Opt[str] = NotSet, + dependabot_alerts: Opt[str] = NotSet, + dependabot_security_updates: Opt[str] = NotSet, + code_scanning_default_setup: Opt[str] = NotSet, + secret_scanning: Opt[str] = NotSet, + secret_scanning_push_protection: Opt[str] = NotSet, + secret_scanning_delegated_bypass: Opt[str] = NotSet, + secret_scanning_validity_checks: Opt[str] = NotSet, + secret_scanning_non_provider_patterns: Opt[str] = NotSet, + private_vulnerability_reporting: Opt[str] = NotSet, + enforcement: Opt[str] = NotSet, + ) -> CodeSecurityConfig: + """ + :calls: `POST /orgs/{org}/code-security/configurations `_ + :rtype: :class:`PaginatedList` of dict + """ + assert isinstance(name, str), name + assert isinstance(description, str), description + assert is_optional(advanced_security, str), advanced_security + assert is_optional(dependency_graph, str), dependency_graph + assert is_optional(dependency_graph_autosubmit_action, str), dependency_graph_autosubmit_action + assert is_optional(dependabot_alerts, str), dependabot_alerts + assert is_optional(dependabot_security_updates, str), dependabot_security_updates + assert is_optional(code_scanning_default_setup, str), code_scanning_default_setup + assert is_optional(secret_scanning, str), secret_scanning + assert is_optional(secret_scanning_push_protection, str), secret_scanning_push_protection + assert is_optional(secret_scanning_delegated_bypass, str), secret_scanning_delegated_bypass + assert is_optional(secret_scanning_validity_checks, str), secret_scanning_validity_checks + assert is_optional(secret_scanning_non_provider_patterns, str), secret_scanning_non_provider_patterns + assert is_optional(private_vulnerability_reporting, str), private_vulnerability_reporting + assert is_optional(enforcement, str), enforcement + post_parameters = NotSet.remove_unset_items( + { + "name": name, + "description": description, + "advanced_security": advanced_security, + "dependency_graph": dependency_graph, + "dependency_graph_autosubmit_action": dependency_graph_autosubmit_action, + "dependabot_alerts": dependabot_alerts, + "dependabot_security_updates": dependabot_security_updates, + "code_scanning_default_setup": code_scanning_default_setup, + "secret_scanning": secret_scanning, + "secret_scanning_push_protection": secret_scanning_push_protection, + "secret_scanning_delegated_bypass": secret_scanning_delegated_bypass, + "secret_scanning_validity_checks": secret_scanning_validity_checks, + "secret_scanning_non_provider_patterns": secret_scanning_non_provider_patterns, + "private_vulnerability_reporting": private_vulnerability_reporting, + "enforcement": enforcement, + } + ) + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/code-security/configurations", + input=post_parameters, + headers={"Accept": Consts.repoVisibilityPreview}, + ) + return github.CodeSecurityConfig.CodeSecurityConfig(self._requester, headers, data) + + def edit_code_security_config( + self, + id: int, + name: Opt[str] = NotSet, + description: Opt[str] = NotSet, + advanced_security: Opt[str] = NotSet, + dependency_graph: Opt[str] = NotSet, + dependency_graph_autosubmit_action: Opt[str] = NotSet, + dependabot_alerts: Opt[str] = NotSet, + dependabot_security_updates: Opt[str] = NotSet, + code_scanning_default_setup: Opt[str] = NotSet, + secret_scanning: Opt[str] = NotSet, + secret_scanning_push_protection: Opt[str] = NotSet, + secret_scanning_delegated_bypass: Opt[str] = NotSet, + secret_scanning_validity_checks: Opt[str] = NotSet, + secret_scanning_non_provider_patterns: Opt[str] = NotSet, + private_vulnerability_reporting: Opt[str] = NotSet, + enforcement: Opt[str] = NotSet, + ) -> CodeSecurityConfig: + """ + :calls: `PATCH /orgs/{org}/code-security/configurations/{configuration_id} `_ + """ + assert isinstance(id, int), id + assert is_optional(name, str), name + assert is_optional(description, str), description + assert is_optional(advanced_security, str), advanced_security + assert is_optional(dependency_graph, str), dependency_graph + assert is_optional(dependency_graph_autosubmit_action, str), dependency_graph_autosubmit_action + assert is_optional(dependabot_alerts, str), dependabot_alerts + assert is_optional(dependabot_security_updates, str), dependabot_security_updates + assert is_optional(code_scanning_default_setup, str), code_scanning_default_setup + assert is_optional(secret_scanning, str), secret_scanning + assert is_optional(secret_scanning_push_protection, str), secret_scanning_push_protection + assert is_optional(secret_scanning_delegated_bypass, str), secret_scanning_delegated_bypass + assert is_optional(secret_scanning_validity_checks, str), secret_scanning_validity_checks + assert is_optional(secret_scanning_non_provider_patterns, str), secret_scanning_non_provider_patterns + assert is_optional(private_vulnerability_reporting, str), private_vulnerability_reporting + assert is_optional(enforcement, str), enforcement + post_parameters = NotSet.remove_unset_items( + { + "name": name, + "description": description, + "advanced_security": advanced_security, + "dependency_graph": dependency_graph, + "dependency_graph_autosubmit_action": dependency_graph_autosubmit_action, + "dependabot_alerts": dependabot_alerts, + "dependabot_security_updates": dependabot_security_updates, + "code_scanning_default_setup": code_scanning_default_setup, + "secret_scanning": secret_scanning, + "secret_scanning_push_protection": secret_scanning_push_protection, + "secret_scanning_delegated_bypass": secret_scanning_delegated_bypass, + "secret_scanning_validity_checks": secret_scanning_validity_checks, + "secret_scanning_non_provider_patterns": secret_scanning_non_provider_patterns, + "private_vulnerability_reporting": private_vulnerability_reporting, + "enforcement": enforcement, + } + ) + + headers, data = self._requester.requestJsonAndCheck( + "PATCH", f"{self.url}/code-security/configurations/{id}", input=post_parameters + ) + return github.CodeSecurityConfig.CodeSecurityConfig(self._requester, headers, data) + + def delete_code_security_config(self, id: int) -> None: + """ + :calls: `DELETE /orgs/{org}/code-security/configurations/{configuration_id} `_ + :param id: integer + :rtype: None` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/code-security/configurations/{id}") + + def get_code_security_config(self, id: int) -> CodeSecurityConfig: + """ + :calls: `GET /orgs/{org}/code-security/configurations/{configuration_id} `_ + :param id: configuration_id + :rtype: CodeSecurityConfig + """ + assert isinstance(id, int), id + + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/code-security/configurations/{id}") + return github.CodeSecurityConfig.CodeSecurityConfig(self._requester, headers, data) + + def set_default_code_security_config(self, id: int, default_for_new_repos: Opt[str] = NotSet) -> None: + """ + :calls: `PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults `_ + """ + assert isinstance(id, int), id + assert is_optional(default_for_new_repos, str), default_for_new_repos + put_parameters = NotSet.remove_unset_items({"default_for_new_repos": default_for_new_repos}) + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/code-security/configurations/{id}/defaults", input=put_parameters + ) + + def get_default_code_security_configs(self) -> PaginatedList[DefaultCodeSecurityConfig]: + """ + :calls: `GET /orgs/{org}/code-security/configurations/defaults `_ + :rtype: :class:`github.DefaultCodeSecurityConfig.DefaultCodeSecurityConfig` + """ + return PaginatedList( + contentClass=github.DefaultCodeSecurityConfig.DefaultCodeSecurityConfig, + requester=self._requester, + firstUrl=f"{self.url}/code-security/configurations/defaults", + firstParams=None, + ) + + def attach_security_config_to_repositories( + self, id: int, scope: str, selected_repository_ids: Opt[list[int]] = NotSet + ) -> None: + """ + :calls: `POST /orgs/{org}/code-security/configurations/{configuration_id}/attach `_ + """ + assert isinstance(id, int), id + assert isinstance(scope, str), scope + assert is_optional(selected_repository_ids, list), selected_repository_ids + post_parameters: dict[str, Any] = NotSet.remove_unset_items( + { + "scope": scope, + "selected_repository_ids": selected_repository_ids, + } + ) + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"/orgs/{self.login}/code-security/configurations/{id}/attach", + input=post_parameters, + headers={"Accept": Consts.repoVisibilityPreview}, + ) + + def detach_security_config_from_repositories(self, selected_repository_ids: list[int]) -> None: + """ + :calls: `DELETE /orgs/{org}/code-security/configurations/detach `_ + """ + assert isinstance(selected_repository_ids, list), selected_repository_ids + delete_parameters: dict[str, Any] = NotSet.remove_unset_items( + { + "selected_repository_ids": selected_repository_ids, + } + ) + headers, data = self._requester.requestJsonAndCheck( + "DELETE", + f"/orgs/{self.login}/code-security/configurations/detach", + input=delete_parameters, + headers={"Accept": Consts.repoVisibilityPreview}, + ) + + def get_repos_for_code_security_config( + self, id: int, status: Opt[str] = NotSet + ) -> PaginatedList[CodeSecurityConfigRepository]: + """ + :calls: `GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories `_ + """ + assert isinstance(id, int), id + assert is_optional(status, str), status + + url_parameters = NotSet.remove_unset_items({"status": status}) + + return PaginatedList( + github.CodeSecurityConfigRepository.CodeSecurityConfigRepository, + self._requester, + f"{self.url}/code-security/configurations/{id}/repositories", + url_parameters, + headers={"Accept": Consts.repoVisibilityPreview}, + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "advanced_security_enabled_for_new_repositories" in attributes: # pragma no branch + self._advanced_security_enabled_for_new_repositories = self._makeBoolAttribute( + attributes["advanced_security_enabled_for_new_repositories"] + ) + if "archived_at" in attributes: # pragma no branch + assert attributes["archived_at"] is None or isinstance(attributes["archived_at"], str), attributes[ + "archived_at" + ] + self._archived_at = self._makeDatetimeAttribute(attributes["archived_at"]) + if "avatar_url" in attributes: # pragma no branch + self._avatar_url = self._makeStringAttribute(attributes["avatar_url"]) + if "billing_email" in attributes: # pragma no branch + self._billing_email = self._makeStringAttribute(attributes["billing_email"]) + if "blog" in attributes: # pragma no branch + self._blog = self._makeStringAttribute(attributes["blog"]) + if "collaborators" in attributes: # pragma no branch + self._collaborators = self._makeIntAttribute(attributes["collaborators"]) + if "company" in attributes: # pragma no branch + self._company = self._makeStringAttribute(attributes["company"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "default_repository_permission" in attributes: # pragma no branch + self._default_repository_permission = self._makeStringAttribute(attributes["default_repository_permission"]) + if "dependabot_alerts_enabled_for_new_repositories" in attributes: # pragma no branch + self._dependabot_alerts_enabled_for_new_repositories = self._makeBoolAttribute( + attributes["dependabot_alerts_enabled_for_new_repositories"] + ) + if "dependabot_security_updates_enabled_for_new_repositories" in attributes: # pragma no branch + self._dependabot_security_updates_enabled_for_new_repositories = self._makeBoolAttribute( + attributes["dependabot_security_updates_enabled_for_new_repositories"] + ) + if "dependency_graph_enabled_for_new_repositories" in attributes: # pragma no branch + self._dependency_graph_enabled_for_new_repositories = self._makeBoolAttribute( + attributes["dependency_graph_enabled_for_new_repositories"] + ) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "disk_usage" in attributes: # pragma no branch + self._disk_usage = self._makeIntAttribute(attributes["disk_usage"]) + if "display_login" in attributes: # pragma no branch + self._display_login = self._makeStringAttribute(attributes["display_login"]) + if "email" in attributes: # pragma no branch + self._email = self._makeStringAttribute(attributes["email"]) + if "events_url" in attributes: # pragma no branch + self._events_url = self._makeStringAttribute(attributes["events_url"]) + if "followers" in attributes: # pragma no branch + self._followers = self._makeIntAttribute(attributes["followers"]) + if "following" in attributes: # pragma no branch + self._following = self._makeIntAttribute(attributes["following"]) + if "gravatar_id" in attributes: # pragma no branch + self._gravatar_id = self._makeStringAttribute(attributes["gravatar_id"]) + if "has_organization_projects" in attributes: # pragma no branch + self._has_organization_projects = self._makeBoolAttribute(attributes["has_organization_projects"]) + if "has_repository_projects" in attributes: # pragma no branch + self._has_repository_projects = self._makeBoolAttribute(attributes["has_repository_projects"]) + if "hooks_url" in attributes: # pragma no branch + self._hooks_url = self._makeStringAttribute(attributes["hooks_url"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "is_verified" in attributes: # pragma no branch + self._is_verified = self._makeBoolAttribute(attributes["is_verified"]) + if "issues_url" in attributes: # pragma no branch + self._issues_url = self._makeStringAttribute(attributes["issues_url"]) + if "location" in attributes: # pragma no branch + self._location = self._makeStringAttribute(attributes["location"]) + if "login" in attributes: # pragma no branch + self._login = self._makeStringAttribute(attributes["login"]) + if "members_allowed_repository_creation_type" in attributes: # pragma no branch + self._members_allowed_repository_creation_type = self._makeStringAttribute( + attributes["members_allowed_repository_creation_type"] + ) + if "members_can_create_internal_repositories" in attributes: # pragma no branch + self._members_can_create_internal_repositories = self._makeBoolAttribute( + attributes["members_can_create_internal_repositories"] + ) + if "members_can_create_pages" in attributes: # pragma no branch + self._members_can_create_pages = self._makeBoolAttribute(attributes["members_can_create_pages"]) + if "members_can_create_private_pages" in attributes: # pragma no branch + self._members_can_create_private_pages = self._makeBoolAttribute( + attributes["members_can_create_private_pages"] + ) + if "members_can_create_private_repositories" in attributes: # pragma no branch + self._members_can_create_private_repositories = self._makeBoolAttribute( + attributes["members_can_create_private_repositories"] + ) + if "members_can_create_public_pages" in attributes: # pragma no branch + self._members_can_create_public_pages = self._makeBoolAttribute( + attributes["members_can_create_public_pages"] + ) + if "members_can_create_public_repositories" in attributes: # pragma no branch + self._members_can_create_public_repositories = self._makeBoolAttribute( + attributes["members_can_create_public_repositories"] + ) + if "members_can_create_repositories" in attributes: # pragma no branch + self._members_can_create_repositories = self._makeBoolAttribute( + attributes["members_can_create_repositories"] + ) + if "members_can_fork_private_repositories" in attributes: # pragma no branch + self._members_can_fork_private_repositories = self._makeBoolAttribute( + attributes["members_can_fork_private_repositories"] + ) + if "members_url" in attributes: # pragma no branch + self._members_url = self._makeStringAttribute(attributes["members_url"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "owned_private_repos" in attributes: # pragma no branch + self._owned_private_repos = self._makeIntAttribute(attributes["owned_private_repos"]) + if "plan" in attributes: # pragma no branch + self._plan = self._makeClassAttribute(github.Plan.Plan, attributes["plan"]) + if "private_gists" in attributes: # pragma no branch + self._private_gists = self._makeIntAttribute(attributes["private_gists"]) + if "public_gists" in attributes: # pragma no branch + self._public_gists = self._makeIntAttribute(attributes["public_gists"]) + if "public_members_url" in attributes: # pragma no branch + self._public_members_url = self._makeStringAttribute(attributes["public_members_url"]) + if "public_repos" in attributes: # pragma no branch + self._public_repos = self._makeIntAttribute(attributes["public_repos"]) + if "repos_url" in attributes: # pragma no branch + self._repos_url = self._makeStringAttribute(attributes["repos_url"]) + if "secret_scanning_enabled_for_new_repositories" in attributes: # pragma no branch + self._secret_scanning_enabled_for_new_repositories = self._makeBoolAttribute( + attributes["secret_scanning_enabled_for_new_repositories"] + ) + if "secret_scanning_push_protection_custom_link" in attributes: # pragma no branch + self._secret_scanning_push_protection_custom_link = self._makeStringAttribute( + attributes["secret_scanning_push_protection_custom_link"] + ) + if "secret_scanning_push_protection_custom_link_enabled" in attributes: # pragma no branch + self._secret_scanning_push_protection_custom_link_enabled = self._makeBoolAttribute( + attributes["secret_scanning_push_protection_custom_link_enabled"] + ) + if "secret_scanning_push_protection_enabled_for_new_repositories" in attributes: # pragma no branch + self._secret_scanning_push_protection_enabled_for_new_repositories = self._makeBoolAttribute( + attributes["secret_scanning_push_protection_enabled_for_new_repositories"] + ) + if "total_private_repos" in attributes: # pragma no branch + self._total_private_repos = self._makeIntAttribute(attributes["total_private_repos"]) + if "twitter_username" in attributes: # pragma no branch + self._twitter_username = self._makeStringAttribute(attributes["twitter_username"]) + if "two_factor_requirement_enabled" in attributes: # pragma no branch + self._two_factor_requirement_enabled = self._makeBoolAttribute(attributes["two_factor_requirement_enabled"]) + if "type" in attributes: # pragma no branch + self._type = self._makeStringAttribute(attributes["type"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "web_commit_signoff_required" in attributes: # pragma no branch + self._web_commit_signoff_required = self._makeBoolAttribute(attributes["web_commit_signoff_required"]) diff --git a/python_embeded/Lib/site-packages/github/OrganizationCustomProperty.py b/python_embeded/Lib/site-packages/github/OrganizationCustomProperty.py new file mode 100644 index 0000000000000000000000000000000000000000..53f935ba1fd2929bd0641b77e2a0e36aa45ebfab --- /dev/null +++ b/python_embeded/Lib/site-packages/github/OrganizationCustomProperty.py @@ -0,0 +1,183 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2024 Jacky Lam # +# Copyright 2024 Kian-Meng Ang # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet, Opt, is_optional + + +class CustomProperty: + """ + This class represents a CustomProperty for an Organization. Use this class to create a new post parameter object. + + The reference can be found here + https://docs.github.com/en/rest/orgs/custom-properties#create-or-update-custom-properties-for-an-organization + + """ + + def __init__( + self, + property_name: str, + value_type: str, + required: Opt[bool] = NotSet, + default_value: Opt[None | str | list[str]] = NotSet, + description: Opt[str | None] = NotSet, + allowed_values: Opt[list[str] | None] = NotSet, + values_editable_by: Opt[str | None] = NotSet, + ): + assert isinstance(property_name, str), property_name + assert isinstance(value_type, str), value_type + assert value_type in ["string", "single_select"], value_type + assert is_optional(required, bool), required + assert is_optional(default_value, (type(None), str, list)), default_value + assert is_optional(description, (str, type(None))), description + assert is_optional(allowed_values, (list, type(None))), allowed_values + assert is_optional(values_editable_by, (str, type(None))), values_editable_by + if values_editable_by is not NotSet: + assert values_editable_by in ["org_actors", "org_and_repo_actors"], values_editable_by + + self.property_name = property_name + self.value_type = value_type + self.required = required + self.default_value = default_value + self.description = description + self.allowed_values = allowed_values + self.values_editable_by = values_editable_by + + def to_dict(self) -> dict[str, Any]: + return NotSet.remove_unset_items(self.__dict__) + + +class OrganizationCustomProperty(NonCompletableGithubObject): + """ + This class represents a CustomProperty for an Organization. + + The reference can be found here + https://docs.github.com/en/rest/orgs/custom-properties + + The OpenAPI schema can be found at + - /components/schemas/custom-property + + """ + + def _initAttributes(self) -> None: + self._allowed_values: Attribute[list[str]] = NotSet + self._default_value: Attribute[str | list[str]] = NotSet + self._description: Attribute[str] = NotSet + self._property_name: Attribute[str] = NotSet + self._required: Attribute[bool] = NotSet + self._url: Attribute[str] = NotSet + self._value_type: Attribute[str] = NotSet + self._values_editable_by: Attribute[str] = NotSet + + @property + def allowed_values(self) -> Opt[list[str] | None]: + return self._allowed_values.value + + @property + def default_value(self) -> Opt[str | list[str] | None]: + return self._default_value.value + + @property + def description(self) -> Opt[str | None]: + return self._description.value + + @property + def property_name(self) -> str: + return self._property_name.value + + @property + def required(self) -> Opt[bool | None]: + return self._required.value + + @property + def url(self) -> str: + return self._url.value + + @property + def value_type(self) -> str: + return self._value_type.value + + @property + def values_editable_by(self) -> Opt[str | None]: + return self._values_editable_by.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "allowed_values" in attributes: + self._allowed_values = self._makeListOfStringsAttribute(attributes["allowed_values"]) + if "default_value" in attributes: + self._default_value = self._makeStringAttribute(attributes["default_value"]) + if "description" in attributes: + self._description = self._makeStringAttribute(attributes["description"]) + if "property_name" in attributes: # pragma no branch + self._property_name = self._makeStringAttribute(attributes["property_name"]) + if "required" in attributes: + self._required = self._makeBoolAttribute(attributes["required"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "value_type" in attributes: # pragma no branch + self._value_type = self._makeStringAttribute(attributes["value_type"]) + if "values_editable_by" in attributes: + self._values_editable_by = self._makeStringAttribute(attributes["values_editable_by"]) + + +class RepositoryCustomPropertyValues(NonCompletableGithubObject): + """ + This class represents CustomPropertyValues for a Repository. + + The reference can be found here + https://docs.github.com/en/rest/orgs/custom-properties#list-custom-property-values-for-organization-repositories + + """ + + def _initAttributes(self) -> None: + self._properties: Attribute[dict[str, str]] = NotSet + self._repository_full_name: Attribute[str] = NotSet + self._repository_id: Attribute[int] = NotSet + self._repository_name: Attribute[str] = NotSet + + @property + def properties(self) -> dict[str, str]: + return self._properties.value + + @property + def repository_full_name(self) -> str: + return self._repository_full_name.value + + @property + def repository_name(self) -> str: + return self._repository_name.value + + @property + def repository_id(self) -> int: + return self._repository_id.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + self._repository_id = self._makeIntAttribute(attributes["repository_id"]) + self._repository_name = self._makeStringAttribute(attributes["repository_name"]) + self._repository_full_name = self._makeStringAttribute(attributes["repository_full_name"]) + properties = {p["property_name"]: p["value"] for p in attributes["properties"]} + self._properties = self._makeDictAttribute(properties) diff --git a/python_embeded/Lib/site-packages/github/OrganizationDependabotAlert.py b/python_embeded/Lib/site-packages/github/OrganizationDependabotAlert.py new file mode 100644 index 0000000000000000000000000000000000000000..ec1fcb1486704224667d14e968a015bb1c57a1c7 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/OrganizationDependabotAlert.py @@ -0,0 +1,58 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Thomas Cooper # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.DependabotAlert import DependabotAlert +from github.GithubObject import Attribute, NotSet +from github.Repository import Repository + + +class OrganizationDependabotAlert(DependabotAlert): + """ + This class represents a Dependabot alert on an organization. + + The reference can be found here + https://docs.github.com/en/rest/dependabot/alerts#list-dependabot-alerts-for-an-organization + + The OpenAPI schema can be found at + - /components/schemas/dependabot-alert-with-repository + + """ + + def _initAttributes(self) -> None: + super()._initAttributes() + self._repository: Attribute[Repository] = NotSet + + @property + def repository(self) -> Repository: + return self._repository.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + super()._useAttributes(attributes) + if "repository" in attributes: + self._repository = self._makeClassAttribute(Repository, attributes["repository"]) diff --git a/python_embeded/Lib/site-packages/github/OrganizationSecret.py b/python_embeded/Lib/site-packages/github/OrganizationSecret.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0cbd1d398268896091ce7447a7c1f6d16bbf16 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/OrganizationSecret.py @@ -0,0 +1,138 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Thomas Crowley <15927917+thomascrowley@users.noreply.github.com># +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from datetime import datetime +from typing import Any, Dict + +from github.GithubObject import Attribute, NotSet +from github.PaginatedList import PaginatedList +from github.Repository import Repository +from github.Secret import Secret + + +class OrganizationSecret(Secret): + """ + This class represents a org level GitHub secret. + + The reference can be found here + https://docs.github.com/en/rest/actions/secrets + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._name: Attribute[str] = NotSet + self._selected_repositories: Attribute[PaginatedList[Repository]] = NotSet + self._selected_repositories_url: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._visibility: Attribute[str] = NotSet + + @property + def visibility(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._visibility) + return self._visibility.value + + @property + def selected_repositories(self) -> PaginatedList[Repository]: + return PaginatedList( + Repository, + self._requester, + self._selected_repositories_url.value, + None, + list_item="repositories", + ) + + def edit( + self, + value: str, + visibility: str = "all", + secret_type: str = "actions", + ) -> bool: + """ + :calls: `PATCH /orgs/{org}/{secret_type}/secrets/{variable_name} `_ + :param variable_name: string + :param value: string + :param visibility: string + :param secret_type: string options actions or dependabot + :rtype: bool + """ + assert isinstance(value, str), value + assert isinstance(visibility, str), visibility + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + + patch_parameters: Dict[str, Any] = { + "name": self.name, + "value": value, + "visibility": visibility, + } + + status, _, _ = self._requester.requestJson( + "PATCH", + f"{self.url}/{secret_type}/secrets/{self.name}", + input=patch_parameters, + ) + return status == 204 + + def add_repo(self, repo: Repository) -> bool: + """ + :calls: 'PUT {org_url}/actions/secrets/{secret_name} `_ + :param repo: github.Repository.Repository + :rtype: bool + """ + if self.visibility != "selected": + return False + self._requester.requestJsonAndCheck("PUT", f"{self._selected_repositories_url.value}/{repo.id}") + return True + + def remove_repo(self, repo: Repository) -> bool: + """ + :calls: 'DELETE {org_url}/actions/secrets/{secret_name} `_ + :param repo: github.Repository.Repository + :rtype: bool + """ + if self.visibility != "selected": + return False + self._requester.requestJsonAndCheck("DELETE", f"{self._selected_repositories_url.value}/{repo.id}") + return True + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "created_at" in attributes: + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "name" in attributes: + self._name = self._makeStringAttribute(attributes["name"]) + if "selected_repositories_url" in attributes: + self._selected_repositories_url = self._makeStringAttribute(attributes["selected_repositories_url"]) + if "updated_at" in attributes: + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: + self._url = self._makeStringAttribute(attributes["url"]) + if "visibility" in attributes: + self._visibility = self._makeStringAttribute(attributes["visibility"]) diff --git a/python_embeded/Lib/site-packages/github/OrganizationVariable.py b/python_embeded/Lib/site-packages/github/OrganizationVariable.py new file mode 100644 index 0000000000000000000000000000000000000000..8abd430868e30ad2b4bd8820fa8869bedbbe3f1a --- /dev/null +++ b/python_embeded/Lib/site-packages/github/OrganizationVariable.py @@ -0,0 +1,134 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from datetime import datetime +from typing import Any, Dict + +from github.GithubObject import Attribute, NotSet +from github.PaginatedList import PaginatedList +from github.Repository import Repository +from github.Variable import Variable + + +class OrganizationVariable(Variable): + """ + This class represents a org level GitHub variable. + + The reference can be found here + https://docs.github.com/en/rest/actions/variables + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._name: Attribute[str] = NotSet + self._selected_repositories: Attribute[PaginatedList[Repository]] = NotSet + self._selected_repositories_url: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._visibility: Attribute[str] = NotSet + + @property + def visibility(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._visibility) + return self._visibility.value + + @property + def selected_repositories(self) -> PaginatedList[Repository]: + return PaginatedList( + Repository, + self._requester, + self._selected_repositories_url.value, + None, + list_item="repositories", + ) + + def edit( + self, + value: str, + visibility: str = "all", + ) -> bool: + """ + :calls: `PATCH /orgs/{org}/actions/variables/{variable_name} `_ + :param variable_name: string + :param value: string + :param visibility: string + :rtype: bool + """ + assert isinstance(value, str), value + assert isinstance(visibility, str), visibility + + patch_parameters: Dict[str, Any] = { + "name": self.name, + "value": value, + "visibility": visibility, + } + + status, _, _ = self._requester.requestJson( + "PATCH", + f"{self.url}/actions/variables/{self.name}", + input=patch_parameters, + ) + return status == 204 + + def add_repo(self, repo: Repository) -> bool: + """ + :calls: 'PUT {org_url}/actions/variables/{variable_name} `_ + :param repo: github.Repository.Repository + :rtype: bool + """ + if self.visibility != "selected": + return False + self._requester.requestJsonAndCheck("PUT", f"{self._selected_repositories_url.value}/{repo.id}") + return True + + def remove_repo(self, repo: Repository) -> bool: + """ + :calls: 'DELETE {org_url}/actions/variables/{variable_name} `_ + :param repo: github.Repository.Repository + :rtype: bool + """ + if self.visibility != "selected": + return False + self._requester.requestJsonAndCheck("DELETE", f"{self._selected_repositories_url.value}/{repo.id}") + return True + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "created_at" in attributes: + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "name" in attributes: + self._name = self._makeStringAttribute(attributes["name"]) + if "selected_repositories_url" in attributes: + self._selected_repositories_url = self._makeStringAttribute(attributes["selected_repositories_url"]) + if "updated_at" in attributes: + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: + self._url = self._makeStringAttribute(attributes["url"]) + if "visibility" in attributes: + self._visibility = self._makeStringAttribute(attributes["visibility"]) diff --git a/python_embeded/Lib/site-packages/github/PaginatedList.py b/python_embeded/Lib/site-packages/github/PaginatedList.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbe4caae3d09b5d0e93000e2724a9fdaa31197f --- /dev/null +++ b/python_embeded/Lib/site-packages/github/PaginatedList.py @@ -0,0 +1,441 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Bill Mill # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 davidbrai # +# Copyright 2014 Thialfihar # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Dan Vanderkam # +# Copyright 2015 Eliot Walker # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Jannis Gebauer # +# Copyright 2018 Gilad Shefer # +# Copyright 2018 Joel Koglin # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 netsgnut <284779+netsgnut@users.noreply.github.com> # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Emir Hodzic # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2023 YugoHino # +# Copyright 2024 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Callable, Dict, Generic, Iterator, List, Optional, Type, TypeVar, Union +from urllib.parse import parse_qs + +from github.GithubObject import GithubObject +from github.Requester import Requester + +T = TypeVar("T", bound=GithubObject) + + +class PaginatedListBase(Generic[T]): + __elements: List[T] + + def _couldGrow(self) -> bool: + raise NotImplementedError + + def _fetchNextPage(self) -> List[T]: + raise NotImplementedError + + def __init__(self, elements: Optional[List[T]] = None) -> None: + self.__elements = [] if elements is None else elements + + def __getitem__(self, index: Union[int, slice]) -> Any: + assert isinstance(index, (int, slice)) + if isinstance(index, int): + self.__fetchToIndex(index) + return self.__elements[index] + else: + return self._Slice(self, index) + + def __iter__(self) -> Iterator[T]: + yield from self.__elements + while self._couldGrow(): + newElements = self._grow() + yield from newElements + + def _isBiggerThan(self, index: int) -> bool: + return len(self.__elements) > index or self._couldGrow() + + def __fetchToIndex(self, index: int) -> None: + while len(self.__elements) <= index and self._couldGrow(): + self._grow() + + def _grow(self) -> List[T]: + newElements = self._fetchNextPage() + self.__elements += newElements + return newElements + + class _Slice: + def __init__(self, theList: "PaginatedListBase[T]", theSlice: slice): + self.__list = theList + self.__start = theSlice.start or 0 + self.__stop = theSlice.stop + self.__step = theSlice.step or 1 + + def __iter__(self) -> Iterator[T]: + index = self.__start + while not self.__finished(index): + if self.__list._isBiggerThan(index): + yield self.__list[index] + index += self.__step + else: + return + + def __finished(self, index: int) -> bool: + return self.__stop is not None and index >= self.__stop + + +class PaginatedList(PaginatedListBase[T]): + """ + This class abstracts the `pagination of the REST API `_ + and the GraphQl API `_. + + You can simply enumerate through instances of this class:: + + for repo in user.get_repos(): + print(repo.name) + + If you want to know the total number of items in the list:: + + print(user.get_repos().totalCount) + + You can also index them or take slices:: + + second_repo = user.get_repos()[1] + first_repos = user.get_repos()[:10] + + If you want to iterate in reversed order, just do:: + + for repo in user.get_repos().reversed: + print(repo.name) + + And if you really need it, you can explicitly access a specific page:: + + repos = user.get_repos() + assert repos.is_rest, "get_page not supported by the GraphQL API" + + some_repos = repos.get_page(0) + some_other_repos = repos.get_page(3) + """ + + # v3: move * before firstUrl and fix call sites + def __init__( + self, + contentClass: Type[T], + requester: Requester, + firstUrl: Optional[str] = None, + firstParams: Optional[Dict[str, Any]] = None, + *, + headers: Optional[Dict[str, str]] = None, + list_item: Union[str, List[str]] = "items", + total_count_item: str = "total_count", + firstData: Optional[Any] = None, + firstHeaders: Optional[Dict[str, Union[str, int]]] = None, + attributesTransformer: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None, + graphql_query: Optional[str] = None, + graphql_variables: Optional[Dict[str, Any]] = None, + ): + if firstUrl is None and firstData is None and graphql_query is None: + raise ValueError("Either firstUrl or graphql_query must be given") + if firstUrl is not None and graphql_query is not None: + raise ValueError("Only one of firstUrl or graphql_query can be given") + if graphql_query is not None: + if not (isinstance(list_item, list) and all(isinstance(item, str) for item in list_item)): + raise ValueError("With graphql_query given, item_list must be a list of strings") + + self.__requester = requester + self.__contentClass = contentClass + + self.__is_rest = firstUrl is not None or firstData is not None + self.__firstUrl = firstUrl + self.__firstParams: Dict[str, Any] = firstParams or {} + self.__nextUrl = firstUrl + self.__nextParams: Dict[str, Any] = firstParams or {} + self.__headers = headers + self.__list_item = list_item + self.__total_count_item = total_count_item + if self.__requester.per_page != 30: + self.__nextParams["per_page"] = self.__requester.per_page + self._reversed = False + self.__totalCount: Optional[int] = None + self._attributesTransformer = attributesTransformer + + self.__graphql_query = graphql_query + self.__graphql_variables = graphql_variables or {} + self.__page_info = None + + first_page = [] + if firstData is not None: + first_page = self._getPage(firstData, firstHeaders) + # this paginated list contains a single page + if self.__nextUrl is None and self.__totalCount is None: + self.__totalCount = len(first_page) + super().__init__(first_page) + + @property + def is_rest(self) -> bool: + return self.__is_rest + + @property + def is_graphql(self) -> bool: + return not self.is_rest + + def _transformAttributes(self, element: Dict[str, Any]) -> Dict[str, Any]: + if self._attributesTransformer is None: + return element + return self._attributesTransformer(element) + + @property + def totalCount(self) -> int: + if self.__totalCount is None: + if self.is_rest: + params = self.__nextParams.copy() + # set per_page = 1 so the totalCount is just the number of pages + params.update({"per_page": 1}) + headers, data = self.__requester.requestJsonAndCheck( + "GET", self.__firstUrl, parameters=params, headers=self.__headers # type: ignore + ) + if "link" not in headers: + if data and "total_count" in data: + self.__totalCount = data["total_count"] + elif data: + if isinstance(data, dict): + data = data[self.__list_item] + self.__totalCount = len(data) + else: + self.__totalCount = 0 + else: + links = self.__parseLinkHeader(headers) + lastUrl = links.get("last") + if lastUrl: + self.__totalCount = int(parse_qs(lastUrl)["page"][0]) + else: + self.__totalCount = 0 + else: + variables = self.__graphql_variables.copy() + if not self._reversed: + variables["first"] = 1 + variables["after"] = None + else: + variables["last"] = 1 + variables["before"] = None + + _, data = self.__requester.graphql_query(self.__graphql_query, variables) # type: ignore + pagination = self._get_graphql_pagination(data["data"], self.__list_item) # type: ignore + self.__totalCount = pagination.get("totalCount") + return self.__totalCount # type: ignore + + def _getLastPageUrl(self) -> Optional[str]: + headers, data = self.__requester.requestJsonAndCheck( + "GET", self.__firstUrl, parameters=self.__nextParams, headers=self.__headers # type: ignore + ) + links = self.__parseLinkHeader(headers) + return links.get("last") + + @property + def reversed(self) -> "PaginatedList[T]": + r = PaginatedList( + self.__contentClass, + self.__requester, + self.__firstUrl, + self.__firstParams, + headers=self.__headers, + list_item=self.__list_item, + attributesTransformer=self._attributesTransformer, + graphql_query=self.__graphql_query, + graphql_variables=self.__graphql_variables, + ) + r.__reverse() + return r + + def __reverse(self) -> None: + self._reversed = True + if self.is_rest: + lastUrl = self._getLastPageUrl() + if lastUrl: + self.__nextUrl = lastUrl + if self.__nextParams: + # #2929: remove all parameters from self.__nextParams contained in self.__nextUrl + self.__nextParams = { + k: v + for k, v in self.__nextParams.items() + if k not in Requester.get_parameters_of_url(self.__nextUrl).keys() + } + + def _couldGrow(self) -> bool: + return ( + self.is_rest + and self.__nextUrl is not None + or self.is_graphql + and ( + self.__page_info is None + or not self._reversed + and self.__page_info["hasNextPage"] + or self._reversed + and self.__page_info["hasPreviousPage"] + ) + ) + + def _get_graphql_pagination(self, data: Dict[str, Any], path: List[str]) -> Dict[str, Any]: + for item in path: + if item not in data: + raise RuntimeError(f"Pagination path {path} not found in data: {self.paths_of_dict(data)}") + data = data[item] + return data + + def _fetchNextPage(self) -> List[T]: + if self.is_rest: + # REST API pagination + headers, data = self.__requester.requestJsonAndCheck( + "GET", self.__nextUrl, parameters=self.__nextParams, headers=self.__headers # type: ignore + ) + data = data if data else [] + return self._getPage(data, headers) + else: + # GraphQL API pagination + variables = self.__graphql_variables.copy() + if not self._reversed: + variables["first"] = self.__requester.per_page + if self.__page_info is not None: + variables["after"] = self.__page_info["endCursor"] + else: + variables["last"] = self.__requester.per_page + if self.__page_info is not None: + variables["before"] = self.__page_info["startCursor"] + + _, data = self.__requester.graphql_query(self.__graphql_query, variables) # type: ignore + + pagination = self._get_graphql_pagination(data["data"], self.__list_item) # type: ignore + return self._getPage(pagination, {}) + + def _getPage(self, data: Any, headers: Optional[Dict[str, Union[str, int]]]) -> List[T]: + if self.is_rest: + self.__nextUrl = None # type: ignore + if len(data) > 0: + links = self.__parseLinkHeader(headers) # type: ignore + if self._reversed: + if "prev" in links: + self.__nextUrl = links["prev"] + elif "next" in links: + self.__nextUrl = links["next"] + self.__nextParams = {} + if self.__list_item in data: + self.__totalCount = data.get(self.__total_count_item) + data = data[self.__list_item] + content = [ + self.__contentClass(self.__requester, headers, self._transformAttributes(element)) # type: ignore + for element in data + if element is not None + ] + if self._reversed: + return content[::-1] + return content + else: + if "pageInfo" not in data: + raise RuntimeError(f"Query must provide pagination with pageInfo:\n{self.__graphql_query}") + + self.__page_info = data["pageInfo"] + if any( + item not in self.__page_info # type: ignore + for item in ["startCursor", "endCursor", "hasNextPage", "hasPreviousPage"] + ): + raise RuntimeError(f"Query must provide pagination with pageInfo\n{self.__graphql_query}") + + if self.__totalCount is None: + if "totalCount" not in data: + raise RuntimeError(f"Query must provide totalCount\n{self.__graphql_query}") + self.__totalCount = data["totalCount"] + + if "nodes" not in data: + raise RuntimeError( + f"No nodes found under pagination path {self.__list_item}: {self.paths_of_dict(data)}" + ) + + nodes = data["nodes"] + if self._reversed: + nodes = nodes[::-1] + return [self.__contentClass(self.__requester, {}, element) for element in nodes if element is not None] + + def __parseLinkHeader(self, headers: Dict[str, Union[str, int]]) -> Dict[str, str]: + links = {} + if "link" in headers and isinstance(headers["link"], str): + linkHeaders = headers["link"].split(", ") + for linkHeader in linkHeaders: + url, rel, *rest = linkHeader.split("; ") + url = url[1:-1] + rel = rel[5:-1] + links[rel] = url + return links + + def get_page(self, page: int) -> List[T]: + if self.is_graphql: + raise RuntimeError("Not supported for GraphQL pagination") + + params = dict(self.__firstParams) + if page != 0: + params["page"] = page + 1 + if self.__requester.per_page != 30: + params["per_page"] = self.__requester.per_page + headers, data = self.__requester.requestJsonAndCheck( + "GET", self.__firstUrl, parameters=params, headers=self.__headers # type: ignore + ) + + if self.__list_item in data: + self.__totalCount = data.get("total_count") + data = data[self.__list_item] + return [self.__contentClass(self.__requester, headers, self._transformAttributes(element)) for element in data] + + @classmethod + def override_attributes(cls, overrides: Dict[str, Any]) -> Callable[[Dict[str, Any]], Dict[str, Any]]: + def attributes_transformer(element: Dict[str, Any]) -> Dict[str, Any]: + # Recursively merge overrides with attributes, overriding attributes with overrides + element = cls.merge_dicts(element, overrides) + return element + + return attributes_transformer + + @classmethod + def merge_dicts(cls, d1: Dict[str, Any], d2: Dict[str, Any]) -> Dict[str, Any]: + # clone d1 + d1 = d1.copy() + for k, v in d2.items(): + if isinstance(v, dict): + d1[k] = cls.merge_dicts(d1.get(k, {}), v) + else: + d1[k] = v + return d1 + + @classmethod + def paths_of_dict(cls, d: dict) -> dict: + return {key: cls.paths_of_dict(val) if isinstance(val, dict) else None for key, val in d.items()} diff --git a/python_embeded/Lib/site-packages/github/Path.py b/python_embeded/Lib/site-packages/github/Path.py new file mode 100644 index 0000000000000000000000000000000000000000..07e036af0996b998249c264b5774f1ffa97bf99d --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Path.py @@ -0,0 +1,98 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Justin Kufro # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class Path(NonCompletableGithubObject): + """ + This class represents a popular Path for a GitHub repository. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#traffic + + The OpenAPI schema can be found at + - /components/schemas/content-traffic + + """ + + def _initAttributes(self) -> None: + self._count: Attribute[int] = NotSet + self._path: Attribute[str] = NotSet + self._title: Attribute[str] = NotSet + self._uniques: Attribute[int] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "path": self._path.value, + "title": self._title.value, + "count": self._count.value, + "uniques": self._uniques.value, + } + ) + + @property + def count(self) -> int: + return self._count.value + + @property + def path(self) -> str: + return self._path.value + + @property + def title(self) -> str: + return self._title.value + + @property + def uniques(self) -> int: + return self._uniques.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "count" in attributes: # pragma no branch + self._count = self._makeIntAttribute(attributes["count"]) + if "path" in attributes: # pragma no branch + self._path = self._makeStringAttribute(attributes["path"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "uniques" in attributes: # pragma no branch + self._uniques = self._makeIntAttribute(attributes["uniques"]) diff --git a/python_embeded/Lib/site-packages/github/Permissions.py b/python_embeded/Lib/site-packages/github/Permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..4abba205519ccd581c427216a7e720e5294ab62e --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Permissions.py @@ -0,0 +1,107 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 karsten-wagner <39054096+karsten-wagner@users.noreply.github.com># +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class Permissions(NonCompletableGithubObject): + """ + This class represents Permissions. + + The OpenAPI schema can be found at + - /components/schemas/collaborator/properties/permissions + - /components/schemas/full-repository/properties/permissions + - /components/schemas/minimal-repository/properties/permissions + - /components/schemas/repo-search-result-item/properties/permissions + - /components/schemas/repository/properties/permissions + - /components/schemas/team/properties/permissions + + """ + + def _initAttributes(self) -> None: + self._admin: Attribute[bool] = NotSet + self._maintain: Attribute[bool] = NotSet + self._pull: Attribute[bool] = NotSet + self._push: Attribute[bool] = NotSet + self._triage: Attribute[bool] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "admin": self._admin.value, + "maintain": self._maintain.value, + "pull": self._pull.value, + "push": self._push.value, + "triage": self._triage.value, + } + ) + + @property + def admin(self) -> bool: + return self._admin.value + + @property + def maintain(self) -> bool: + return self._maintain.value + + @property + def pull(self) -> bool: + return self._pull.value + + @property + def push(self) -> bool: + return self._push.value + + @property + def triage(self) -> bool: + return self._triage.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "admin" in attributes: # pragma no branch + self._admin = self._makeBoolAttribute(attributes["admin"]) + if "maintain" in attributes: # pragma no branch + self._maintain = self._makeBoolAttribute(attributes["maintain"]) + if "pull" in attributes: # pragma no branch + self._pull = self._makeBoolAttribute(attributes["pull"]) + if "push" in attributes: # pragma no branch + self._push = self._makeBoolAttribute(attributes["push"]) + if "triage" in attributes: # pragma no branch + self._triage = self._makeBoolAttribute(attributes["triage"]) diff --git a/python_embeded/Lib/site-packages/github/Plan.py b/python_embeded/Lib/site-packages/github/Plan.py new file mode 100644 index 0000000000000000000000000000000000000000..e1f1a39d9bb1447be064f4395bef25cf2a1a09fe --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Plan.py @@ -0,0 +1,103 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Geoff Low # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class Plan(NonCompletableGithubObject): + """ + This class represents Plans. + + The OpenAPI schema can be found at + - /components/schemas/organization-full/properties/plan + - /components/schemas/public-user/properties/plan + - /components/schemas/team-organization/properties/plan + + """ + + def _initAttributes(self) -> None: + self._collaborators: Attribute[int] = NotSet + self._filled_seats: Attribute[int] = NotSet + self._name: Attribute[str] = NotSet + self._private_repos: Attribute[int] = NotSet + self._seats: Attribute[int] = NotSet + self._space: Attribute[int] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value}) + + @property + def collaborators(self) -> int: + return self._collaborators.value + + @property + def filled_seats(self) -> int: + return self._filled_seats.value + + @property + def name(self) -> str: + return self._name.value + + @property + def private_repos(self) -> int: + return self._private_repos.value + + @property + def seats(self) -> int: + return self._seats.value + + @property + def space(self) -> int: + return self._space.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "collaborators" in attributes: # pragma no branch + self._collaborators = self._makeIntAttribute(attributes["collaborators"]) + if "filled_seats" in attributes: # pragma no branch + self._filled_seats = self._makeIntAttribute(attributes["filled_seats"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "private_repos" in attributes: # pragma no branch + self._private_repos = self._makeIntAttribute(attributes["private_repos"]) + if "seats" in attributes: # pragma no branch + self._seats = self._makeIntAttribute(attributes["seats"]) + if "space" in attributes: # pragma no branch + self._space = self._makeIntAttribute(attributes["space"]) diff --git a/python_embeded/Lib/site-packages/github/Project.py b/python_embeded/Lib/site-packages/github/Project.py new file mode 100644 index 0000000000000000000000000000000000000000..900e76a54050f591373e1b991b7e231e76127892 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Project.py @@ -0,0 +1,265 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Chris McBride # +# Copyright 2017 Simon # +# Copyright 2018 Benoit Latinier # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 Yossarian King # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Anuj Bansal # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Lars Kellogg-Stedman # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.NamedUser +import github.ProjectColumn +from github import Consts +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt +from github.PaginatedList import PaginatedList + + +class Project(CompletableGithubObject): + """ + This class represents Projects. + + The reference can be found here + https://docs.github.com/en/rest/reference/projects + + The OpenAPI schema can be found at + - /components/schemas/project + + """ + + def _initAttributes(self) -> None: + self._body: Attribute[str] = NotSet + self._columns_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._creator: Attribute[github.NamedUser.NamedUser] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._number: Attribute[int] = NotSet + self._organization_permission: Attribute[str] = NotSet + self._owner_url: Attribute[str] = NotSet + self._private: Attribute[bool] = NotSet + self._state: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value}) + + @property + def body(self) -> str: + self._completeIfNotSet(self._body) + return self._body.value + + @property + def columns_url(self) -> str: + self._completeIfNotSet(self._columns_url) + return self._columns_url.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def creator(self) -> github.NamedUser.NamedUser: + self._completeIfNotSet(self._creator) + return self._creator.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def number(self) -> int: + self._completeIfNotSet(self._number) + return self._number.value + + @property + def organization_permission(self) -> str: + self._completeIfNotSet(self._organization_permission) + return self._organization_permission.value + + @property + def owner_url(self) -> str: + self._completeIfNotSet(self._owner_url) + return self._owner_url.value + + @property + def private(self) -> bool: + self._completeIfNotSet(self._private) + return self._private.value + + @property + def state(self) -> str: + self._completeIfNotSet(self._state) + return self._state.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def delete(self) -> None: + """ + :calls: `DELETE /projects/{project_id} `_ + """ + headers, data = self._requester.requestJsonAndCheck( + "DELETE", self.url, headers={"Accept": Consts.mediaTypeProjectsPreview} + ) + + def edit( + self, + name: Opt[str] = NotSet, + body: Opt[str] = NotSet, + state: Opt[str] = NotSet, + organization_permission: Opt[str] = NotSet, + private: Opt[bool] = NotSet, + ) -> None: + """ + :calls: `PATCH /projects/{project_id} `_ + """ + assert name is NotSet or isinstance(name, str), name + assert body is NotSet or isinstance(body, str), body + assert state is NotSet or isinstance(state, str), state + assert organization_permission is NotSet or isinstance(organization_permission, str), organization_permission + assert private is NotSet or isinstance(private, bool), private + patch_parameters = NotSet.remove_unset_items( + { + "name": name, + "body": body, + "state": state, + "organization_permission": organization_permission, + "private": private, + } + ) + + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + self._useAttributes(data) + + def get_columns(self) -> PaginatedList[github.ProjectColumn.ProjectColumn]: + """ + :calls: `GET /projects/{project_id}/columns `_ + """ + + return PaginatedList( + github.ProjectColumn.ProjectColumn, + self._requester, + self.columns_url, + None, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + + def create_column(self, name: str) -> github.ProjectColumn.ProjectColumn: + """ + calls: `POST /projects/{project_id}/columns `_ + """ + assert isinstance(name, str), name + post_parameters = {"name": name} + import_header = {"Accept": Consts.mediaTypeProjectsPreview} + headers, data = self._requester.requestJsonAndCheck( + "POST", f"{self.url}/columns", headers=import_header, input=post_parameters + ) + return github.ProjectColumn.ProjectColumn(self._requester, headers, data, completed=True) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "columns_url" in attributes: # pragma no branch + self._columns_url = self._makeStringAttribute(attributes["columns_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "creator" in attributes: # pragma no branch + self._creator = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["creator"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "number" in attributes: # pragma no branch + self._number = self._makeIntAttribute(attributes["number"]) + if "organization_permission" in attributes: # pragma no branch + self._organization_permission = self._makeStringAttribute(attributes["organization_permission"]) + if "owner_url" in attributes: # pragma no branch + self._owner_url = self._makeStringAttribute(attributes["owner_url"]) + if "private" in attributes: # pragma no branch + self._private = self._makeBoolAttribute(attributes["private"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/ProjectCard.py b/python_embeded/Lib/site-packages/github/ProjectCard.py new file mode 100644 index 0000000000000000000000000000000000000000..34e2ce94be92a5df0e6e877bedf5b5b5cf333866 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/ProjectCard.py @@ -0,0 +1,225 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Matt Babineau # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Martijn Koster # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 Yossarian King # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Jody McIntyre # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 chloe jungah kim <43295963+chloeeekim@users.noreply.github.com># +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.Issue +import github.NamedUser +import github.ProjectColumn +import github.PullRequest +from github import Consts +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt + +# NOTE: There is currently no way to get cards "in triage" for a project. +# https://platform.github.community/t/moving-github-project-cards-that-are-in-triage/3784 +# +# See also https://developer.github.com/v4/object/projectcard for the next generation GitHub API, +# which may point the way to where the API is likely headed and what might come back to v3. E.g. ProjectCard.content member. + + +class ProjectCard(CompletableGithubObject): + """ + This class represents Project Cards. + + The reference can be found here + https://docs.github.com/en/rest/reference/projects#cards + + The OpenAPI schema can be found at + - /components/schemas/project-card + - /components/schemas/validation-error + - /components/schemas/validation-error-simple + - /paths/"/projects/columns/{column_id}/cards"/post/responses/503/content/"application/json"/schema + + """ + + def _initAttributes(self) -> None: + self._archived: Attribute[bool] = NotSet + self._column_url: Attribute[str] = NotSet + self._content_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._creator: Attribute[github.NamedUser.NamedUser] = NotSet + self._id: Attribute[int] = NotSet + self._node_id: Attribute[str] = NotSet + self._note: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value}) + + @property + def archived(self) -> bool: + return self._archived.value + + @property + def column_url(self) -> str: + return self._column_url.value + + @property + def content_url(self) -> str: + return self._content_url.value + + @property + def created_at(self) -> datetime: + return self._created_at.value + + @property + def creator(self) -> github.NamedUser.NamedUser: + return self._creator.value + + @property + def id(self) -> int: + return self._id.value + + @property + def node_id(self) -> str: + return self._node_id.value + + @property + def note(self) -> str: + return self._note.value + + @property + def updated_at(self) -> datetime: + return self._updated_at.value + + @property + def url(self) -> str: + return self._url.value + + # Note that the content_url for any card will be an "issue" URL, from + # which you can retrieve either an Issue or a PullRequest. Unfortunately + # the API doesn't make it clear which you are dealing with. + def get_content( + self, content_type: Opt[str] = NotSet + ) -> github.PullRequest.PullRequest | github.Issue.Issue | None: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number} `_ + """ + assert content_type is NotSet or isinstance(content_type, str), content_type + if self.content_url is None: + return None + + retclass: type[github.PullRequest.PullRequest] | type[github.Issue.Issue] + if content_type == "PullRequest": + url = self.content_url.replace("issues", "pulls") + retclass = github.PullRequest.PullRequest + elif content_type is NotSet or content_type == "Issue": + url = self.content_url + retclass = github.Issue.Issue + else: + raise ValueError(f"Unknown content type: {content_type}") + headers, data = self._requester.requestJsonAndCheck("GET", url) + return retclass(self._requester, headers, data, completed=True) + + def move(self, position: str, column: github.ProjectColumn.ProjectColumn | int) -> bool: + """ + :calls: `POST /projects/columns/cards/{card_id}/moves `_ + """ + assert isinstance(position, str), position + assert isinstance(column, github.ProjectColumn.ProjectColumn) or isinstance(column, int), column + post_parameters = { + "position": position, + "column_id": column.id if isinstance(column, github.ProjectColumn.ProjectColumn) else column, + } + status, _, _ = self._requester.requestJson( + "POST", + f"{self.url}/moves", + input=post_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + return status == 201 + + def delete(self) -> bool: + """ + :calls: `DELETE /projects/columns/cards/{card_id} `_ + """ + status, _, _ = self._requester.requestJson( + "DELETE", + self.url, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + return status == 204 + + def edit(self, note: Opt[str] = NotSet, archived: Opt[bool] = NotSet) -> None: + """ + :calls: `PATCH /projects/columns/cards/{card_id} `_ + """ + assert note is NotSet or isinstance(note, str), note + assert archived is NotSet or isinstance(archived, bool), archived + patch_parameters: dict[str, Any] = NotSet.remove_unset_items({"note": note, "archived": archived}) + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + self._useAttributes(data) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "archived" in attributes: # pragma no branch + self._archived = self._makeBoolAttribute(attributes["archived"]) + if "column_url" in attributes: # pragma no branch + self._column_url = self._makeStringAttribute(attributes["column_url"]) + if "content_url" in attributes: # pragma no branch + self._content_url = self._makeStringAttribute(attributes["content_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "creator" in attributes: # pragma no branch + self._creator = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["creator"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "note" in attributes: # pragma no branch + self._note = self._makeStringAttribute(attributes["note"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/ProjectColumn.py b/python_embeded/Lib/site-packages/github/ProjectColumn.py new file mode 100644 index 0000000000000000000000000000000000000000..ad4cfb4fb9e7fa548e15035bd70e8174e308c5aa --- /dev/null +++ b/python_embeded/Lib/site-packages/github/ProjectColumn.py @@ -0,0 +1,221 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Matt Babineau # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Martijn Koster # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 Yossarian King # +# Copyright 2018 sfdye # +# Copyright 2019 Benoit Latinier # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Vincent # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Alice GIRARD # +# Copyright 2020 Florent Clarret # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Dhruv Bhanushali # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.Project +import github.ProjectCard +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt +from github.PaginatedList import PaginatedList + +from . import Consts + + +class ProjectColumn(CompletableGithubObject): + """ + This class represents Project Columns. + + The reference can be found here + https://docs.github.com/en/rest/reference/projects#columns + + The OpenAPI schema can be found at + - /components/schemas/project-column + + """ + + def _initAttributes(self) -> None: + self._cards_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._id: Attribute[int] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._project_url: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value}) + + @property + def cards_url(self) -> str: + return self._cards_url.value + + @property + def created_at(self) -> datetime: + return self._created_at.value + + @property + def id(self) -> int: + return self._id.value + + @property + def name(self) -> str: + return self._name.value + + @property + def node_id(self) -> str: + return self._node_id.value + + @property + def project_url(self) -> str: + return self._project_url.value + + @property + def updated_at(self) -> datetime: + return self._updated_at.value + + @property + def url(self) -> str: + return self._url.value + + def get_cards(self, archived_state: Opt[str] = NotSet) -> PaginatedList[github.ProjectCard.ProjectCard]: + """ + :calls: `GET /projects/columns/{column_id}/cards `_ + """ + assert archived_state is NotSet or isinstance(archived_state, str), archived_state + + url_parameters = dict() + if archived_state is not NotSet: + url_parameters["archived_state"] = archived_state + + return PaginatedList( + github.ProjectCard.ProjectCard, + self._requester, + f"{self.url}/cards", + url_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + + def create_card( + self, + note: Opt[str] = NotSet, + content_id: Opt[int] = NotSet, + content_type: Opt[str] = NotSet, + ) -> github.ProjectCard.ProjectCard: + """ + :calls: `POST /projects/columns/{column_id}/cards `_ + """ + if isinstance(note, str): + assert content_id is NotSet, content_id + assert content_type is NotSet, content_type + post_parameters: dict[str, Any] = {"note": note} + else: + assert note is NotSet, note + assert isinstance(content_id, int), content_id + assert isinstance(content_type, str), content_type + post_parameters = {"content_id": content_id, "content_type": content_type} + + import_header = {"Accept": Consts.mediaTypeProjectsPreview} + headers, data = self._requester.requestJsonAndCheck( + "POST", f"{self.url}/cards", headers=import_header, input=post_parameters + ) + return github.ProjectCard.ProjectCard(self._requester, headers, data, completed=True) + + def move(self, position: str) -> bool: + """ + :calls: `POST POST /projects/columns/{column_id}/moves `_ + """ + assert isinstance(position, str), position + post_parameters = {"position": position} + status, _, _ = self._requester.requestJson( + "POST", + f"{self.url}/moves", + input=post_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + return status == 201 + + def delete(self) -> bool: + """ + :calls: `DELETE /projects/columns/{column_id} `_ + """ + status, _, _ = self._requester.requestJson( + "DELETE", + self.url, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + return status == 204 + + def edit(self, name: str) -> None: + """ + :calls: `PATCH /projects/columns/{column_id} `_ + """ + assert isinstance(name, str), name + patch_parameters = {"name": name} + + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + + self._useAttributes(data) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "cards_url" in attributes: # pragma no branch + self._cards_url = self._makeStringAttribute(attributes["cards_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "project_url" in attributes: # pragma no branch + self._project_url = self._makeStringAttribute(attributes["project_url"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/PublicKey.py b/python_embeded/Lib/site-packages/github/PublicKey.py new file mode 100644 index 0000000000000000000000000000000000000000..8459b3d0d4ed1db15a13946e6b95f0be356e9962 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/PublicKey.py @@ -0,0 +1,136 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Chris Keating # +# Copyright 2021 MeggyCal # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +# https://docs.github.com/en/rest/reference/actions#example-encrypting-a-secret-using-python +from __future__ import annotations + +from base64 import b64encode +from typing import Any + +from nacl import encoding, public + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +def encrypt(public_key: str, secret_value: str) -> str: + """ + Encrypt a Unicode string using the public key. + """ + pk = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder) + sealed_box = public.SealedBox(pk) + encrypted = sealed_box.encrypt(secret_value.encode("utf-8")) + return b64encode(encrypted).decode("utf-8") + + +class PublicKey(CompletableGithubObject): + """ + This class represents either an organization public key or a repository public key. + + The reference can be found here + https://docs.github.com/en/rest/reference/actions#get-an-organization-public-key + or here + https://docs.github.com/en/rest/reference/actions#get-a-repository-public-key + + The OpenAPI schema can be found at + - /components/schemas/actions-public-key + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._key: Attribute[str] = NotSet + self._key_id: Attribute[str | int] = NotSet + self._title: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"key_id": self._key_id.value, "key": self._key.value}) + + @property + def created_at(self) -> str: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def key(self) -> str: + self._completeIfNotSet(self._key) + return self._key.value + + @property + def key_id(self) -> str | int: + self._completeIfNotSet(self._key_id) + return self._key_id.value + + @property + def title(self) -> str: + self._completeIfNotSet(self._title) + return self._title.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def encrypt(self, unencrypted_value: str) -> str: + return encrypt(self._key.value, unencrypted_value) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeStringAttribute(attributes["created_at"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "key" in attributes: # pragma no branch + self._key = self._makeStringAttribute(attributes["key"]) + if "key_id" in attributes: # pragma no branch + if isinstance(attributes["key_id"], str): + self._key_id = self._makeStringAttribute(attributes["key_id"]) + else: + self._key_id = self._makeIntAttribute(attributes["key_id"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/PullRequest.py b/python_embeded/Lib/site-packages/github/PullRequest.py new file mode 100644 index 0000000000000000000000000000000000000000..5bcf95817e42b184c0b4c737479c4f744210dbe9 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/PullRequest.py @@ -0,0 +1,1141 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Michael Stead # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 @tmshn # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Aaron Levine # +# Copyright 2017 Simon # +# Copyright 2018 Ben Yohay # +# Copyright 2018 Brian J. Murrell # +# Copyright 2018 Gilad Shefer # +# Copyright 2018 Martin Monperrus # +# Copyright 2018 Matt Babineau <9685860+babineaum@users.noreply.github.com> # +# Copyright 2018 Shinichi TAMURA # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Thibault Jamet # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 per1234 # +# Copyright 2018 sfdye # +# Copyright 2019 MarcoFalke # +# Copyright 2019 Mark Browning # +# Copyright 2019 MurphyZhao # +# Copyright 2019 Olof-Joachim Frahm (欧雅福) # +# Copyright 2019 Pavan Kunisetty # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Tim Gates # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Alice GIRARD # +# Copyright 2020 Florent Clarret # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2022 tison # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Heitor Polidoro <14806300+heitorpolidoro@users.noreply.github.com># +# Copyright 2023 Heitor Polidoro # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2023 sd-kialo <138505487+sd-kialo@users.noreply.github.com> # +# Copyright 2023 vanya20074 # +# Copyright 2024 Austin Sasko # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Evan Fetsko # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Kobbi Gal <85439776+kgal-pan@users.noreply.github.com> # +# Copyright 2025 Bruno Didot # +# Copyright 2025 Enrico Minack # +# Copyright 2025 Ryan Peach # +# Copyright 2025 a-sido # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import urllib.parse +from datetime import datetime +from typing import TYPE_CHECKING, Any + +from typing_extensions import NotRequired, TypedDict + +import github.Commit +import github.File +import github.IssueComment +import github.IssueEvent +import github.Label +import github.Milestone +import github.NamedUser +import github.PaginatedList +import github.PullRequestComment +import github.PullRequestMergeStatus +import github.PullRequestPart +import github.PullRequestReview +import github.Team +from github import Consts +from github.GithubObject import ( + Attribute, + CompletableGithubObject, + NotSet, + Opt, + is_defined, + is_optional, + is_optional_list, + is_undefined, +) +from github.Issue import Issue +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.Commit import Commit + from github.File import File + from github.GitRef import GitRef + from github.IssueComment import IssueComment + from github.IssueEvent import IssueEvent + from github.Label import Label + from github.Milestone import Milestone + from github.NamedUser import NamedUser + from github.PullRequestComment import PullRequestComment + from github.PullRequestMergeStatus import PullRequestMergeStatus + from github.PullRequestPart import PullRequestPart + from github.PullRequestReview import PullRequestReview + from github.Team import Team + + +class ReviewComment(TypedDict): + path: str + position: NotRequired[int] + body: str + line: NotRequired[int] + side: NotRequired[str] + start_line: NotRequired[int] + start_side: NotRequired[str] + + +class PullRequest(CompletableGithubObject): + """ + This class represents PullRequests. + + The reference can be found here + https://docs.github.com/en/rest/reference/pulls + + The OpenAPI schema can be found at + - /components/schemas/pull-request + - /components/schemas/pull-request-minimal + - /components/schemas/pull-request-simple + + """ + + def _initAttributes(self) -> None: + self.__links: Attribute[dict[str, Any]] = NotSet + self._active_lock_reason: Attribute[str] = NotSet + self._additions: Attribute[int] = NotSet + self._assignee: Attribute[NamedUser] = NotSet + self._assignees: Attribute[list[NamedUser]] = NotSet + self._author_association: Attribute[str] = NotSet + self._auto_merge: Attribute[dict[str, Any]] = NotSet + self._base: Attribute[PullRequestPart] = NotSet + self._body: Attribute[str] = NotSet + self._changed_files: Attribute[int] = NotSet + self._closed_at: Attribute[datetime | None] = NotSet + self._comments: Attribute[int] = NotSet + self._comments_url: Attribute[str] = NotSet + self._commits: Attribute[int] = NotSet + self._commits_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._deletions: Attribute[int] = NotSet + self._diff_url: Attribute[str] = NotSet + self._draft: Attribute[bool] = NotSet + self._head: Attribute[PullRequestPart] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._issue_url: Attribute[str] = NotSet + self._labels: Attribute[list[Label]] = NotSet + self._locked: Attribute[bool] = NotSet + self._maintainer_can_modify: Attribute[bool] = NotSet + self._merge_commit_sha: Attribute[str] = NotSet + self._mergeable: Attribute[bool] = NotSet + self._mergeable_state: Attribute[str] = NotSet + self._merged: Attribute[bool] = NotSet + self._merged_at: Attribute[datetime | None] = NotSet + self._merged_by: Attribute[NamedUser] = NotSet + self._milestone: Attribute[Milestone] = NotSet + self._node_id: Attribute[str] = NotSet + self._number: Attribute[int] = NotSet + self._patch_url: Attribute[str] = NotSet + self._rebaseable: Attribute[bool] = NotSet + self._requested_reviewers: Attribute[list[NamedUser]] = NotSet + self._requested_teams: Attribute[list[Team]] = NotSet + self._review_comment_url: Attribute[str] = NotSet + self._review_comments: Attribute[int] = NotSet + self._review_comments_url: Attribute[str] = NotSet + self._state: Attribute[str] = NotSet + self._statuses_url: Attribute[str] = NotSet + self._title: Attribute[str] = NotSet + self._updated_at: Attribute[datetime | None] = NotSet + self._url: Attribute[str] = NotSet + self._user: Attribute[NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"number": self._number.value, "title": self._title.value}) + + @property + def _links(self) -> dict[str, Any]: + self._completeIfNotSet(self.__links) + return self.__links.value + + @property + def active_lock_reason(self) -> str: + self._completeIfNotSet(self._active_lock_reason) + return self._active_lock_reason.value + + @property + def additions(self) -> int: + self._completeIfNotSet(self._additions) + return self._additions.value + + @property + def assignee(self) -> NamedUser: + self._completeIfNotSet(self._assignee) + return self._assignee.value + + @property + def assignees(self) -> list[NamedUser]: + self._completeIfNotSet(self._assignees) + return self._assignees.value + + @property + def author_association(self) -> str: + self._completeIfNotSet(self._author_association) + return self._author_association.value + + @property + def auto_merge(self) -> dict[str, Any]: + self._completeIfNotSet(self._auto_merge) + return self._auto_merge.value + + @property + def base(self) -> PullRequestPart: + self._completeIfNotSet(self._base) + return self._base.value + + @property + def body(self) -> str: + self._completeIfNotSet(self._body) + return self._body.value + + @property + def changed_files(self) -> int: + self._completeIfNotSet(self._changed_files) + return self._changed_files.value + + @property + def closed_at(self) -> datetime | None: + self._completeIfNotSet(self._closed_at) + return self._closed_at.value + + @property + def comments(self) -> int: + self._completeIfNotSet(self._comments) + return self._comments.value + + @property + def comments_url(self) -> str: + self._completeIfNotSet(self._comments_url) + return self._comments_url.value + + @property + def commits(self) -> int: + self._completeIfNotSet(self._commits) + return self._commits.value + + @property + def commits_url(self) -> str: + self._completeIfNotSet(self._commits_url) + return self._commits_url.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def deletions(self) -> int: + self._completeIfNotSet(self._deletions) + return self._deletions.value + + @property + def diff_url(self) -> str: + self._completeIfNotSet(self._diff_url) + return self._diff_url.value + + @property + def draft(self) -> bool: + self._completeIfNotSet(self._draft) + return self._draft.value + + @property + def head(self) -> PullRequestPart: + self._completeIfNotSet(self._head) + return self._head.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def issue_url(self) -> str: + self._completeIfNotSet(self._issue_url) + return self._issue_url.value + + @property + def labels(self) -> list[Label]: + self._completeIfNotSet(self._labels) + return self._labels.value + + @property + def locked(self) -> bool: + self._completeIfNotSet(self._locked) + return self._locked.value + + @property + def maintainer_can_modify(self) -> bool: + self._completeIfNotSet(self._maintainer_can_modify) + return self._maintainer_can_modify.value + + @property + def merge_commit_sha(self) -> str: + self._completeIfNotSet(self._merge_commit_sha) + return self._merge_commit_sha.value + + @property + def mergeable(self) -> bool: + self._completeIfNotSet(self._mergeable) + return self._mergeable.value + + @property + def mergeable_state(self) -> str: + self._completeIfNotSet(self._mergeable_state) + return self._mergeable_state.value + + @property + def merged(self) -> bool: + self._completeIfNotSet(self._merged) + return self._merged.value + + @property + def merged_at(self) -> datetime | None: + self._completeIfNotSet(self._merged_at) + return self._merged_at.value + + @property + def merged_by(self) -> NamedUser: + self._completeIfNotSet(self._merged_by) + return self._merged_by.value + + @property + def milestone(self) -> Milestone: + self._completeIfNotSet(self._milestone) + return self._milestone.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def number(self) -> int: + self._completeIfNotSet(self._number) + return self._number.value + + @property + def patch_url(self) -> str: + self._completeIfNotSet(self._patch_url) + return self._patch_url.value + + @property + def rebaseable(self) -> bool: + self._completeIfNotSet(self._rebaseable) + return self._rebaseable.value + + @property + def requested_reviewers(self) -> list[NamedUser]: + self._completeIfNotSet(self._requested_reviewers) + return self._requested_reviewers.value + + @property + def requested_teams(self) -> list[Team]: + self._completeIfNotSet(self._requested_teams) + return self._requested_teams.value + + @property + def review_comment_url(self) -> str: + self._completeIfNotSet(self._review_comment_url) + return self._review_comment_url.value + + @property + def review_comments(self) -> int: + self._completeIfNotSet(self._review_comments) + return self._review_comments.value + + @property + def review_comments_url(self) -> str: + self._completeIfNotSet(self._review_comments_url) + return self._review_comments_url.value + + @property + def state(self) -> str: + self._completeIfNotSet(self._state) + return self._state.value + + @property + def statuses_url(self) -> str: + self._completeIfNotSet(self._statuses_url) + return self._statuses_url.value + + @property + def title(self) -> str: + self._completeIfNotSet(self._title) + return self._title.value + + @property + def updated_at(self) -> datetime | None: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def user(self) -> NamedUser: + self._completeIfNotSet(self._user) + return self._user.value + + def as_issue(self) -> Issue: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number} `_ + """ + headers, data = self._requester.requestJsonAndCheck("GET", self.issue_url) + return github.Issue.Issue(self._requester, headers, data, completed=True) + + def create_comment(self, body: str, commit: github.Commit.Commit, path: str, position: int) -> PullRequestComment: + """ + :calls: `POST /repos/{owner}/{repo}/pulls/{number}/comments `_ + """ + return self.create_review_comment(body, commit, path, position) + + def create_review_comment( + self, + body: str, + commit: github.Commit.Commit, + path: str, + # line replaces deprecated position argument, so we put it between path and side + line: Opt[int] = NotSet, + side: Opt[str] = NotSet, + start_line: Opt[int] = NotSet, + start_side: Opt[str] = NotSet, + in_reply_to: Opt[int] = NotSet, + subject_type: Opt[str] = NotSet, + as_suggestion: bool = False, + ) -> PullRequestComment: + """ + :calls: `POST /repos/{owner}/{repo}/pulls/{number}/comments `_ + """ + assert isinstance(body, str), body + assert isinstance(commit, github.Commit.Commit), commit + assert isinstance(path, str), path + assert is_optional(line, int), line + assert is_undefined(side) or side in ["LEFT", "RIGHT"], side + assert is_optional(start_line, int), start_line + assert is_undefined(start_side) or start_side in [ + "LEFT", + "RIGHT", + "side", + ], start_side + assert is_optional(in_reply_to, int), in_reply_to + assert is_undefined(subject_type) or subject_type in [ + "line", + "file", + ], subject_type + assert isinstance(as_suggestion, bool), as_suggestion + + if as_suggestion: + body = f"```suggestion\n{body}\n```" + post_parameters = NotSet.remove_unset_items( + { + "body": body, + "commit_id": commit._identity, + "path": path, + "line": line, + "side": side, + "start_line": start_line, + "start_side": start_side, + "in_reply_to": in_reply_to, + "subject_type": subject_type, + } + ) + + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/comments", input=post_parameters) + return github.PullRequestComment.PullRequestComment(self._requester, headers, data, completed=True) + + def create_review_comment_reply(self, comment_id: int, body: str) -> PullRequestComment: + """ + :calls: `POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies `_ + """ + assert isinstance(comment_id, int), comment_id + assert isinstance(body, str), body + post_parameters = {"body": body} + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/comments/{comment_id}/replies", + input=post_parameters, + ) + return github.PullRequestComment.PullRequestComment(self._requester, headers, data, completed=True) + + def create_issue_comment(self, body: str) -> IssueComment: + """ + :calls: `POST /repos/{owner}/{repo}/issues/{number}/comments `_ + """ + assert isinstance(body, str), body + post_parameters = { + "body": body, + } + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.issue_url}/comments", input=post_parameters) + return github.IssueComment.IssueComment(self._requester, headers, data, completed=True) + + def create_review( + self, + commit: Opt[github.Commit.Commit] = NotSet, + body: Opt[str] = NotSet, + event: Opt[str] = NotSet, + comments: Opt[list[ReviewComment]] = NotSet, + ) -> PullRequestReview: + """ + :calls: `POST /repos/{owner}/{repo}/pulls/{number}/reviews `_ + """ + assert is_optional(commit, github.Commit.Commit), commit + assert is_optional(body, str), body + assert is_optional(event, str), event + assert is_optional_list(comments, dict), comments + post_parameters: dict[str, Any] = NotSet.remove_unset_items({"body": body}) + post_parameters["event"] = "COMMENT" if is_undefined(event) else event + if is_defined(commit): + post_parameters["commit_id"] = commit.sha + if is_defined(comments): + post_parameters["comments"] = comments + else: + post_parameters["comments"] = [] + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/reviews", input=post_parameters) + return github.PullRequestReview.PullRequestReview(self._requester, headers, data) + + def create_review_request( + self, + reviewers: Opt[list[str] | str] = NotSet, + team_reviewers: Opt[list[str] | str] = NotSet, + ) -> None: + """ + :calls: `POST /repos/{owner}/{repo}/pulls/{number}/requested_reviewers `_ + """ + assert is_optional(reviewers, str) or is_optional_list(reviewers, str), reviewers + assert is_optional(team_reviewers, str) or is_optional_list(team_reviewers, str), team_reviewers + + if isinstance(reviewers, str): + reviewers = [reviewers] + if isinstance(team_reviewers, str): + team_reviewers = [team_reviewers] + + post_parameters = NotSet.remove_unset_items({"reviewers": reviewers, "team_reviewers": team_reviewers}) + + headers, data = self._requester.requestJsonAndCheck( + "POST", f"{self.url}/requested_reviewers", input=post_parameters + ) + + def delete_review_request( + self, + reviewers: Opt[list[str] | str] = NotSet, + team_reviewers: Opt[list[str] | str] = NotSet, + ) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/pulls/{number}/requested_reviewers `_ + """ + assert is_optional(reviewers, str) or is_optional_list(reviewers, str), reviewers + assert is_optional(team_reviewers, str) or is_optional_list(team_reviewers, str), team_reviewers + + if isinstance(reviewers, str): + reviewers = [reviewers] + if isinstance(team_reviewers, str): + team_reviewers = [team_reviewers] + + post_parameters = NotSet.remove_unset_items({"reviewers": reviewers, "team_reviewers": team_reviewers}) + + headers, data = self._requester.requestJsonAndCheck( + "DELETE", f"{self.url}/requested_reviewers", input=post_parameters + ) + + def edit( + self, + title: Opt[str] = NotSet, + body: Opt[str] = NotSet, + state: Opt[str] = NotSet, + base: Opt[str] = NotSet, + maintainer_can_modify: Opt[bool] = NotSet, + ) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/pulls/{number} `_ + """ + assert is_optional(title, str), title + assert is_optional(body, str), body + assert is_optional(state, str), state + assert is_optional(base, str), base + assert is_optional(maintainer_can_modify, bool), maintainer_can_modify + post_parameters = NotSet.remove_unset_items( + {"title": title, "body": body, "state": state, "base": base, "maintainer_can_modify": maintainer_can_modify} + ) + + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def get_comment(self, id: int) -> PullRequestComment: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/comments/{number} `_ + """ + return self.get_review_comment(id) + + def get_review_comment(self, id: int) -> PullRequestComment: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/comments/{number} `_ + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self._parentUrl(self.url)}/comments/{id}") + return github.PullRequestComment.PullRequestComment(self._requester, headers, data, completed=True) + + def get_comments( + self, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + ) -> PaginatedList[PullRequestComment]: + """ + Warning: this only returns review comments. For normal conversation comments, use get_issue_comments. + + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/comments `_ + :param sort: string 'created' or 'updated' + :param direction: string 'asc' or 'desc' + :param since: datetime + """ + return self.get_review_comments(sort=sort, direction=direction, since=since) + + # v3: remove *, added here to force named parameters because order has changed + def get_review_comments( + self, + *, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + ) -> PaginatedList[PullRequestComment]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/comments `_ + :param sort: string 'created' or 'updated' + :param direction: string 'asc' or 'desc' + :param since: datetime + """ + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + assert is_optional(since, datetime), since + + url_parameters = NotSet.remove_unset_items({"sort": sort, "direction": direction}) + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + + return PaginatedList( + github.PullRequestComment.PullRequestComment, + self._requester, + f"{self.url}/comments", + url_parameters, + ) + + def get_single_review_comments(self, id: int) -> PaginatedList[PullRequestComment]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/review/{id}/comments `_ + """ + assert isinstance(id, int), id + return PaginatedList( + github.PullRequestComment.PullRequestComment, + self._requester, + f"{self.url}/reviews/{id}/comments", + None, + ) + + def get_commits(self) -> PaginatedList[Commit]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/commits `_ + """ + return PaginatedList(github.Commit.Commit, self._requester, f"{self.url}/commits", None) + + def get_files(self) -> PaginatedList[File]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/files `_ + """ + return PaginatedList(github.File.File, self._requester, f"{self.url}/files", None) + + def get_issue_comment(self, id: int) -> IssueComment: + """ + :calls: `GET /repos/{owner}/{repo}/issues/comments/{id} `_ + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self._parentUrl(self.issue_url)}/comments/{id}") + return github.IssueComment.IssueComment(self._requester, headers, data, completed=True) + + def get_issue_comments(self) -> PaginatedList[IssueComment]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number}/comments `_ + """ + return PaginatedList( + github.IssueComment.IssueComment, + self._requester, + f"{self.issue_url}/comments", + None, + ) + + def get_issue_events(self) -> PaginatedList[IssueEvent]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{issue_number}/events `_ + :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueEvent.IssueEvent` + """ + return PaginatedList( + github.IssueEvent.IssueEvent, + self._requester, + f"{self.issue_url}/events", + None, + headers={"Accept": Consts.mediaTypeLockReasonPreview}, + ) + + def get_review(self, id: int) -> PullRequestReview: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/reviews/{id} `_ + :param id: integer + :rtype: :class:`github.PullRequestReview.PullRequestReview` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/reviews/{id}", + ) + return github.PullRequestReview.PullRequestReview(self._requester, headers, data) + + def get_reviews(self) -> PaginatedList[PullRequestReview]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/reviews `_ + :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequestReview.PullRequestReview` + """ + return PaginatedList( + github.PullRequestReview.PullRequestReview, + self._requester, + f"{self.url}/reviews", + None, + ) + + def get_review_requests(self) -> tuple[PaginatedList[NamedUser], PaginatedList[Team]]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/requested_reviewers `_ + :rtype: tuple of :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` and of :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team` + """ + return ( + PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/requested_reviewers", + None, + list_item="users", + ), + PaginatedList( + github.Team.Team, + self._requester, + f"{self.url}/requested_reviewers", + None, + list_item="teams", + ), + ) + + def get_labels(self) -> PaginatedList[Label]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + return PaginatedList(github.Label.Label, self._requester, f"{self.issue_url}/labels", None) + + def add_to_labels(self, *labels: github.Label.Label | str) -> None: + """ + :calls: `POST /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels + post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels] + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.issue_url}/labels", input=post_parameters) + + def delete_labels(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.issue_url}/labels") + + def remove_from_labels(self, label: github.Label.Label | str) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name} `_ + """ + assert isinstance(label, (github.Label.Label, str)), label + if isinstance(label, github.Label.Label): + label = label._identity + else: + label = urllib.parse.quote(label) + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.issue_url}/labels/{label}") + + def set_labels(self, *labels: github.Label.Label | str) -> None: + """ + :calls: `PUT /repos/{owner}/{repo}/issues/{number}/labels `_ + """ + assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels + post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels] + headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.issue_url}/labels", input=post_parameters) + + def is_merged(self) -> bool: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number}/merge `_ + """ + status, headers, data = self._requester.requestJson("GET", f"{self.url}/merge") + return status == 204 + + def restore_branch(self) -> GitRef: + """ + Convenience function that calls :meth:`Repository.create_git_ref` :rtype: :class:`github.GitRef.GitRef` + """ + return self.head.repo.create_git_ref(f"refs/heads/{self.head.ref}", sha=self.head.sha) + + def delete_branch(self, force: bool = False) -> None: + """ + Convenience function that calls :meth:`GitRef.delete` :rtype: bool. + """ + if not force: + remaining_pulls = self.head.repo.get_pulls(head=f"{self.head.repo.owner.login}:{self.head.ref}") + if remaining_pulls.totalCount > 0: + raise RuntimeError( + "This branch is referenced by open pull requests, set force=True to delete this branch." + ) + return self.head.repo.get_git_ref(f"heads/{self.head.ref}").delete() + + def enable_automerge( + self, + merge_method: Opt[str] = "MERGE", + author_email: Opt[str] = NotSet, + client_mutation_id: Opt[str] = NotSet, + commit_body: Opt[str] = NotSet, + commit_headline: Opt[str] = NotSet, + expected_head_oid: Opt[str] = NotSet, + ) -> dict[str, Any]: + """ + :calls: `POST /graphql `_ with a mutation to enable pull request auto merge + + """ + assert is_optional(author_email, str), author_email + assert is_optional(client_mutation_id, str), client_mutation_id + assert is_optional(commit_body, str), commit_body + assert is_optional(commit_headline, str), commit_headline + assert is_optional(expected_head_oid, str), expected_head_oid + assert isinstance(merge_method, str) and merge_method in ["MERGE", "REBASE", "SQUASH"], merge_method + + # Define the variables + variables = { + "pullRequestId": self.node_id, + "authorEmail": author_email, + "clientMutationId": client_mutation_id, + "commitBody": commit_body, + "commitHeadline": commit_headline, + "expectedHeadOid": expected_head_oid, + "mergeMethod": merge_method, + } + + # Make the request + _, data = self._requester.graphql_named_mutation( + mutation_name="enablePullRequestAutoMerge", + mutation_input=NotSet.remove_unset_items(variables), + output_schema="actor { avatarUrl login resourcePath url } clientMutationId", + ) + return data + + def disable_automerge( + self, + client_mutation_id: Opt[str] = NotSet, + ) -> dict[str, Any]: + """ + :calls: `POST /graphql `_ with a mutation to disable pull request auto merge + + """ + assert is_optional(client_mutation_id, str), client_mutation_id + + # Define the variables + variables = { + "pullRequestId": self.node_id, + "clientMutationId": client_mutation_id, + } + + # Make the request + _, data = self._requester.graphql_named_mutation( + mutation_name="disablePullRequestAutoMerge", + mutation_input=NotSet.remove_unset_items(variables), + output_schema="actor { avatarUrl login resourcePath url } clientMutationId", + ) + return data + + def merge( + self, + commit_message: Opt[str] = NotSet, + commit_title: Opt[str] = NotSet, + merge_method: Opt[str] = NotSet, + sha: Opt[str] = NotSet, + delete_branch: bool = False, + ) -> PullRequestMergeStatus: + """ + :calls: `PUT /repos/{owner}/{repo}/pulls/{number}/merge `_ + """ + assert is_optional(commit_message, str), commit_message + assert is_optional(commit_title, str), commit_title + assert is_optional(merge_method, str), merge_method + assert is_optional(sha, str), sha + post_parameters = NotSet.remove_unset_items( + {"commit_message": commit_message, "commit_title": commit_title, "merge_method": merge_method, "sha": sha} + ) + headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/merge", input=post_parameters) + if delete_branch: + self.delete_branch() + + return github.PullRequestMergeStatus.PullRequestMergeStatus(self._requester, headers, data) + + def add_to_assignees(self, *assignees: github.NamedUser.NamedUser | str) -> None: + """ + :calls: `POST /repos/{owner}/{repo}/issues/{number}/assignees `_ + """ + assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees + post_parameters = { + "assignees": [ + assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee + for assignee in assignees + ] + } + headers, data = self._requester.requestJsonAndCheck( + "POST", f"{self.issue_url}/assignees", input=post_parameters + ) + # Only use the assignees attribute, since we call this PR as an issue + self._useAttributes({"assignees": data["assignees"]}) + + def remove_from_assignees(self, *assignees: github.NamedUser.NamedUser | str) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/issues/{number}/assignees `_ + """ + assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees + post_parameters = { + "assignees": [ + assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee + for assignee in assignees + ] + } + headers, data = self._requester.requestJsonAndCheck( + "DELETE", f"{self.issue_url}/assignees", input=post_parameters + ) + # Only use the assignees attribute, since we call this PR as an issue + self._useAttributes({"assignees": data["assignees"]}) + + def update_branch(self, expected_head_sha: Opt[str] = NotSet) -> bool: + """ + :calls `PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch `_ + """ + assert is_optional(expected_head_sha, str), expected_head_sha + post_parameters = NotSet.remove_unset_items({"expected_head_sha": expected_head_sha}) + status, headers, data = self._requester.requestJson( + "PUT", + f"{self.url}/update-branch", + input=post_parameters, + headers={"Accept": Consts.updateBranchPreview}, + ) + return status == 202 + + def convert_to_draft( + self, + client_mutation_id: Opt[str] = NotSet, + ) -> dict[str, Any]: + """ + :calls: `POST /graphql `_ to convert pull request to draft + + """ + assert is_optional(client_mutation_id, str), client_mutation_id + + # Define the variables + variables = { + "pullRequestId": self.node_id, + "clientMutationId": client_mutation_id, + } + + # Make the request + _, data = self._requester.graphql_named_mutation( + mutation_name="convertPullRequestToDraft", + mutation_input=NotSet.remove_unset_items(variables), + output_schema="clientMutationId pullRequest { isDraft }", + ) + self._useAttributes({"draft": data["pullRequest"]["isDraft"]}) + return data + + def mark_ready_for_review( + self, + client_mutation_id: Opt[str] = NotSet, + ) -> dict[str, Any]: + """ + :calls: `POST /graphql `_ to mark pull request ready for review + + """ + assert is_optional(client_mutation_id, str), client_mutation_id + + # Define the variables + variables = { + "pullRequestId": self.node_id, + "clientMutationId": client_mutation_id, + } + + # Make the request + _, data = self._requester.graphql_named_mutation( + mutation_name="markPullRequestReadyForReview", + mutation_input=NotSet.remove_unset_items(variables), + output_schema="clientMutationId pullRequest { isDraft }", + ) + self._useAttributes({"draft": data["pullRequest"]["isDraft"]}) + return data + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "_links" in attributes: # pragma no branch + self.__links = self._makeDictAttribute(attributes["_links"]) + if "active_lock_reason" in attributes: # pragma no branch + self._active_lock_reason = self._makeStringAttribute(attributes["active_lock_reason"]) + if "additions" in attributes: # pragma no branch + self._additions = self._makeIntAttribute(attributes["additions"]) + if "assignee" in attributes: # pragma no branch + self._assignee = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["assignee"]) + if "assignees" in attributes: # pragma no branch + self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, attributes["assignees"]) + elif "assignee" in attributes: + if attributes["assignee"] is not None: + self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, [attributes["assignee"]]) + else: + self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, []) + if "author_association" in attributes: # pragma no branch + self._author_association = self._makeStringAttribute(attributes["author_association"]) + if "auto_merge" in attributes: # pragma no branch + self._auto_merge = self._makeDictAttribute(attributes["auto_merge"]) + if "base" in attributes: # pragma no branch + self._base = self._makeClassAttribute(github.PullRequestPart.PullRequestPart, attributes["base"]) + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "changed_files" in attributes: # pragma no branch + self._changed_files = self._makeIntAttribute(attributes["changed_files"]) + if "closed_at" in attributes: # pragma no branch + self._closed_at = self._makeDatetimeAttribute(attributes["closed_at"]) + if "comments" in attributes: # pragma no branch + self._comments = self._makeIntAttribute(attributes["comments"]) + if "comments_url" in attributes: # pragma no branch + self._comments_url = self._makeStringAttribute(attributes["comments_url"]) + if "commits" in attributes: # pragma no branch + self._commits = self._makeIntAttribute(attributes["commits"]) + if "commits_url" in attributes: # pragma no branch + self._commits_url = self._makeStringAttribute(attributes["commits_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "deletions" in attributes: # pragma no branch + self._deletions = self._makeIntAttribute(attributes["deletions"]) + if "diff_url" in attributes: # pragma no branch + self._diff_url = self._makeStringAttribute(attributes["diff_url"]) + if "draft" in attributes: # pragma no branch + self._draft = self._makeBoolAttribute(attributes["draft"]) + if "head" in attributes: # pragma no branch + self._head = self._makeClassAttribute(github.PullRequestPart.PullRequestPart, attributes["head"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "issue_url" in attributes: # pragma no branch + self._issue_url = self._makeStringAttribute(attributes["issue_url"]) + if "labels" in attributes: # pragma no branch + self._labels = self._makeListOfClassesAttribute(github.Label.Label, attributes["labels"]) + if "locked" in attributes: # pragma no branch + self._locked = self._makeBoolAttribute(attributes["locked"]) + if "maintainer_can_modify" in attributes: # pragma no branch + self._maintainer_can_modify = self._makeBoolAttribute(attributes["maintainer_can_modify"]) + if "merge_commit_sha" in attributes: # pragma no branch + self._merge_commit_sha = self._makeStringAttribute(attributes["merge_commit_sha"]) + if "mergeable" in attributes: # pragma no branch + self._mergeable = self._makeBoolAttribute(attributes["mergeable"]) + if "mergeable_state" in attributes: # pragma no branch + self._mergeable_state = self._makeStringAttribute(attributes["mergeable_state"]) + if "merged" in attributes: # pragma no branch + self._merged = self._makeBoolAttribute(attributes["merged"]) + if "merged_at" in attributes: # pragma no branch + self._merged_at = self._makeDatetimeAttribute(attributes["merged_at"]) + if "merged_by" in attributes: # pragma no branch + self._merged_by = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["merged_by"]) + if "milestone" in attributes: # pragma no branch + self._milestone = self._makeClassAttribute(github.Milestone.Milestone, attributes["milestone"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "number" in attributes: # pragma no branch + self._number = self._makeIntAttribute(attributes["number"]) + if "patch_url" in attributes: # pragma no branch + self._patch_url = self._makeStringAttribute(attributes["patch_url"]) + if "rebaseable" in attributes: # pragma no branch + self._rebaseable = self._makeBoolAttribute(attributes["rebaseable"]) + if "requested_reviewers" in attributes: + self._requested_reviewers = self._makeListOfClassesAttribute( + github.NamedUser.NamedUser, attributes["requested_reviewers"] + ) + if "requested_teams" in attributes: + self._requested_teams = self._makeListOfClassesAttribute(github.Team.Team, attributes["requested_teams"]) + if "review_comment_url" in attributes: # pragma no branch + self._review_comment_url = self._makeStringAttribute(attributes["review_comment_url"]) + if "review_comments" in attributes: # pragma no branch + self._review_comments = self._makeIntAttribute(attributes["review_comments"]) + if "review_comments_url" in attributes: # pragma no branch + self._review_comments_url = self._makeStringAttribute(attributes["review_comments_url"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "statuses_url" in attributes: # pragma no branch + self._statuses_url = self._makeStringAttribute(attributes["statuses_url"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/PullRequestComment.py b/python_embeded/Lib/site-packages/github/PullRequestComment.py new file mode 100644 index 0000000000000000000000000000000000000000..4b90ec74311b89dcfdbd53d92c9810f65385f2e9 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/PullRequestComment.py @@ -0,0 +1,379 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Michael Stead # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Nicolas Agustín Torres # +# Copyright 2018 Jess Morgan <979404+JessMorgan@users.noreply.github.com> # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 per1234 # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Huan-Cheng Chang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Den Stroebel # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.NamedUser +import github.Reaction +from github import Consts +from github.GithubObject import Attribute, CompletableGithubObject, NotSet +from github.PaginatedList import PaginatedList + + +class PullRequestComment(CompletableGithubObject): + """ + This class represents PullRequestComments. + + The reference can be found here + https://docs.github.com/en/rest/reference/pulls#review-comments + + The OpenAPI schema can be found at + - /components/schemas/pull-request-review-comment + + """ + + def _initAttributes(self) -> None: + self.__links: Attribute[dict[str, Any]] = NotSet + self._author_association: Attribute[str] = NotSet + self._body: Attribute[str] = NotSet + self._body_html: Attribute[str] = NotSet + self._body_text: Attribute[str] = NotSet + self._commit_id: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._diff_hunk: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._in_reply_to_id: Attribute[int] = NotSet + self._line: Attribute[int] = NotSet + self._node_id: Attribute[str] = NotSet + self._original_commit_id: Attribute[str] = NotSet + self._original_line: Attribute[int] = NotSet + self._original_position: Attribute[int] = NotSet + self._original_start_line: Attribute[int] = NotSet + self._path: Attribute[str] = NotSet + self._position: Attribute[int] = NotSet + self._pull_request_review_id: Attribute[int] = NotSet + self._pull_request_url: Attribute[str] = NotSet + self._reactions: Attribute[dict[str, Any]] = NotSet + self._side: Attribute[str] = NotSet + self._start_line: Attribute[int] = NotSet + self._start_side: Attribute[str] = NotSet + self._subject_type: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._user: Attribute[github.NamedUser.NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "user": self._user.value}) + + @property + def _links(self) -> dict[str, Any]: + self._completeIfNotSet(self.__links) + return self.__links.value + + @property + def author_association(self) -> str: + self._completeIfNotSet(self._author_association) + return self._author_association.value + + @property + def body(self) -> str: + self._completeIfNotSet(self._body) + return self._body.value + + @property + def body_html(self) -> str: + self._completeIfNotSet(self._body_html) + return self._body_html.value + + @property + def body_text(self) -> str: + self._completeIfNotSet(self._body_text) + return self._body_text.value + + @property + def commit_id(self) -> str: + self._completeIfNotSet(self._commit_id) + return self._commit_id.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def diff_hunk(self) -> str: + self._completeIfNotSet(self._diff_hunk) + return self._diff_hunk.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def in_reply_to_id(self) -> int: + self._completeIfNotSet(self._in_reply_to_id) + return self._in_reply_to_id.value + + @property + def line(self) -> int: + self._completeIfNotSet(self._line) + return self._line.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def original_commit_id(self) -> str: + self._completeIfNotSet(self._original_commit_id) + return self._original_commit_id.value + + @property + def original_line(self) -> int: + self._completeIfNotSet(self._original_line) + return self._original_line.value + + @property + def original_position(self) -> int: + self._completeIfNotSet(self._original_position) + return self._original_position.value + + @property + def original_start_line(self) -> int: + self._completeIfNotSet(self._original_start_line) + return self._original_start_line.value + + @property + def path(self) -> str: + self._completeIfNotSet(self._path) + return self._path.value + + @property + def position(self) -> int: + self._completeIfNotSet(self._position) + return self._position.value + + @property + def pull_request_review_id(self) -> int: + self._completeIfNotSet(self._pull_request_review_id) + return self._pull_request_review_id.value + + @property + def pull_request_url(self) -> str: + self._completeIfNotSet(self._pull_request_url) + return self._pull_request_url.value + + @property + def reactions(self) -> dict[str, Any]: + self._completeIfNotSet(self._reactions) + return self._reactions.value + + @property + def side(self) -> str: + self._completeIfNotSet(self._side) + return self._side.value + + @property + def start_line(self) -> int: + self._completeIfNotSet(self._start_line) + return self._start_line.value + + @property + def start_side(self) -> str: + self._completeIfNotSet(self._start_side) + return self._start_side.value + + @property + def subject_type(self) -> str: + self._completeIfNotSet(self._subject_type) + return self._subject_type.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def user(self) -> github.NamedUser.NamedUser: + self._completeIfNotSet(self._user) + return self._user.value + + def delete(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/pulls/comments/{number} `_ + :rtype: None + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def edit(self, body: str) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/pulls/comments/{number} `_ + :param body: string + :rtype: None + """ + assert isinstance(body, str), body + post_parameters = { + "body": body, + } + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def get_reactions(self) -> PaginatedList[github.Reaction.Reaction]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/comments/{number}/reactions + `_ + :return: :class: :class:`github.PaginatedList.PaginatedList` of :class:`github.Reaction.Reaction` + """ + return PaginatedList( + github.Reaction.Reaction, + self._requester, + f"{self.url}/reactions", + None, + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + + def create_reaction(self, reaction_type: str) -> github.Reaction.Reaction: + """ + :calls: `POST /repos/{owner}/{repo}/pulls/comments/{number}/reactions + `_ + :param reaction_type: string + :rtype: :class:`github.Reaction.Reaction` + """ + assert isinstance(reaction_type, str), reaction_type + post_parameters = { + "content": reaction_type, + } + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/reactions", + input=post_parameters, + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + return github.Reaction.Reaction(self._requester, headers, data, completed=True) + + def delete_reaction(self, reaction_id: int) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id} + `_ + :param reaction_id: integer + :rtype: bool + """ + assert isinstance(reaction_id, int), reaction_id + status, _, _ = self._requester.requestJson( + "DELETE", + f"{self.url}/reactions/{reaction_id}", + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + return status == 204 + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "_links" in attributes: # pragma no branch + self.__links = self._makeDictAttribute(attributes["_links"]) + if "author_association" in attributes: # pragma no branch + self._author_association = self._makeStringAttribute(attributes["author_association"]) + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "body_html" in attributes: # pragma no branch + self._body_html = self._makeStringAttribute(attributes["body_html"]) + if "body_text" in attributes: # pragma no branch + self._body_text = self._makeStringAttribute(attributes["body_text"]) + if "commit_id" in attributes: # pragma no branch + self._commit_id = self._makeStringAttribute(attributes["commit_id"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "diff_hunk" in attributes: # pragma no branch + self._diff_hunk = self._makeStringAttribute(attributes["diff_hunk"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "in_reply_to_id" in attributes: # pragma no branch + self._in_reply_to_id = self._makeIntAttribute(attributes["in_reply_to_id"]) + if "line" in attributes: # pragma no branch + self._line = self._makeIntAttribute(attributes["line"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "original_commit_id" in attributes: # pragma no branch + self._original_commit_id = self._makeStringAttribute(attributes["original_commit_id"]) + if "original_line" in attributes: # pragma no branch + self._original_line = self._makeIntAttribute(attributes["original_line"]) + if "original_position" in attributes: # pragma no branch + self._original_position = self._makeIntAttribute(attributes["original_position"]) + if "original_start_line" in attributes: # pragma no branch + self._original_start_line = self._makeIntAttribute(attributes["original_start_line"]) + if "path" in attributes: # pragma no branch + self._path = self._makeStringAttribute(attributes["path"]) + if "position" in attributes: # pragma no branch + self._position = self._makeIntAttribute(attributes["position"]) + if "pull_request_review_id" in attributes: # pragma no branch + self._pull_request_review_id = self._makeIntAttribute(attributes["pull_request_review_id"]) + if "pull_request_url" in attributes: # pragma no branch + self._pull_request_url = self._makeStringAttribute(attributes["pull_request_url"]) + if "reactions" in attributes: # pragma no branch + self._reactions = self._makeDictAttribute(attributes["reactions"]) + if "side" in attributes: # pragma no branch + self._side = self._makeStringAttribute(attributes["side"]) + if "start_line" in attributes: # pragma no branch + self._start_line = self._makeIntAttribute(attributes["start_line"]) + if "start_side" in attributes: # pragma no branch + self._start_side = self._makeStringAttribute(attributes["start_side"]) + if "subject_type" in attributes: # pragma no branch + self._subject_type = self._makeStringAttribute(attributes["subject_type"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/PullRequestMergeStatus.py b/python_embeded/Lib/site-packages/github/PullRequestMergeStatus.py new file mode 100644 index 0000000000000000000000000000000000000000..986985d31df5f3ed50db7ee2faa7275d7f471008 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/PullRequestMergeStatus.py @@ -0,0 +1,81 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class PullRequestMergeStatus(NonCompletableGithubObject): + """ + This class represents PullRequestMergeStatuses. + + The reference can be found here + https://docs.github.com/en/rest/reference/pulls#check-if-a-pull-request-has-been-merged + + """ + + def _initAttributes(self) -> None: + self._merged: Attribute[bool] = NotSet + self._message: Attribute[str] = NotSet + self._sha: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"sha": self._sha.value, "merged": self._merged.value}) + + @property + def merged(self) -> bool: + return self._merged.value + + @property + def message(self) -> str: + return self._message.value + + @property + def sha(self) -> str: + return self._sha.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "merged" in attributes: # pragma no branch + self._merged = self._makeBoolAttribute(attributes["merged"]) + if "message" in attributes: # pragma no branch + self._message = self._makeStringAttribute(attributes["message"]) + if "sha" in attributes: # pragma no branch + self._sha = self._makeStringAttribute(attributes["sha"]) diff --git a/python_embeded/Lib/site-packages/github/PullRequestPart.py b/python_embeded/Lib/site-packages/github/PullRequestPart.py new file mode 100644 index 0000000000000000000000000000000000000000..7cc64bbf181a5706980757c73240a79a242ce0b0 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/PullRequestPart.py @@ -0,0 +1,107 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.NamedUser +import github.Repository +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + from github.Repository import Repository + + +class PullRequestPart(NonCompletableGithubObject): + """ + This class represents PullRequestParts. + + The OpenAPI schema can be found at + - /components/schemas/pull-request-minimal/properties/base + - /components/schemas/pull-request-minimal/properties/head + - /components/schemas/pull-request-simple/properties/base + - /components/schemas/pull-request-simple/properties/head + - /components/schemas/pull-request/properties/base + - /components/schemas/pull-request/properties/head + + """ + + def _initAttributes(self) -> None: + self._label: Attribute[str] = NotSet + self._ref: Attribute[str] = NotSet + self._repo: Attribute[Repository] = NotSet + self._sha: Attribute[str] = NotSet + self._user: Attribute[NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"sha": self._sha.value}) + + @property + def label(self) -> str: + return self._label.value + + @property + def ref(self) -> str: + return self._ref.value + + @property + def repo(self) -> Repository: + return self._repo.value + + @property + def sha(self) -> str: + return self._sha.value + + @property + def user(self) -> NamedUser: + return self._user.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "label" in attributes: # pragma no branch + self._label = self._makeStringAttribute(attributes["label"]) + if "ref" in attributes: # pragma no branch + self._ref = self._makeStringAttribute(attributes["ref"]) + if "repo" in attributes: # pragma no branch + self._repo = self._makeClassAttribute(github.Repository.Repository, attributes["repo"]) + if "sha" in attributes: # pragma no branch + self._sha = self._makeStringAttribute(attributes["sha"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/PullRequestReview.py b/python_embeded/Lib/site-packages/github/PullRequestReview.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf5e56650023ccd7b24156693494cfd2d294d61 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/PullRequestReview.py @@ -0,0 +1,160 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Aaron Levine # +# Copyright 2017 Mike Miller # +# Copyright 2018 Darragh Bailey # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Claire Johns <42869556+johnsc1@users.noreply.github.com> # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Gael Colas # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.NamedUser +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class PullRequestReview(NonCompletableGithubObject): + """ + This class represents PullRequestReviews. + + The reference can be found here + https://docs.github.com/en/rest/reference/pulls#reviews + + """ + + def _initAttributes(self) -> None: + self._body: Attribute[str] = NotSet + self._commit_id: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._pull_request_url: Attribute[str] = NotSet + self._state: Attribute[str] = NotSet + self._submitted_at: Attribute[datetime] = NotSet + self._user: Attribute[github.NamedUser.NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "user": self._user.value}) + + @property + def body(self) -> str: + return self._body.value + + @property + def commit_id(self) -> str: + return self._commit_id.value + + @property + def html_url(self) -> str: + return self._html_url.value + + @property + def id(self) -> int: + return self._id.value + + @property + def pull_request_url(self) -> str: + return self._pull_request_url.value + + @property + def state(self) -> str: + return self._state.value + + @property + def submitted_at(self) -> datetime: + return self._submitted_at.value + + @property + def user(self) -> github.NamedUser.NamedUser: + return self._user.value + + def dismiss(self, message: str) -> None: + """ + :calls: `PUT /repos/{owner}/{repo}/pulls/{number}/reviews/{review_id}/dismissals `_ + """ + post_parameters = {"message": message} + headers, data = self._requester.requestJsonAndCheck( + "PUT", + f"{self.pull_request_url}/reviews/{self.id}/dismissals", + input=post_parameters, + ) + self._useAttributes(data) + + def delete(self) -> None: + """ + :calls: `DELETE /repos/:owner/:repo/pulls/:number/reviews/:review_id `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.pull_request_url}/reviews/{self.id}") + + def edit(self, body: str) -> None: + """ + :calls: `PUT /repos/{owner}/{repo}/pulls/{number}/reviews/{review_id} + `_ + """ + assert isinstance(body, str), body + post_parameters = { + "body": body, + } + headers, data = self._requester.requestJsonAndCheck( + "PUT", + f"{self.pull_request_url}/reviews/{self.id}", + input=post_parameters, + ) + self._useAttributes(data) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "commit_id" in attributes: # pragma no branch + self._commit_id = self._makeStringAttribute(attributes["commit_id"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "pull_request_url" in attributes: # pragma no branch + self._pull_request_url = self._makeStringAttribute(attributes["pull_request_url"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "submitted_at" in attributes: # pragma no branch + self._submitted_at = self._makeDatetimeAttribute(attributes["submitted_at"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/Rate.py b/python_embeded/Lib/site-packages/github/Rate.py new file mode 100644 index 0000000000000000000000000000000000000000..6f634350bfb734629e720ce34fbe8dcaacc232f5 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Rate.py @@ -0,0 +1,99 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Nikolay Yurin # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from datetime import datetime +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class Rate(NonCompletableGithubObject): + """ + This class represents Rates. + + The reference can be found here + https://docs.github.com/en/rest/reference/rate-limit + + The OpenAPI schema can be found at + - /components/schemas/rate-limit + + """ + + def _initAttributes(self) -> None: + self._limit: Attribute[int] = NotSet + self._remaining: Attribute[int] = NotSet + self._reset: Attribute[datetime] = NotSet + self._used: Attribute[int] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "limit": self._limit.value, + "remaining": self._remaining.value, + "reset": self._reset.value, + } + ) + + @property + def limit(self) -> int: + return self._limit.value + + @property + def remaining(self) -> int: + return self._remaining.value + + @property + def reset(self) -> datetime: + return self._reset.value + + @property + def used(self) -> int: + return self._used.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "limit" in attributes: # pragma no branch + self._limit = self._makeIntAttribute(attributes["limit"]) + if "remaining" in attributes: # pragma no branch + self._remaining = self._makeIntAttribute(attributes["remaining"]) + if "reset" in attributes: # pragma no branch + self._reset = self._makeTimestampAttribute(attributes["reset"]) + if "used" in attributes: # pragma no branch + self._used = self._makeIntAttribute(attributes["used"]) diff --git a/python_embeded/Lib/site-packages/github/RateLimit.py b/python_embeded/Lib/site-packages/github/RateLimit.py new file mode 100644 index 0000000000000000000000000000000000000000..434562c0f87c0be2ae9d7c9644c90cf13055f725 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RateLimit.py @@ -0,0 +1,166 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Bill Napier # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.Rate +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.Rate import Rate + + +class RateLimit(NonCompletableGithubObject): + """ + This class represents RateLimits. + + The reference can be found here + https://docs.github.com/en/rest/reference/rate-limit + + The OpenAPI schema can be found at + - /components/schemas/rate-limit-overview/properties/resources + + """ + + def _initAttributes(self) -> None: + self._actions_runner_registration: Attribute[Rate] = NotSet + self._code_scanning_upload: Attribute[Rate] = NotSet + self._code_search: Attribute[Rate] = NotSet + self._core: Attribute[Rate] = NotSet + self._dependency_snapshots: Attribute[Rate] = NotSet + self._graphql: Attribute[Rate] = NotSet + self._integration_manifest: Attribute[Rate] = NotSet + self._scim: Attribute[Rate] = NotSet + self._search: Attribute[Rate] = NotSet + self._source_import: Attribute[Rate] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"core": self._core.value}) + + @property + def actions_runner_registration(self) -> Rate: + """ + Rate limit for registering self-hosted runners in GitHub Actions. + """ + return self._actions_runner_registration.value + + @property + def code_scanning_upload(self) -> Rate: + """ + Rate limit for uploading SARIF results to code scanning. + """ + return self._code_scanning_upload.value + + @property + def code_search(self) -> Rate: + """ + Rate limit for the REST API for searching code. + """ + return self._code_search.value + + @property + def core(self) -> Rate: + """ + Rate limit for the non-search-related API. + """ + return self._core.value + + @property + def dependency_snapshots(self) -> Rate: + """ + Rate limit for submitting snapshots to the dependency graph. + """ + return self._dependency_snapshots.value + + @property + def graphql(self) -> Rate: + """ + (Experimental) Rate limit for GraphQL API, use with caution. + """ + return self._graphql.value + + @property + def integration_manifest(self) -> Rate: + """ + Rate limit for POST /app-manifests/{code}/conversions operation. + """ + return self._integration_manifest.value + + @property + def scim(self) -> github.Rate.Rate: + return self._scim.value + + @property + def search(self) -> Rate: + """ + Rate limit for the Search API. + """ + return self._search.value + + @property + def source_import(self) -> github.Rate.Rate: + return self._source_import.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "actions_runner_registration" in attributes: # pragma no branch + self._actions_runner_registration = self._makeClassAttribute( + github.Rate.Rate, attributes["actions_runner_registration"] + ) + if "code_scanning_upload" in attributes: # pragma no branch + self._code_scanning_upload = self._makeClassAttribute(github.Rate.Rate, attributes["code_scanning_upload"]) + if "code_search" in attributes: # pragma no branch + self._code_search = self._makeClassAttribute(github.Rate.Rate, attributes["code_search"]) + if "core" in attributes: # pragma no branch + self._core = self._makeClassAttribute(github.Rate.Rate, attributes["core"]) + if "dependency_snapshots" in attributes: # pragma no branch + self._dependency_snapshots = self._makeClassAttribute(github.Rate.Rate, attributes["dependency_snapshots"]) + if "graphql" in attributes: # pragma no branch + self._graphql = self._makeClassAttribute(github.Rate.Rate, attributes["graphql"]) + if "integration_manifest" in attributes: # pragma no branch + self._integration_manifest = self._makeClassAttribute(github.Rate.Rate, attributes["integration_manifest"]) + if "scim" in attributes: # pragma no branch + self._scim = self._makeClassAttribute(github.Rate.Rate, attributes["scim"]) + if "search" in attributes: # pragma no branch + self._search = self._makeClassAttribute(github.Rate.Rate, attributes["search"]) + if "source_import" in attributes: # pragma no branch + self._source_import = self._makeClassAttribute(github.Rate.Rate, attributes["source_import"]) diff --git a/python_embeded/Lib/site-packages/github/Reaction.py b/python_embeded/Lib/site-packages/github/Reaction.py new file mode 100644 index 0000000000000000000000000000000000000000..56e2c6c81b9c553d432c5a6b4094d48df696a367 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Reaction.py @@ -0,0 +1,113 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Nicolas Agustín Torres # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.NamedUser +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + +from . import Consts + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + + +class Reaction(CompletableGithubObject): + """ + This class represents Reactions. + + The reference can be found here + https://docs.github.com/en/rest/reference/reactions + + """ + + def _initAttributes(self) -> None: + self._content: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._id: Attribute[int] = NotSet + self._user: Attribute[NamedUser] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "user": self._user.value}) + + @property + def content(self) -> str: + self._completeIfNotSet(self._content) + return self._content.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def user(self) -> NamedUser: + self._completeIfNotSet(self._user) + return self._user.value + + def delete(self) -> None: + """ + :calls: `DELETE /reactions/{id} `_ + :rtype: None + """ + self._requester.requestJsonAndCheck( + "DELETE", + f"{self._parentUrl('')}/reactions/{self.id}", + headers={"Accept": Consts.mediaTypeReactionsPreview}, + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "content" in attributes: # pragma no branch + self._content = self._makeStringAttribute(attributes["content"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "user" in attributes: # pragma no branch + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/Referrer.py b/python_embeded/Lib/site-packages/github/Referrer.py new file mode 100644 index 0000000000000000000000000000000000000000..268c32f3bbf4fae35e4be9cd760bc7adc4712fbd --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Referrer.py @@ -0,0 +1,90 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Justin Kufro # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class Referrer(NonCompletableGithubObject): + """ + This class represents a popylar Referrer for a GitHub repository. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#traffic + + The OpenAPI schema can be found at + - /components/schemas/referrer-traffic + + """ + + def _initAttributes(self) -> None: + self._count: Attribute[int] = NotSet + self._referrer: Attribute[str] = NotSet + self._uniques: Attribute[int] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "referrer": self._referrer.value, + "count": self._count.value, + "uniques": self._uniques.value, + } + ) + + @property + def count(self) -> int: + return self._count.value + + @property + def referrer(self) -> str: + return self._referrer.value + + @property + def uniques(self) -> int: + return self._uniques.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "count" in attributes: # pragma no branch + self._count = self._makeIntAttribute(attributes["count"]) + if "referrer" in attributes: # pragma no branch + self._referrer = self._makeStringAttribute(attributes["referrer"]) + if "uniques" in attributes: # pragma no branch + self._uniques = self._makeIntAttribute(attributes["uniques"]) diff --git a/python_embeded/Lib/site-packages/github/RepoCodeSecurityConfig.py b/python_embeded/Lib/site-packages/github/RepoCodeSecurityConfig.py new file mode 100644 index 0000000000000000000000000000000000000000..29c1c7e1cb3ed6f83b371177d01cd233ff1cd4ba --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RepoCodeSecurityConfig.py @@ -0,0 +1,87 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Justin Kufro # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Bill Napier # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.CodeSecurityConfig +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + pass + + +class RepoCodeSecurityConfig(NonCompletableGithubObject): + """ + This class represents Configurations for Code Security for a Repository. + + The reference can be found here + https://docs.github.com/en/rest/code-security/configurations. + + """ + + def _initAttributes(self) -> None: + self._configuration: Attribute[github.CodeSecurityConfig.CodeSecurityConfig] = NotSet + self._status: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "configuration": self.configuration, + } + ) + + @property + def configuration(self) -> github.CodeSecurityConfig.CodeSecurityConfig: + return self._configuration.value + + @property + def status(self) -> str: + return self._status.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "configuration" in attributes: # pragma no branch + self._configuration = self._makeClassAttribute( + github.CodeSecurityConfig.CodeSecurityConfig, attributes["configuration"] + ) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) diff --git a/python_embeded/Lib/site-packages/github/Repository.py b/python_embeded/Lib/site-packages/github/Repository.py new file mode 100644 index 0000000000000000000000000000000000000000..66d0afc9c7f7e5095bd146a92abe992d2de2fcea --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Repository.py @@ -0,0 +1,4656 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Christopher Gilbert # +# Copyright 2012 Steve English # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Adrian Petrescu # +# Copyright 2013 Cameron White # +# Copyright 2013 David Farr # +# Copyright 2013 Mark Roddy # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Aaron Levine # +# Copyright 2015 Christopher Wilcox # +# Copyright 2015 Dan Vanderkam # +# Copyright 2015 Ed Holland # +# Copyright 2015 Enix Yu # +# Copyright 2015 Jay # +# Copyright 2015 Jonathan Debonis # +# Copyright 2015 Kevin Lewandowski # +# Copyright 2015 Kyle Hornberg # +# Copyright 2016 @tmshn # +# Copyright 2016 Dustin Spicuzza # +# Copyright 2016 Enix Yu # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Per Øyvind Karlsen # +# Copyright 2016 Peter Buckley # +# Copyright 2016 Sylvus # +# Copyright 2016 fukatani # +# Copyright 2016 ghfan # +# Copyright 2017 Andreas Lutro # +# Copyright 2017 Ben Firshman # +# Copyright 2017 Chris McBride # +# Copyright 2017 Hugo # +# Copyright 2017 Jannis Gebauer # +# Copyright 2017 Jason White # +# Copyright 2017 Jimmy Zelinskie # +# Copyright 2017 Simon # +# Copyright 2018 Aaron L. Levine # +# Copyright 2018 AetherDeity # +# Copyright 2018 Alice GIRARD # +# Copyright 2018 Andrew Smith # +# Copyright 2018 Benoit Latinier # +# Copyright 2018 Brian Torres-Gil # +# Copyright 2018 Hayden Fuss # +# Copyright 2018 Ilya Konstantinov # +# Copyright 2018 Jacopo Notarstefano # +# Copyright 2018 John Hui # +# Copyright 2018 Justin Kufro # +# Copyright 2018 Mateusz Loskot # +# Copyright 2018 Michael Behrisch # +# Copyright 2018 Nicholas Buse # +# Copyright 2018 Philip May # +# Copyright 2018 Raihaan <31362124+res0nance@users.noreply.github.com> # +# Copyright 2018 Shinichi TAMURA # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Vinay Hegde # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 Will Yardley # +# Copyright 2018 Yossarian King # +# Copyright 2018 per1234 # +# Copyright 2018 sechastain # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Alex # +# Copyright 2019 Kevin LaFlamme # +# Copyright 2019 Olof-Joachim Frahm (欧雅福) # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Tim Gates # +# Copyright 2019 Wan Liuyang # +# Copyright 2019 Will Li # +# Copyright 2020 Alice GIRARD # +# Copyright 2020 Anuj Bansal # +# Copyright 2020 Chris de Graaf # +# Copyright 2020 Dhruv Manilawala # +# Copyright 2020 Dominic Davis-Foster # +# Copyright 2020 Florent Clarret # +# Copyright 2020 Glenn McDonald # +# Copyright 2020 Huw Jones # +# Copyright 2020 Mark Bromell # +# Copyright 2020 Max Wittig # +# Copyright 2020 Pascal Hofmann # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 Tim Gates # +# Copyright 2020 Victor Zeng # +# Copyright 2020 ton-katsu # +# Copyright 2021 Chris Keating # +# Copyright 2021 Floyd Hightower # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2021 Tanner <51724788+lightningboltemoji@users.noreply.github.com> # +# Copyright 2021 xmo-odoo # +# Copyright 2022 Aleksei Fedotov # +# Copyright 2022 Eric Nieuwland # +# Copyright 2022 Ibrahim Hussaini # +# Copyright 2022 KimSia Sim <245021+simkimsia@users.noreply.github.com> # +# Copyright 2022 Marco Köpcke # +# Copyright 2023 Andrew Collington # +# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> # +# Copyright 2023 Armen Martirosyan # +# Copyright 2023 BradChengIRESS <49461141+BradChengIRESS@users.noreply.github.com># +# Copyright 2023 Enrico Minack # +# Copyright 2023 Felipe Peter # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> # +# Copyright 2023 Jonathan Leitschuh # +# Copyright 2023 Joseph Henrich # +# Copyright 2023 Kevin Grandjean # +# Copyright 2023 Mark Amery # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2023 Max Mehl <6170081+mxmehl@users.noreply.github.com> # +# Copyright 2023 Micael <10292135+notmicaelfilipe@users.noreply.github.com> # +# Copyright 2023 Mikhail f. Shiryaev # +# Copyright 2023 Oskar Jansson <56458534+janssonoskar@users.noreply.github.com># +# Copyright 2023 Philipp A # +# Copyright 2023 Roberto Pastor Muela <37798125+RobPasMue@users.noreply.github.com># +# Copyright 2023 Sol Redfern <59831933+Tsuesun@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2023 Wojciech Barczyński <104033489+WojciechBarczynski@users.noreply.github.com># +# Copyright 2023 alson # +# Copyright 2023 chantra # +# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> # +# Copyright 2024 Caleb McCombs # +# Copyright 2024 Chris Wells # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Heitor Polidoro # +# Copyright 2024 Heitor de Bittencourt # +# Copyright 2024 Jacky Lam # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Sebastien NICOT # +# Copyright 2024 Sebastián Ramírez # +# Copyright 2024 Thomas Cooper # +# Copyright 2024 Thomas Crowley <15927917+thomascrowley@users.noreply.github.com># +# Copyright 2024 jodelasur <34933233+jodelasur@users.noreply.github.com> # +# Copyright 2025 Bill Napier # +# Copyright 2025 Enrico Minack # +# Copyright 2025 Mikhail f. Shiryaev # +# Copyright 2025 Tan An Nie <121005973+tanannie22@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import collections +import urllib.parse +from base64 import b64encode +from collections.abc import Iterable +from datetime import date, datetime, timezone +from typing import TYPE_CHECKING, Any + +from deprecated import deprecated + +import github.AdvisoryCredit +import github.AdvisoryVulnerability +import github.Artifact +import github.AuthenticatedUser +import github.Autolink +import github.Branch +import github.CheckRun +import github.CheckSuite +import github.Clones +import github.CodeScanAlert +import github.Commit +import github.CommitComment +import github.Comparison +import github.ContentFile +import github.DependabotAlert +import github.Deployment +import github.Download +import github.Environment +import github.EnvironmentDeploymentBranchPolicy +import github.EnvironmentProtectionRule +import github.EnvironmentProtectionRuleReviewer +import github.Event +import github.GitBlob +import github.GitCommit +import github.GithubObject +import github.GitRef +import github.GitRelease +import github.GitReleaseAsset +import github.GitTag +import github.GitTree +import github.Hook +import github.HookDelivery +import github.Invitation +import github.Issue +import github.IssueComment +import github.IssueEvent +import github.Label +import github.License +import github.MergedUpstream +import github.Milestone +import github.NamedUser +import github.Notification +import github.Organization +import github.PaginatedList +import github.Path +import github.Permissions +import github.Project +import github.PublicKey +import github.PullRequest +import github.PullRequestComment +import github.Referrer +import github.RepoCodeSecurityConfig +import github.RepositoryAdvisory +import github.RepositoryDiscussion +import github.RepositoryKey +import github.RepositoryPreferences +import github.Secret +import github.SecurityAndAnalysis +import github.SelfHostedActionsRunner +import github.SourceImport +import github.Stargazer +import github.StatsCodeFrequency +import github.StatsCommitActivity +import github.StatsContributor +import github.StatsParticipation +import github.StatsPunchCard +import github.Tag +import github.Team +import github.Variable +import github.View +import github.Workflow +import github.WorkflowRun +from github import Consts +from github.Environment import Environment +from github.GithubObject import ( + Attribute, + CompletableGithubObject, + NotSet, + Opt, + _NotSetType, + is_defined, + is_optional, + is_optional_list, + is_undefined, +) +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.Artifact import Artifact + from github.AuthenticatedUser import AuthenticatedUser + from github.Autolink import Autolink + from github.Branch import Branch + from github.CheckRun import CheckRun + from github.CheckSuite import CheckSuite + from github.Clones import Clones + from github.CodeScanAlert import CodeScanAlert + from github.Commit import Commit + from github.CommitComment import CommitComment + from github.Comparison import Comparison + from github.ContentFile import ContentFile + from github.DependabotAlert import DependabotAlert + from github.Deployment import Deployment + from github.Download import Download + from github.EnvironmentDeploymentBranchPolicy import ( + EnvironmentDeploymentBranchPolicyParams, + ) + from github.EnvironmentProtectionRuleReviewer import ReviewerParams + from github.Event import Event + from github.GitBlob import GitBlob + from github.GitCommit import GitCommit + from github.GitRef import GitRef + from github.GitRelease import GitRelease + from github.GitReleaseAsset import GitReleaseAsset + from github.GitTag import GitTag + from github.GitTree import GitTree + from github.Hook import Hook + from github.InputGitAuthor import InputGitAuthor + from github.InputGitTreeElement import InputGitTreeElement + from github.Invitation import Invitation + from github.Issue import Issue + from github.IssueComment import IssueComment + from github.IssueEvent import IssueEvent + from github.Label import Label + from github.License import License + from github.MergedUpstream import MergedUpstream + from github.Milestone import Milestone + from github.NamedUser import NamedUser + from github.Notification import Notification + from github.Organization import Organization + from github.Path import Path + from github.Permissions import Permissions + from github.Project import Project + from github.PublicKey import PublicKey + from github.PullRequest import PullRequest + from github.PullRequestComment import PullRequestComment + from github.Referrer import Referrer + from github.RepoCodeSecurityConfig import RepoCodeSecurityConfig + from github.RepositoryDiscussion import RepositoryDiscussion + from github.RepositoryKey import RepositoryKey + from github.RepositoryPreferences import RepositoryPreferences + from github.SecurityAndAnalysis import SecurityAndAnalysis + from github.SelfHostedActionsRunner import SelfHostedActionsRunner + from github.SourceImport import SourceImport + from github.Stargazer import Stargazer + from github.StatsCodeFrequency import StatsCodeFrequency + from github.StatsCommitActivity import StatsCommitActivity + from github.StatsContributor import StatsContributor + from github.StatsParticipation import StatsParticipation + from github.StatsPunchCard import StatsPunchCard + from github.Tag import Tag + from github.Team import Team + from github.View import View + from github.Workflow import Workflow + from github.WorkflowRun import WorkflowRun + + +class Repository(CompletableGithubObject): + """ + This class represents Repositories. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos + + The OpenAPI schema can be found at + - /components/schemas/event/properties/repo + - /components/schemas/full-repository + - /components/schemas/minimal-repository + - /components/schemas/nullable-repository + - /components/schemas/pull-request-minimal/properties/base/properties/repo + - /components/schemas/pull-request-minimal/properties/head/properties/repo + - /components/schemas/repository + - /components/schemas/simple-repository + + """ + + def _initAttributes(self) -> None: + self._allow_auto_merge: Attribute[bool] = NotSet + self._allow_forking: Attribute[bool] = NotSet + self._allow_merge_commit: Attribute[bool] = NotSet + self._allow_rebase_merge: Attribute[bool] = NotSet + self._allow_squash_merge: Attribute[bool] = NotSet + self._allow_update_branch: Attribute[bool] = NotSet + self._anonymous_access_enabled: Attribute[bool] = NotSet + self._archive_url: Attribute[str] = NotSet + self._archived: Attribute[bool] = NotSet + self._assignees_url: Attribute[str] = NotSet + self._blobs_url: Attribute[str] = NotSet + self._branches_url: Attribute[str] = NotSet + self._clone_url: Attribute[str] = NotSet + self._code_of_conduct: Attribute[dict[str, Any]] = NotSet + self._collaborators_url: Attribute[str] = NotSet + self._comments_url: Attribute[str] = NotSet + self._commits_url: Attribute[str] = NotSet + self._compare_url: Attribute[str] = NotSet + self._contents_url: Attribute[str] = NotSet + self._contributors_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._custom_properties: Attribute[dict[str, None | str | list]] = NotSet # type: ignore + self._default_branch: Attribute[str] = NotSet + self._delete_branch_on_merge: Attribute[bool] = NotSet + self._deployments_url: Attribute[str] = NotSet + self._description: Attribute[str] = NotSet + self._disabled: Attribute[bool] = NotSet + self._downloads_url: Attribute[str] = NotSet + self._events_url: Attribute[str] = NotSet + self._fork: Attribute[bool] = NotSet + self._forks: Attribute[int] = NotSet + self._forks_count: Attribute[int] = NotSet + self._forks_url: Attribute[str] = NotSet + self._full_name: Attribute[str] = NotSet + self._git_commits_url: Attribute[str] = NotSet + self._git_refs_url: Attribute[str] = NotSet + self._git_tags_url: Attribute[str] = NotSet + self._git_url: Attribute[str] = NotSet + self._has_discussions: Attribute[bool] = NotSet + self._has_downloads: Attribute[bool] = NotSet + self._has_issues: Attribute[bool] = NotSet + self._has_pages: Attribute[bool] = NotSet + self._has_projects: Attribute[bool] = NotSet + self._has_wiki: Attribute[bool] = NotSet + self._homepage: Attribute[str] = NotSet + self._hooks_url: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._is_template: Attribute[bool] = NotSet + self._issue_comment_url: Attribute[str] = NotSet + self._issue_events_url: Attribute[str] = NotSet + self._issues_url: Attribute[str] = NotSet + self._keys_url: Attribute[str] = NotSet + self._labels_url: Attribute[str] = NotSet + self._language: Attribute[str] = NotSet + self._languages_url: Attribute[str] = NotSet + self._license: Attribute[License] = NotSet + self._master_branch: Attribute[str] = NotSet + self._merge_commit_message: Attribute[str] = NotSet + self._merge_commit_title: Attribute[str] = NotSet + self._merges_url: Attribute[str] = NotSet + self._milestones_url: Attribute[str] = NotSet + self._mirror_url: Attribute[str] = NotSet + self._name: Attribute[str] = NotSet + self._network_count: Attribute[int] = NotSet + self._node_id: Attribute[str] = NotSet + self._notifications_url: Attribute[str] = NotSet + self._open_issues: Attribute[int] = NotSet + self._open_issues_count: Attribute[int] = NotSet + self._organization: Attribute[Organization] = NotSet + self._owner: Attribute[NamedUser] = NotSet + self._parent: Attribute[Repository] = NotSet + self._permissions: Attribute[Permissions] = NotSet + self._private: Attribute[bool] = NotSet + self._pulls_url: Attribute[str] = NotSet + self._pushed_at: Attribute[datetime] = NotSet + self._releases_url: Attribute[str] = NotSet + self._role_name: Attribute[str] = NotSet + self._security_and_analysis: Attribute[SecurityAndAnalysis] = NotSet + self._size: Attribute[int] = NotSet + self._source: Attribute[Repository] = NotSet + self._squash_merge_commit_message: Attribute[str] = NotSet + self._squash_merge_commit_title: Attribute[str] = NotSet + self._ssh_url: Attribute[str] = NotSet + self._stargazers_count: Attribute[int] = NotSet + self._stargazers_url: Attribute[str] = NotSet + self._starred_at: Attribute[str] = NotSet + self._statuses_url: Attribute[str] = NotSet + self._subscribers_count: Attribute[int] = NotSet + self._subscribers_url: Attribute[str] = NotSet + self._subscription_url: Attribute[str] = NotSet + self._svn_url: Attribute[str] = NotSet + self._tags_url: Attribute[str] = NotSet + self._teams_url: Attribute[str] = NotSet + self._temp_clone_token: Attribute[str] = NotSet + self._template_repository: Attribute[Repository] = NotSet + self._topics: Attribute[list[str]] = NotSet + self._trees_url: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._use_squash_pr_title_as_default: Attribute[bool] = NotSet + self._visibility: Attribute[str] = NotSet + self._watchers: Attribute[int] = NotSet + self._watchers_count: Attribute[int] = NotSet + self._web_commit_signoff_required: Attribute[bool] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"full_name": self._full_name.value}) + + @property + def _identity(self) -> str: + return f"{self.owner.login}/{self.name}" + + @property + def allow_auto_merge(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._allow_auto_merge) + return self._allow_auto_merge.value + + @property + def allow_forking(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._allow_forking) + return self._allow_forking.value + + @property + def allow_merge_commit(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._allow_merge_commit) + return self._allow_merge_commit.value + + @property + def allow_rebase_merge(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._allow_rebase_merge) + return self._allow_rebase_merge.value + + @property + def allow_squash_merge(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._allow_squash_merge) + return self._allow_squash_merge.value + + @property + def allow_update_branch(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._allow_update_branch) + return self._allow_update_branch.value + + @property + def anonymous_access_enabled(self) -> bool: + self._completeIfNotSet(self._anonymous_access_enabled) + return self._anonymous_access_enabled.value + + @property + def archive_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._archive_url) + return self._archive_url.value + + @property + def archived(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._archived) + return self._archived.value + + @property + def assignees_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._assignees_url) + return self._assignees_url.value + + @property + def blobs_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._blobs_url) + return self._blobs_url.value + + @property + def branches_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._branches_url) + return self._branches_url.value + + @property + def clone_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._clone_url) + return self._clone_url.value + + @property + def code_of_conduct(self) -> dict[str, Any]: + self._completeIfNotSet(self._code_of_conduct) + return self._code_of_conduct.value + + @property + def collaborators_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._collaborators_url) + return self._collaborators_url.value + + @property + def comments_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._comments_url) + return self._comments_url.value + + @property + def commits_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._commits_url) + return self._commits_url.value + + @property + def compare_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._compare_url) + return self._compare_url.value + + @property + def contents_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._contents_url) + return self._contents_url.value + + @property + def contributors_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._contributors_url) + return self._contributors_url.value + + @property + def created_at(self) -> datetime: + """ + :type: datetime + """ + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def custom_properties(self) -> dict[str, None | str | list]: + """ + :type: dict[str, None | str | list] + """ + self._completeIfNotSet(self._custom_properties) + return self._custom_properties.value + + @property + def default_branch(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._default_branch) + return self._default_branch.value + + @property + def delete_branch_on_merge(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._delete_branch_on_merge) + return self._delete_branch_on_merge.value + + @property + def deployments_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._deployments_url) + return self._deployments_url.value + + @property + def description(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._description) + return self._description.value + + @property + def disabled(self) -> bool: + self._completeIfNotSet(self._disabled) + return self._disabled.value + + @property + def downloads_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._downloads_url) + return self._downloads_url.value + + @property + def events_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._events_url) + return self._events_url.value + + @property + def fork(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._fork) + return self._fork.value + + @property + def forks(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._forks) + return self._forks.value + + @property + def forks_count(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._forks_count) + return self._forks_count.value + + @property + def forks_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._forks_url) + return self._forks_url.value + + @property + def full_name(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._full_name) + return self._full_name.value + + @property + def git_commits_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._git_commits_url) + return self._git_commits_url.value + + @property + def git_refs_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._git_refs_url) + return self._git_refs_url.value + + @property + def git_tags_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._git_tags_url) + return self._git_tags_url.value + + @property + def git_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._git_url) + return self._git_url.value + + @property + def has_discussions(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._has_discussions) + return self._has_discussions.value + + @property + def has_downloads(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._has_downloads) + return self._has_downloads.value + + @property + def has_issues(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._has_issues) + return self._has_issues.value + + @property + def has_pages(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._has_pages) + return self._has_pages.value + + @property + def has_projects(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._has_projects) + return self._has_projects.value + + @property + def has_wiki(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._has_wiki) + return self._has_wiki.value + + @property + def homepage(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._homepage) + return self._homepage.value + + @property + def hooks_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._hooks_url) + return self._hooks_url.value + + @property + def html_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._id) + return self._id.value + + @property + def is_template(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._is_template) + return self._is_template.value + + @property + def issue_comment_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._issue_comment_url) + return self._issue_comment_url.value + + @property + def issue_events_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._issue_events_url) + return self._issue_events_url.value + + @property + def issues_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._issues_url) + return self._issues_url.value + + @property + def keys_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._keys_url) + return self._keys_url.value + + @property + def labels_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._labels_url) + return self._labels_url.value + + @property + def language(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._language) + return self._language.value + + @property + def languages_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._languages_url) + return self._languages_url.value + + @property + def license(self) -> License: + self._completeIfNotSet(self._license) + return self._license.value + + @property + def master_branch(self) -> str: + self._completeIfNotSet(self._master_branch) + return self._master_branch.value + + @property + def merge_commit_message(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._merge_commit_message) + return self._merge_commit_message.value + + @property + def merge_commit_title(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._merge_commit_title) + return self._merge_commit_title.value + + @property + def merges_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._merges_url) + return self._merges_url.value + + @property + def milestones_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._milestones_url) + return self._milestones_url.value + + @property + def mirror_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._mirror_url) + return self._mirror_url.value + + @property + def name(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._name) + return self._name.value + + @property + def network_count(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._network_count) + return self._network_count.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def notifications_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._notifications_url) + return self._notifications_url.value + + @property + def open_issues(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._open_issues) + return self._open_issues.value + + @property + def open_issues_count(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._open_issues_count) + return self._open_issues_count.value + + @property + def organization(self) -> Organization: + """ + :type: :class:`github.Organization.Organization` + """ + self._completeIfNotSet(self._organization) + return self._organization.value + + @property + def owner(self) -> NamedUser: + """ + :type: :class:`github.NamedUser.NamedUser` + """ + self._completeIfNotSet(self._owner) + return self._owner.value + + @property + def parent(self) -> Repository: + """ + :type: :class:`github.Repository.Repository` + """ + self._completeIfNotSet(self._parent) + return self._parent.value + + @property + def permissions(self) -> Permissions: + """ + :type: :class:`github.Permissions.Permissions` + """ + self._completeIfNotSet(self._permissions) + return self._permissions.value + + @property + def private(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._private) + return self._private.value + + @property + def pulls_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._pulls_url) + return self._pulls_url.value + + @property + def pushed_at(self) -> datetime: + """ + :type: datetime + """ + self._completeIfNotSet(self._pushed_at) + return self._pushed_at.value + + @property + def releases_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._releases_url) + return self._releases_url.value + + @property + def role_name(self) -> str: + self._completeIfNotSet(self._role_name) + return self._role_name.value + + @property + def security_and_analysis(self) -> SecurityAndAnalysis: + """ + :type: :class:`github.SecurityAndAnalysis.SecurityAndAnalysis` + """ + self._completeIfNotSet(self._security_and_analysis) + return self._security_and_analysis.value + + @property + def size(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._size) + return self._size.value + + @property + def source(self) -> Repository | None: + """ + :type: :class:`github.Repository.Repository` + """ + self._completeIfNotSet(self._source) + return self._source.value + + @property + def squash_merge_commit_message(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._squash_merge_commit_message) + return self._squash_merge_commit_message.value + + @property + def squash_merge_commit_title(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._squash_merge_commit_title) + return self._squash_merge_commit_title.value + + @property + def ssh_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._ssh_url) + return self._ssh_url.value + + @property + def stargazers_count(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._stargazers_count) # pragma no cover (Should be covered) + return self._stargazers_count.value # pragma no cover (Should be covered) + + @property + def stargazers_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._stargazers_url) + return self._stargazers_url.value + + @property + def starred_at(self) -> str: + self._completeIfNotSet(self._starred_at) + return self._starred_at.value + + @property + def statuses_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._statuses_url) + return self._statuses_url.value + + @property + def subscribers_count(self) -> int: + """ + :type: integer + """ + self._completeIfNotSet(self._subscribers_count) + return self._subscribers_count.value + + @property + def subscribers_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._subscribers_url) + return self._subscribers_url.value + + @property + def subscription_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._subscription_url) + return self._subscription_url.value + + @property + def svn_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._svn_url) + return self._svn_url.value + + @property + def tags_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._tags_url) + return self._tags_url.value + + @property + def teams_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._teams_url) + return self._teams_url.value + + @property + def temp_clone_token(self) -> str: + self._completeIfNotSet(self._temp_clone_token) + return self._temp_clone_token.value + + @property + def template_repository(self) -> github.Repository.Repository: + self._completeIfNotSet(self._template_repository) + return self._template_repository.value + + @property + def topics(self) -> list[str]: + """ + :type: list of strings + """ + self._completeIfNotSet(self._topics) + return self._topics.value + + @property + def trees_url(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._trees_url) + return self._trees_url.value + + @property + def updated_at(self) -> datetime: + """ + :type: datetime + """ + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + if is_undefined(self._url) and is_defined(self._owner) and is_defined(self._name): + self._url = self._makeStringAttribute(self._requester.base_url + f"/repos/{self.owner.login}/{self.name}") + self._completeIfNotSet(self._url) + return self._url.value + + @property + def use_squash_pr_title_as_default(self) -> bool: + self._completeIfNotSet(self._use_squash_pr_title_as_default) + return self._use_squash_pr_title_as_default.value + + @property + def visibility(self) -> str: + self._completeIfNotSet(self._visibility) + return self._visibility.value + + @property + def watchers(self) -> int: + self._completeIfNotSet(self._watchers) + return self._watchers.value + + @property + def watchers_count(self) -> int: + self._completeIfNotSet(self._watchers_count) + return self._watchers_count.value + + @property + def web_commit_signoff_required(self) -> bool: + """ + :type: bool + """ + self._completeIfNotSet(self._web_commit_signoff_required) + return self._web_commit_signoff_required.value + + def add_to_collaborators(self, collaborator: str | NamedUser, permission: Opt[str] = NotSet) -> Invitation | None: + """ + :calls: `PUT /repos/{owner}/{repo}/collaborators/{user} `_ + :param collaborator: string or :class:`github.NamedUser.NamedUser` + :param permission: string 'pull', 'push', 'admin', 'maintain', 'triage', or a custom repository role name, if the owning organization has defined any + :rtype: None + """ + assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator + assert is_optional(permission, str), permission + + if isinstance(collaborator, github.NamedUser.NamedUser): + collaborator = collaborator._identity + else: + collaborator = urllib.parse.quote(collaborator) + + if is_defined(permission): + put_parameters = {"permission": permission} + else: + put_parameters = None + + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/collaborators/{collaborator}", input=put_parameters + ) + # return an invitation object if there's data returned by the API. If data is empty + # there's a pending invitation for the given user. + return ( + github.Invitation.Invitation(self._requester, headers, data, completed=True) if data is not None else None + ) + + def get_collaborator_permission(self, collaborator: str | NamedUser) -> str: + """ + :calls: `GET /repos/{owner}/{repo}/collaborators/{username}/permission `_ + :param collaborator: string or :class:`github.NamedUser.NamedUser` + :rtype: string + """ + assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator + if isinstance(collaborator, github.NamedUser.NamedUser): + collaborator = collaborator._identity + else: + collaborator = urllib.parse.quote(collaborator) + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/collaborators/{collaborator}/permission", + ) + return data["permission"] + + def get_pending_invitations(self) -> PaginatedList[Invitation]: + """ + :calls: `GET /repos/{owner}/{repo}/invitations `_ + :rtype: :class:`PaginatedList` of :class:`github.Invitation.Invitation` + """ + return PaginatedList( + github.Invitation.Invitation, + self._requester, + f"{self.url}/invitations", + None, + ) + + def remove_invitation(self, invite_id: int) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/invitations/{invitation_id} `_ + :rtype: None + """ + assert isinstance(invite_id, int), invite_id + + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/invitations/{invite_id}") + + def compare(self, base: str, head: str) -> Comparison: + """ + :calls: `GET /repos/{owner}/{repo}/compare/{base...:head} `_ + :param base: string + :param head: string + :rtype: :class:`github.Comparison.Comparison` + """ + assert isinstance(base, str), base + assert isinstance(head, str), head + base = urllib.parse.quote(base) + head = urllib.parse.quote(head) + # the compare API has a per_page default of 250, which is different to Consts.DEFAULT_PER_PAGE + per_page = self._requester.per_page if self._requester.per_page != Consts.DEFAULT_PER_PAGE else 250 + # only with page=1 we get the pagination headers for the commits element + params = {"page": 1, "per_page": per_page} + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/compare/{base}...{head}", params) + return github.Comparison.Comparison(self._requester, headers, data, completed=True) + + def create_autolink( + self, key_prefix: str, url_template: str, is_alphanumeric: Opt[bool] = NotSet + ) -> github.Autolink.Autolink: + """ + :calls: `POST /repos/{owner}/{repo}/autolinks `_ + :param key_prefix: string + :param url_template: string + :param is_alphanumeric: bool + :rtype: :class:`github.Autolink.Autolink` + """ + assert isinstance(key_prefix, str), key_prefix + assert isinstance(url_template, str), url_template + assert is_optional(is_alphanumeric, bool), is_alphanumeric + + post_parameters = NotSet.remove_unset_items( + {"key_prefix": key_prefix, "url_template": url_template, "is_alphanumeric": is_alphanumeric} + ) + + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/autolinks", input=post_parameters) + + return github.Autolink.Autolink(self._requester, headers, data) + + def create_git_blob(self, content: str, encoding: str) -> GitBlob: + """ + :calls: `POST /repos/{owner}/{repo}/git/blobs `_ + :param content: string + :param encoding: string + :rtype: :class:`github.GitBlob.GitBlob` + """ + assert isinstance(content, str), content + assert isinstance(encoding, str), encoding + post_parameters = { + "content": content, + "encoding": encoding, + } + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/blobs", input=post_parameters) + return github.GitBlob.GitBlob(self._requester, headers, data, completed=True) + + def create_git_commit( + self, + message: str, + tree: GitTree, + parents: list[GitCommit], + author: Opt[InputGitAuthor] = NotSet, + committer: Opt[InputGitAuthor] = NotSet, + ) -> GitCommit: + """ + :calls: `POST /repos/{owner}/{repo}/git/commits `_ + :param message: string + :param tree: :class:`github.GitTree.GitTree` + :param parents: list of :class:`github.GitCommit.GitCommit` + :param author: :class:`github.InputGitAuthor.InputGitAuthor` + :param committer: :class:`github.InputGitAuthor.InputGitAuthor` + :rtype: :class:`github.GitCommit.GitCommit` + """ + assert isinstance(message, str), message + assert isinstance(tree, github.GitTree.GitTree), tree + assert all(isinstance(element, github.GitCommit.GitCommit) for element in parents), parents + assert is_optional(author, github.InputGitAuthor), author + assert is_optional(committer, github.InputGitAuthor), committer + post_parameters: dict[str, Any] = { + "message": message, + "tree": tree._identity, + "parents": [element._identity for element in parents], + } + if is_defined(author): + post_parameters["author"] = author._identity + if is_defined(committer): + post_parameters["committer"] = committer._identity + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/commits", input=post_parameters) + return github.GitCommit.GitCommit(self._requester, headers, data, completed=True) + + def create_git_ref(self, ref: str, sha: str) -> GitRef: + """ + :calls: `POST /repos/{owner}/{repo}/git/refs `_ + :param ref: string + :param sha: string + :rtype: :class:`github.GitRef.GitRef` + """ + assert isinstance(ref, str), ref + assert isinstance(sha, str), sha + post_parameters = { + "ref": ref, + "sha": sha, + } + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/refs", input=post_parameters) + return github.GitRef.GitRef(self._requester, headers, data, completed=True) + + # TODO: v3: reorder arguments and add default value `NotSet` where `Opt[str]` + def create_git_tag_and_release( + self, + tag: str, + tag_message: str, + release_name: Opt[str], + release_message: Opt[str], + object: str, + type: str, + tagger: Opt[InputGitAuthor] = NotSet, + draft: bool = False, + prerelease: bool = False, + generate_release_notes: bool = False, + make_latest: str = "true", + ) -> GitRelease: + """ + Convenience function that calls :meth:`Repository.create_git_tag` and :meth:`Repository.create_git_release`. + + :param tag: string + :param tag_message: string + :param release_name: string + :param release_message: string + :param object: string + :param type: string + :param tagger: :class:github.InputGitAuthor.InputGitAuthor + :param draft: bool + :param prerelease: bool + :param generate_release_notes: bool + :param make_latest: string + :rtype: :class:`github.GitRelease.GitRelease` + + """ + self.create_git_tag(tag, tag_message, object, type, tagger) + return self.create_git_release( + tag, + release_name, + release_message, + draft, + prerelease, + generate_release_notes, + target_commitish=object, + make_latest=make_latest, + ) + + def create_git_release( + self, + tag: str, + name: Opt[str] = NotSet, + message: Opt[str] = NotSet, + draft: bool = False, + prerelease: bool = False, + generate_release_notes: bool = False, + target_commitish: Opt[str] = NotSet, + make_latest: str = "true", + ) -> GitRelease: + """ + :calls: `POST /repos/{owner}/{repo}/releases `_ + :param tag: string + :param name: string + :param message: string + :param draft: bool + :param prerelease: bool + :param generate_release_notes: bool + :param target_commitish: string or :class:`github.Branch.Branch` or :class:`github.Commit.Commit` or :class:`github.GitCommit.GitCommit` + :param make_latest: string + :rtype: :class:`github.GitRelease.GitRelease` + """ + assert isinstance(tag, str), tag + assert isinstance(generate_release_notes, bool), generate_release_notes + assert isinstance(name, str) or generate_release_notes and is_optional(name, str), name + assert isinstance(message, str) or generate_release_notes and is_optional(message, str), message + assert isinstance(draft, bool), draft + assert isinstance(prerelease, bool), prerelease + assert is_optional( + target_commitish, + (str, github.Branch.Branch, github.Commit.Commit, github.GitCommit.GitCommit), + ), target_commitish + post_parameters = { + "tag_name": tag, + "draft": draft, + "prerelease": prerelease, + "generate_release_notes": generate_release_notes, + } + assert make_latest in ["true", "false", "legacy"], make_latest + if is_defined(name): + post_parameters["name"] = name + if is_defined(message): + post_parameters["body"] = message + if isinstance(target_commitish, str): + post_parameters["target_commitish"] = target_commitish + elif isinstance(target_commitish, github.Branch.Branch): + post_parameters["target_commitish"] = target_commitish.name + elif isinstance(target_commitish, (github.Commit.Commit, github.GitCommit.GitCommit)): + post_parameters["target_commitish"] = target_commitish.sha + if is_defined(make_latest): + post_parameters["make_latest"] = make_latest + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/releases", input=post_parameters) + return github.GitRelease.GitRelease(self._requester, headers, data, completed=True) + + def create_git_tag( + self, + tag: str, + message: str, + object: str, + type: str, + tagger: Opt[InputGitAuthor] = NotSet, + ) -> GitTag: + """ + :calls: `POST /repos/{owner}/{repo}/git/tags `_ + """ + assert isinstance(tag, str), tag + assert isinstance(message, str), message + assert isinstance(object, str), object + assert isinstance(type, str), type + assert is_optional(tagger, github.InputGitAuthor), tagger + post_parameters: dict[str, Any] = { + "tag": tag, + "message": message, + "object": object, + "type": type, + } + if is_defined(tagger): + post_parameters["tagger"] = tagger._identity + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/tags", input=post_parameters) + return github.GitTag.GitTag(self._requester, headers, data, completed=True) + + def create_git_tree(self, tree: list[InputGitTreeElement], base_tree: Opt[GitTree] = NotSet) -> GitTree: + """ + :calls: `POST /repos/{owner}/{repo}/git/trees `_ + :param tree: list of :class:`github.InputGitTreeElement.InputGitTreeElement` + :param base_tree: :class:`github.GitTree.GitTree` + :rtype: :class:`github.GitTree.GitTree` + """ + assert all(isinstance(element, github.InputGitTreeElement) for element in tree), tree + assert is_optional(base_tree, github.GitTree.GitTree), base_tree + post_parameters: dict[str, Any] = { + "tree": [element._identity for element in tree], + } + if is_defined(base_tree): + post_parameters["base_tree"] = base_tree._identity + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/trees", input=post_parameters) + return github.GitTree.GitTree(self._requester, headers, data, completed=True) + + def create_hook( + self, + name: str, + config: dict[str, str], + events: Opt[list[str]] = NotSet, + active: Opt[bool] = NotSet, + ) -> Hook: + """ + :calls: `POST /repos/{owner}/{repo}/hooks `_ + :param name: string + :param config: dict + :param events: list of string + :param active: bool + :rtype: :class:`github.Hook.Hook` + """ + assert isinstance(name, str), name + assert isinstance(config, dict), config + assert is_optional_list(events, str), events + assert is_optional(active, bool), active + post_parameters = NotSet.remove_unset_items( + {"name": name, "config": config, "events": events, "active": active} + ) + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/hooks", input=post_parameters) + return github.Hook.Hook(self._requester, headers, data, completed=True) + + def create_issue( + self, + title: str, + body: Opt[str] = NotSet, + assignee: NamedUser | Opt[str] = NotSet, + milestone: Opt[Milestone] = NotSet, + labels: list[Label] | Opt[list[str]] = NotSet, + assignees: Opt[list[str]] | list[NamedUser] = NotSet, + ) -> Issue: + """ + :calls: `POST /repos/{owner}/{repo}/issues `_ + :param title: string + :param body: string + :param assignee: string or :class:`github.NamedUser.NamedUser` + :param assignees: list of string or :class:`github.NamedUser.NamedUser` + :param milestone: :class:`github.Milestone.Milestone` + :param labels: list of :class:`github.Label.Label` + :rtype: :class:`github.Issue.Issue` + """ + assert isinstance(title, str), title + assert is_optional(body, str), body + assert is_optional(assignee, (str, github.NamedUser.NamedUser)), assignee + assert is_optional_list(assignees, (github.NamedUser.NamedUser, str)), assignees + assert is_optional(milestone, github.Milestone.Milestone), milestone + assert is_optional_list(labels, (github.Label.Label, str)), labels + + post_parameters: dict[str, Any] = { + "title": title, + } + if is_defined(body): + post_parameters["body"] = body + if is_defined(assignee): + if isinstance(assignee, github.NamedUser.NamedUser): + post_parameters["assignee"] = assignee._identity + else: + post_parameters["assignee"] = assignee + if is_defined(assignees): + post_parameters["assignees"] = [ + element._identity if isinstance(element, github.NamedUser.NamedUser) else element + for element in assignees # type: ignore + ] + if is_defined(milestone): + post_parameters["milestone"] = milestone._identity + if is_defined(labels): + post_parameters["labels"] = [ + element.name if isinstance(element, github.Label.Label) else element + for element in labels # type: ignore + ] + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/issues", input=post_parameters) + return github.Issue.Issue(self._requester, headers, data, completed=True) + + def create_key(self, title: str, key: str, read_only: bool = False) -> RepositoryKey: + """ + :calls: `POST /repos/{owner}/{repo}/keys `_ + :param title: string + :param key: string + :param read_only: bool + :rtype: :class:`github.RepositoryKey.RepositoryKey` + """ + assert isinstance(title, str), title + assert isinstance(key, str), key + assert isinstance(read_only, bool), read_only + post_parameters = { + "title": title, + "key": key, + "read_only": read_only, + } + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/keys", input=post_parameters) + return github.RepositoryKey.RepositoryKey(self._requester, headers, data, completed=True) + + def create_label(self, name: str, color: str, description: Opt[str] = NotSet) -> Label: + """ + :calls: `POST /repos/{owner}/{repo}/labels `_ + :param name: string + :param color: string + :param description: string + :rtype: :class:`github.Label.Label` + """ + assert isinstance(name, str), name + assert isinstance(color, str), color + assert is_optional(description, str), description + post_parameters = { + "name": name, + "color": color, + } + if is_defined(description): + post_parameters["description"] = description + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/labels", + input=post_parameters, + headers={"Accept": Consts.mediaTypeLabelDescriptionSearchPreview}, + ) + return github.Label.Label(self._requester, headers, data, completed=True) + + def create_milestone( + self, + title: str, + state: Opt[str] = NotSet, + description: Opt[str] = NotSet, + due_on: Opt[date] = NotSet, + ) -> Milestone: + """ + :calls: `POST /repos/{owner}/{repo}/milestones `_ + :param title: string + :param state: string + :param description: string + :param due_on: datetime + :rtype: :class:`github.Milestone.Milestone` + """ + assert isinstance(title, str), title + assert is_optional(state, str), state + assert is_optional(description, str), description + assert is_optional(due_on, (datetime, date)), due_on + post_parameters = { + "title": title, + } + if is_defined(state): + post_parameters["state"] = state + if is_defined(description): + post_parameters["description"] = description + if is_defined(due_on): + if isinstance(due_on, date): + post_parameters["due_on"] = due_on.strftime("%Y-%m-%dT%H:%M:%SZ") + else: + post_parameters["due_on"] = due_on.isoformat() + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/milestones", input=post_parameters) + return github.Milestone.Milestone(self._requester, headers, data, completed=True) + + def create_project(self, name: str, body: Opt[str] = NotSet) -> Project: + """ + :calls: `POST /repos/{owner}/{repo}/projects `_ + :param name: string + :param body: string + :rtype: :class:`github.Project.Project` + """ + assert isinstance(name, str), name + assert is_optional(body, str), body + post_parameters = { + "name": name, + } + import_header = {"Accept": Consts.mediaTypeProjectsPreview} + if is_defined(body): + post_parameters["body"] = body + headers, data = self._requester.requestJsonAndCheck( + "POST", f"{self.url}/projects", headers=import_header, input=post_parameters + ) + return github.Project.Project(self._requester, headers, data, completed=True) + + def create_pull( + self, + base: str, + head: str, + *, + title: Opt[str] = NotSet, + body: Opt[str] = NotSet, + maintainer_can_modify: Opt[bool] = NotSet, + draft: Opt[bool] = NotSet, + issue: Opt[github.Issue.Issue] = NotSet, + ) -> github.PullRequest.PullRequest: + """ + :calls: `POST /repos/{owner}/{repo}/pulls `_ + """ + assert isinstance(base, str), base + assert isinstance(head, str), head + assert is_optional(title, str), title + assert is_optional(body, str), body + assert is_optional(maintainer_can_modify, bool), maintainer_can_modify + assert is_optional(draft, bool), draft + assert is_optional(issue, github.Issue.Issue), issue + + post_parameters = NotSet.remove_unset_items( + { + "base": base, + "head": head, + "title": title, + "body": body, + "maintainer_can_modify": maintainer_can_modify, + "draft": draft, + } + ) + + if is_defined(issue): + post_parameters["issue"] = issue._identity + + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/pulls", input=post_parameters) + return github.PullRequest.PullRequest(self._requester, headers, data, completed=True) + + def create_repository_advisory( + self, + summary: str, + description: str, + severity_or_cvss_vector_string: str, + cve_id: str | None = None, + vulnerabilities: Iterable[github.AdvisoryVulnerability.AdvisoryVulnerabilityInput] | None = None, + cwe_ids: Iterable[str] | None = None, + credits: Iterable[github.AdvisoryCredit.AdvisoryCredit] | None = None, + ) -> github.RepositoryAdvisory.RepositoryAdvisory: + """ + :calls: `POST /repos/{owner}/{repo}/security-advisories `_ + :param summary: string + :param description: string + :param severity_or_cvss_vector_string: string + :param cve_id: string + :param vulnerabilities: iterable of :class:`github.AdvisoryVulnerability.AdvisoryVulnerabilityInput` + :param cwe_ids: iterable of string + :param credits: iterable of :class:`github.AdvisoryCredit.AdvisoryCredit` + :rtype: :class:`github.RepositoryAdvisory.RepositoryAdvisory` + """ + return self.__create_repository_advisory( + summary=summary, + description=description, + severity_or_cvss_vector_string=severity_or_cvss_vector_string, + cve_id=cve_id, + vulnerabilities=vulnerabilities, + cwe_ids=cwe_ids, + credits=credits, + private_vulnerability_reporting=False, + ) + + def report_security_vulnerability( + self, + summary: str, + description: str, + severity_or_cvss_vector_string: str, + cve_id: str | None = None, + vulnerabilities: Iterable[github.AdvisoryVulnerability.AdvisoryVulnerabilityInput] | None = None, + cwe_ids: Iterable[str] | None = None, + credits: Iterable[github.AdvisoryCredit.AdvisoryCredit] | None = None, + ) -> github.RepositoryAdvisory.RepositoryAdvisory: + """ + :calls: `POST /repos/{owner}/{repo}/security-advisories/reports `_ + :param summary: string + :param description: string + :param severity_or_cvss_vector_string: string + :param cve_id: string + :param vulnerabilities: iterable of :class:`github.AdvisoryVulnerability.AdvisoryVulnerabilityInput` + :param cwe_ids: iterable of string + :param credits: iterable of :class:`github.AdvisoryCredit.AdvisoryCredit` + :rtype: :class:`github.RepositoryAdvisory.RepositoryAdvisory` + """ + return self.__create_repository_advisory( + summary=summary, + description=description, + severity_or_cvss_vector_string=severity_or_cvss_vector_string, + cve_id=cve_id, + vulnerabilities=vulnerabilities, + cwe_ids=cwe_ids, + credits=credits, + private_vulnerability_reporting=True, + ) + + def __create_repository_advisory( + self, + summary: str, + description: str, + severity_or_cvss_vector_string: str, + cve_id: str | None, + vulnerabilities: Iterable[github.AdvisoryVulnerability.AdvisoryVulnerabilityInput] | None, + cwe_ids: Iterable[str] | None, + credits: Iterable[github.AdvisoryCredit.AdvisoryCredit] | None, + private_vulnerability_reporting: bool, + ) -> github.RepositoryAdvisory.RepositoryAdvisory: + if vulnerabilities is None: + vulnerabilities = [] + if cwe_ids is None: + cwe_ids = [] + assert isinstance(summary, str), summary + assert isinstance(description, str), description + assert isinstance(severity_or_cvss_vector_string, str), severity_or_cvss_vector_string + assert isinstance(cve_id, (str, type(None))), cve_id + assert isinstance(vulnerabilities, Iterable), vulnerabilities + for vulnerability in vulnerabilities: + github.AdvisoryVulnerability.AdvisoryVulnerability._validate_vulnerability(vulnerability) + assert isinstance(cwe_ids, Iterable), cwe_ids + assert all(isinstance(element, str) for element in cwe_ids), cwe_ids + assert isinstance(credits, (Iterable, type(None))), credits + if credits is not None: + for credit in credits: + github.AdvisoryCredit.AdvisoryCredit._validate_credit(credit) + post_parameters = { + "summary": summary, + "description": description, + "vulnerabilities": [ + github.AdvisoryVulnerability.AdvisoryVulnerability._to_github_dict(vulnerability) + for vulnerability in vulnerabilities + ], + "cwe_ids": list(cwe_ids), + } + if cve_id is not None: + post_parameters["cve_id"] = cve_id + if credits is not None: + post_parameters["credits"] = [ + github.AdvisoryCredit.AdvisoryCredit._to_github_dict(credit) for credit in credits + ] + if severity_or_cvss_vector_string.startswith("CVSS:"): + post_parameters["cvss_vector_string"] = severity_or_cvss_vector_string + else: + post_parameters["severity"] = severity_or_cvss_vector_string + if private_vulnerability_reporting: + headers, data = self._requester.requestJsonAndCheck( + "POST", f"{self.url}/security-advisories/reports", input=post_parameters + ) + else: + headers, data = self._requester.requestJsonAndCheck( + "POST", f"{self.url}/security-advisories", input=post_parameters + ) + return github.RepositoryAdvisory.RepositoryAdvisory(self._requester, headers, data) + + def create_repository_dispatch(self, event_type: str, client_payload: Opt[dict[str, Any]] = NotSet) -> bool: + """ + :calls: POST /repos/{owner}/{repo}/dispatches + :param event_type: string + :param client_payload: dict + :rtype: bool + """ + assert isinstance(event_type, str), event_type + assert is_optional(client_payload, dict), client_payload + post_parameters = NotSet.remove_unset_items({"event_type": event_type, "client_payload": client_payload}) + status, headers, data = self._requester.requestJson("POST", f"{self.url}/dispatches", input=post_parameters) + return status == 204 + + def create_secret( + self, + secret_name: str, + unencrypted_value: str, + secret_type: str = "actions", + ) -> github.Secret.Secret: + """ + :calls: `PUT /repos/{owner}/{repo}/{secret_type}/secrets/{secret_name} `_ + :param secret_type: string options actions or dependabot + """ + assert isinstance(secret_name, str), secret_name + assert isinstance(unencrypted_value, str), unencrypted_value + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + + secret_name = urllib.parse.quote(secret_name) + public_key = self.get_public_key(secret_type=secret_type) + payload = public_key.encrypt(unencrypted_value) + put_parameters = { + "key_id": public_key.key_id, + "encrypted_value": payload, + } + self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/{secret_type}/secrets/{secret_name}", input=put_parameters + ) + return github.Secret.Secret( + requester=self._requester, + headers={}, + attributes={ + "name": secret_name, + "url": f"{self.url}/{secret_type}/secrets/{secret_name}", + }, + completed=False, + ) + + def get_secrets( + self, + secret_type: str = "actions", + ) -> PaginatedList[github.Secret.Secret]: + """ + Gets all repository secrets :param secret_type: string options actions or dependabot. + """ + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + + return PaginatedList( + github.Secret.Secret, + self._requester, + f"{self.url}/{secret_type}/secrets", + None, + attributesTransformer=PaginatedList.override_attributes( + {"secrets_url": f"{self.url}/{secret_type}/secrets"} + ), + list_item="secrets", + ) + + def get_secret(self, secret_name: str, secret_type: str = "actions") -> github.Secret.Secret: + """ + :calls: 'GET /repos/{owner}/{repo}/actions/secrets/{secret_name} `_ + :param secret_type: string options actions or dependabot + """ + assert isinstance(secret_name, str), secret_name + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + + secret_name = urllib.parse.quote(secret_name) + return github.Secret.Secret( + requester=self._requester, + headers={}, + attributes={"url": f"{self.url}/{secret_type}/secrets/{secret_name}"}, + completed=False, + ) + + def create_variable(self, variable_name: str, value: str) -> github.Variable.Variable: + """ + :calls: `POST /repos/{owner}/{repo}/actions/variables/{variable_name} `_ + """ + assert isinstance(variable_name, str), variable_name + assert isinstance(value, str), value + post_parameters = { + "name": variable_name, + "value": value, + } + self._requester.requestJsonAndCheck("POST", f"{self.url}/actions/variables", input=post_parameters) + return github.Variable.Variable( + self._requester, + headers={}, + attributes={ + "name": variable_name, + "value": value, + "url": f"{self.url}/actions/variables/{variable_name}", + }, + completed=False, + ) + + def get_variables(self) -> PaginatedList[github.Variable.Variable]: + """ + Gets all repository variables :rtype: :class:`PaginatedList` of :class:`github.Variable.Variable` + """ + return PaginatedList( + github.Variable.Variable, + self._requester, + f"{self.url}/actions/variables", + None, + attributesTransformer=PaginatedList.override_attributes({"variables_url": f"{self.url}/actions/variables"}), + list_item="variables", + ) + + def get_variable(self, variable_name: str) -> github.Variable.Variable: + """ + :calls: 'GET /orgs/{org}/actions/variables/{variable_name} `_ + :param variable_name: string + :rtype: github.Variable.Variable + """ + assert isinstance(variable_name, str), variable_name + variable_name = urllib.parse.quote(variable_name) + return github.Variable.Variable( + requester=self._requester, + headers={}, + attributes={"url": f"{self.url}/actions/variables/{variable_name}"}, + completed=False, + ) + + def delete_secret(self, secret_name: str, secret_type: str = "actions") -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/{secret_type}/secrets/{secret_name} `_ + :param secret_name: string + :param secret_type: string options actions or dependabot + :rtype: bool + """ + assert isinstance(secret_name, str), secret_name + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + secret_name = urllib.parse.quote(secret_name) + status, headers, data = self._requester.requestJson("DELETE", f"{self.url}/{secret_type}/secrets/{secret_name}") + return status == 204 + + def delete_variable(self, variable_name: str) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/actions/variables/{variable_name} `_ + :param variable_name: string + :rtype: bool + """ + assert isinstance(variable_name, str), variable_name + variable_name = urllib.parse.quote(variable_name) + status, headers, data = self._requester.requestJson("DELETE", f"{self.url}/actions/variables/{variable_name}") + return status == 204 + + def create_source_import( + self, + vcs: str, + vcs_url: str, + vcs_username: Opt[str] = NotSet, + vcs_password: Opt[str] = NotSet, + ) -> SourceImport: + """ + :calls: `PUT /repos/{owner}/{repo}/import `_ + :param vcs: string + :param vcs_url: string + :param vcs_username: string + :param vcs_password: string + :rtype: :class:`github.SourceImport.SourceImport` + """ + assert isinstance(vcs, str), vcs + assert isinstance(vcs_url, str), vcs_url + assert is_optional(vcs_username, str), vcs_username + assert is_optional(vcs_password, str), vcs_password + put_parameters = {"vcs": vcs, "vcs_url": vcs_url} + + if is_defined(vcs_username): + put_parameters["vcs_username"] = vcs_username + + if is_defined(vcs_password): + put_parameters["vcs_password"] = vcs_password + + import_header = {"Accept": Consts.mediaTypeImportPreview} + + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/import", headers=import_header, input=put_parameters + ) + + return github.SourceImport.SourceImport(self._requester, headers, data, completed=False) + + def delete(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo} `_ + :rtype: None + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def edit( + self, + name: str | None = None, + description: Opt[str] = NotSet, + homepage: Opt[str] = NotSet, + private: Opt[bool] = NotSet, + visibility: Opt[str] = NotSet, + has_issues: Opt[bool] = NotSet, + has_projects: Opt[bool] = NotSet, + has_wiki: Opt[bool] = NotSet, + has_discussions: Opt[bool] = NotSet, + is_template: Opt[bool] = NotSet, + default_branch: Opt[str] = NotSet, + allow_squash_merge: Opt[bool] = NotSet, + allow_merge_commit: Opt[bool] = NotSet, + allow_rebase_merge: Opt[bool] = NotSet, + allow_auto_merge: Opt[bool] = NotSet, + delete_branch_on_merge: Opt[bool] = NotSet, + allow_update_branch: Opt[bool] = NotSet, + use_squash_pr_title_as_default: Opt[bool] = NotSet, + squash_merge_commit_title: Opt[str] = NotSet, + squash_merge_commit_message: Opt[str] = NotSet, + merge_commit_title: Opt[str] = NotSet, + merge_commit_message: Opt[str] = NotSet, + archived: Opt[bool] = NotSet, + allow_forking: Opt[bool] = NotSet, + web_commit_signoff_required: Opt[bool] = NotSet, + ) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo} `_ + """ + if name is None: + name = self.name + assert isinstance(name, str), name + assert is_optional(description, str), description + assert is_optional(homepage, str), homepage + assert is_optional(private, bool), private + assert visibility in ["public", "private", "internal", NotSet], visibility + assert is_optional(has_issues, bool), has_issues + assert is_optional(has_projects, bool), has_projects + assert is_optional(has_wiki, bool), has_wiki + assert is_optional(has_discussions, bool), has_discussions + assert is_optional(is_template, bool), is_template + assert is_optional(default_branch, str), default_branch + assert is_optional(allow_squash_merge, bool), allow_squash_merge + assert is_optional(allow_merge_commit, bool), allow_merge_commit + assert is_optional(allow_rebase_merge, bool), allow_rebase_merge + assert is_optional(allow_auto_merge, bool), allow_auto_merge + assert is_optional(delete_branch_on_merge, bool), delete_branch_on_merge + assert is_optional(allow_update_branch, bool), allow_update_branch + assert is_optional(use_squash_pr_title_as_default, bool), use_squash_pr_title_as_default + assert squash_merge_commit_title in ["PR_TITLE", "COMMIT_OR_PR_TITLE", NotSet], squash_merge_commit_title + assert squash_merge_commit_message in [ + "PR_BODY", + "COMMIT_MESSAGES", + "BLANK", + NotSet, + ], squash_merge_commit_message + assert merge_commit_title in ["PR_TITLE", "MERGE_MESSAGE", NotSet], merge_commit_title + assert merge_commit_message in ["PR_TITLE", "PR_BODY", "BLANK", NotSet], merge_commit_message + assert is_optional(archived, bool), archived + assert is_optional(allow_forking, bool), allow_forking + assert is_optional(web_commit_signoff_required, bool), web_commit_signoff_required + + post_parameters: dict[str, Any] = NotSet.remove_unset_items( + { + "name": name, + "description": description, + "homepage": homepage, + "private": private, + "visibility": visibility, + "has_issues": has_issues, + "has_projects": has_projects, + "has_wiki": has_wiki, + "has_discussions": has_discussions, + "is_template": is_template, + "default_branch": default_branch, + "allow_squash_merge": allow_squash_merge, + "allow_merge_commit": allow_merge_commit, + "allow_rebase_merge": allow_rebase_merge, + "allow_auto_merge": allow_auto_merge, + "delete_branch_on_merge": delete_branch_on_merge, + "allow_update_branch": allow_update_branch, + "use_squash_pr_title_as_default": use_squash_pr_title_as_default, + "squash_merge_commit_title": squash_merge_commit_title, + "squash_merge_commit_message": squash_merge_commit_message, + "merge_commit_title": merge_commit_title, + "merge_commit_message": merge_commit_message, + "archived": archived, + "allow_forking": allow_forking, + "web_commit_signoff_required": web_commit_signoff_required, + } + ) + + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def get_archive_link(self, archive_format: str, ref: Opt[str] = NotSet) -> str: + """ + :calls: `GET /repos/{owner}/{repo}/{archive_format}/{ref} `_ + :param archive_format: string + :param ref: string + :rtype: string + """ + assert isinstance(archive_format, str), archive_format + archive_format = urllib.parse.quote(archive_format) + assert is_optional(ref, str), ref + url = f"{self.url}/{archive_format}" + if is_defined(ref): + ref = urllib.parse.quote(ref) + url += f"/{ref}" + headers, data = self._requester.requestJsonAndCheck("GET", url) + return headers["location"] + + def get_assignees(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /repos/{owner}/{repo}/assignees `_ + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/assignees", None) + + def get_branch(self, branch: str) -> Branch: + """ + :calls: `GET /repos/{owner}/{repo}/branches/{branch} `_ + :param branch: string + :rtype: :class:`github.Branch.Branch` + """ + assert isinstance(branch, str), branch + branch = urllib.parse.quote(branch) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/branches/{branch}") + return github.Branch.Branch(self._requester, headers, data) + + def rename_branch(self, branch: str | Branch, new_name: str) -> bool: + """ + :calls: `POST /repos/{owner}/{repo}/branches/{branch}/rename `_ + :param branch: :class:`github.Branch.Branch` or string + :param new_name: string + :rtype: bool + + NOTE: This method does not return the branch since it may take some + time to fully complete server-side. + """ + is_branch = isinstance(branch, github.Branch.Branch) + assert isinstance(new_name, str), new_name + if is_branch: + branch = branch.name # type: ignore + else: + assert isinstance(branch, str), branch + branch = urllib.parse.quote(branch) + parameters = {"new_name": new_name} + status, _, _ = self._requester.requestJson("POST", f"{self.url}/branches/{branch}/rename", input=parameters) + return status == 201 + + def get_branches(self) -> PaginatedList[Branch]: + """ + :calls: `GET /repos/{owner}/{repo}/branches `_ + :rtype: :class:`PaginatedList` of :class:`github.Branch.Branch` + """ + return PaginatedList(github.Branch.Branch, self._requester, f"{self.url}/branches", None) + + def get_collaborators( + self, affiliation: Opt[str] = NotSet, permission: Opt[str] = NotSet + ) -> PaginatedList[NamedUser]: + """ + :calls: `GET /repos/{owner}/{repo}/collaborators `_ + :param affiliation: string + :param permission: string + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + + url_parameters = dict() + allowed_affiliations = ["outside", "direct", "all"] + allowed_permissions = ["pull", "triage", "push", "maintain", "admin"] + if is_defined(affiliation): + assert isinstance(affiliation, str), affiliation + assert affiliation in allowed_affiliations, f"Affiliation can be one of {', '.join(allowed_affiliations)}" + url_parameters["affiliation"] = affiliation + + if is_defined(permission): + assert isinstance(permission, str), permission + assert permission in allowed_permissions, f"permission can be one of {', '.join(allowed_permissions)}" + url_parameters["permission"] = permission + + return PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/collaborators", + url_parameters, + ) + + def get_comment(self, id: int) -> CommitComment: + """ + :calls: `GET /repos/{owner}/{repo}/comments/{id} `_ + :param id: integer + :rtype: :class:`github.CommitComment.CommitComment` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/comments/{id}") + return github.CommitComment.CommitComment(self._requester, headers, data, completed=True) + + def get_comments(self) -> PaginatedList[CommitComment]: + """ + :calls: `GET /repos/{owner}/{repo}/comments `_ + :rtype: :class:`PaginatedList` of :class:`github.CommitComment.CommitComment` + """ + return PaginatedList( + github.CommitComment.CommitComment, + self._requester, + f"{self.url}/comments", + None, + ) + + def get_commit(self, sha: str) -> Commit: + """ + :calls: `GET /repos/{owner}/{repo}/commits/{sha} `_ + :param sha: string + :rtype: :class:`github.Commit.Commit` + """ + assert isinstance(sha, str), sha + sha = urllib.parse.quote(sha) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/commits/{sha}") + return github.Commit.Commit(self._requester, headers, data, completed=True) + + def get_commits( + self, + sha: Opt[str] = NotSet, + path: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + until: Opt[datetime] = NotSet, + author: Opt[AuthenticatedUser | NamedUser | str] = NotSet, + ) -> PaginatedList[Commit]: + """ + :calls: `GET /repos/{owner}/{repo}/commits `_ + :param sha: string + :param path: string + :param since: datetime + :param until: datetime + :param author: string or :class:`github.NamedUser.NamedUser` or :class:`github.AuthenticatedUser.AuthenticatedUser` + :rtype: :class:`PaginatedList` of :class:`github.Commit.Commit` + """ + assert is_optional(sha, str), sha + assert is_optional(path, str), path + assert is_optional(since, datetime), since + assert is_optional(until, datetime), until + assert is_optional( + author, + (str, github.NamedUser.NamedUser, github.AuthenticatedUser.AuthenticatedUser), + ), author + url_parameters: dict[str, Any] = {} + if is_defined(sha): + url_parameters["sha"] = sha + if is_defined(path): + url_parameters["path"] = path + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + if is_defined(until): + url_parameters["until"] = until.strftime("%Y-%m-%dT%H:%M:%SZ") + if is_defined(author): + if isinstance( + author, + (github.NamedUser.NamedUser, github.AuthenticatedUser.AuthenticatedUser), + ): + url_parameters["author"] = author.login + else: + url_parameters["author"] = author + return PaginatedList(github.Commit.Commit, self._requester, f"{self.url}/commits", url_parameters) + + def get_contents(self, path: str, ref: Opt[str] = NotSet) -> list[ContentFile] | ContentFile: + """ + :calls: `GET /repos/{owner}/{repo}/contents/{path} `_ + :param path: string + :param ref: string + :rtype: :class:`github.ContentFile.ContentFile` or a list of them + """ + assert isinstance(path, str), path + assert is_optional(ref, str), ref + # Path of '/' should be the empty string. + if path == "/": + path = "" + url_parameters = dict() + if is_defined(ref): + url_parameters["ref"] = ref + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/contents/{urllib.parse.quote(path)}", + parameters=url_parameters, + follow_302_redirect=True, + ) + + if isinstance(data, list): + return [ + # Lazy completion only makes sense for files. See discussion + # here: https://github.com/jacquev6/PyGithub/issues/140#issuecomment-13481130 + github.ContentFile.ContentFile(self._requester, headers, item, completed=(item["type"] != "file")) + for item in data + ] + return github.ContentFile.ContentFile(self._requester, headers, data, completed=True) + + def get_deployments( + self, + sha: Opt[str] = NotSet, + ref: Opt[str] = NotSet, + task: Opt[str] = NotSet, + environment: Opt[str] = NotSet, + ) -> PaginatedList[Deployment]: + """ + :calls: `GET /repos/{owner}/{repo}/deployments `_ + :param: sha: string + :param: ref: string + :param: task: string + :param: environment: string + :rtype: :class:`PaginatedList` of :class:`github.Deployment.Deployment` + """ + assert is_optional(sha, str), sha + assert is_optional(ref, str), ref + assert is_optional(task, str), task + assert is_optional(environment, str), environment + parameters = {} + if is_defined(sha): + parameters["sha"] = sha + if is_defined(ref): + parameters["ref"] = ref + if is_defined(task): + parameters["task"] = task + if is_defined(environment): + parameters["environment"] = environment + return PaginatedList( + github.Deployment.Deployment, + self._requester, + f"{self.url}/deployments", + parameters, + headers={"Accept": Consts.deploymentEnhancementsPreview}, + ) + + def get_deployment(self, id_: int) -> Deployment: + """ + :calls: `GET /repos/{owner}/{repo}/deployments/{deployment_id} `_ + :param: id_: int + :rtype: :class:`github.Deployment.Deployment` + """ + assert isinstance(id_, int), id_ + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/deployments/{id_}", + headers={"Accept": Consts.deploymentEnhancementsPreview}, + ) + return github.Deployment.Deployment(self._requester, headers, data, completed=True) + + def create_deployment( + self, + ref: str, + task: Opt[str] = NotSet, + auto_merge: Opt[bool] = NotSet, + required_contexts: Opt[list[str]] = NotSet, + payload: Opt[dict[str, Any]] = NotSet, + environment: Opt[str] = NotSet, + description: Opt[str] = NotSet, + transient_environment: Opt[bool] = NotSet, + production_environment: Opt[bool] = NotSet, + ) -> Deployment: + """ + :calls: `POST /repos/{owner}/{repo}/deployments `_ + :param: ref: string + :param: task: string + :param: auto_merge: bool + :param: required_contexts: list of status contexts + :param: payload: dict + :param: environment: string + :param: description: string + :param: transient_environment: bool + :param: production_environment: bool + :rtype: :class:`github.Deployment.Deployment` + """ + assert isinstance(ref, str), ref + assert is_optional(task, str), task + assert is_optional(auto_merge, bool), auto_merge + assert is_optional(required_contexts, list), required_contexts # need to do better checking here + assert is_optional(payload, dict), payload + assert is_optional(environment, str), environment + assert is_optional(description, str), description + assert is_optional(transient_environment, bool), transient_environment + assert is_optional(production_environment, bool), production_environment + + post_parameters: dict[str, Any] = {"ref": ref} + if is_defined(task): + post_parameters["task"] = task + if is_defined(auto_merge): + post_parameters["auto_merge"] = auto_merge + if is_defined(required_contexts): + post_parameters["required_contexts"] = required_contexts + if is_defined(payload): + post_parameters["payload"] = payload + if is_defined(environment): + post_parameters["environment"] = environment + if is_defined(description): + post_parameters["description"] = description + if is_defined(transient_environment): + post_parameters["transient_environment"] = transient_environment + if is_defined(production_environment): + post_parameters["production_environment"] = production_environment + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/deployments", + input=post_parameters, + headers={"Accept": Consts.deploymentEnhancementsPreview}, + ) + + return github.Deployment.Deployment(self._requester, headers, data, completed=True) + + def get_discussion( + self, + number: int, + discussion_graphql_schema: str, + ) -> RepositoryDiscussion: + assert isinstance(number, int), number + if not discussion_graphql_schema.startswith("\n"): + discussion_graphql_schema = f" {discussion_graphql_schema} " + query = ( + """ + query Q($repo: String!, $owner: String!, $number: Int!) { + repository(name: $repo, owner: $owner) { + discussion(number: $number) {""" + + discussion_graphql_schema + + """} + } + } + """ + ) + variables = { + "repo": self.name, + "owner": self.owner.login, + "number": number, + } + return self._requester.graphql_query_class( + query, variables, ["repository", "discussion"], github.RepositoryDiscussion.RepositoryDiscussion + ) + + def get_discussions( + self, + discussion_graphql_schema: str, + *, + answered: bool | None = None, + category_id: str | None = None, + states: list[str] | None = None, + ) -> PaginatedList[RepositoryDiscussion]: + if not discussion_graphql_schema.startswith("\n"): + discussion_graphql_schema = f" {discussion_graphql_schema} " + query = ( + """ + query Q($repo: String!, $owner: String!, $answered: Boolean, $category_id: ID, $states: [DiscussionState!], $first: Int, $last: Int, $before: String, $after: String) { + repository(name: $repo, owner: $owner) { + discussions(answered: $answered, categoryId: $category_id, states: $states, first: $first, last: $last, before: $before, after: $after) { + totalCount + pageInfo { + startCursor + endCursor + hasNextPage + hasPreviousPage + } + nodes {""" + + discussion_graphql_schema + + """} + } + } + } + """ + ) + variables = { + "repo": self.name, + "owner": self.owner.login, + "answered": answered, + "category_id": category_id, + "states": states, + } + return PaginatedList( + github.RepositoryDiscussion.RepositoryDiscussion, + self._requester, + graphql_query=query, + graphql_variables=variables, + list_item=["repository", "discussions"], + ) + + def get_top_referrers(self) -> None | list[Referrer]: + """ + :calls: `GET /repos/{owner}/{repo}/traffic/popular/referrers `_ + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/traffic/popular/referrers") + if isinstance(data, list): + return [github.Referrer.Referrer(self._requester, headers, item) for item in data] + + def get_top_paths(self) -> None | list[Path]: + """ + :calls: `GET /repos/{owner}/{repo}/traffic/popular/paths `_ + :rtype: :class:`list` of :class:`github.Path.Path` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/traffic/popular/paths") + if isinstance(data, list): + return [github.Path.Path(self._requester, headers, item) for item in data] + + def get_views_traffic(self, per: Opt[str] = NotSet) -> View | None: + """ + :calls: `GET /repos/{owner}/{repo}/traffic/views `_ + :param per: string, must be one of day or week, day by default + :rtype: None or list of :class:`github.View.View` + """ + assert per in ["day", "week", NotSet], "per must be day or week, day by default" + url_parameters = dict() + if is_defined(per): + url_parameters["per"] = per + headers, data = self._requester.requestJsonAndCheck( + "GET", f"{self.url}/traffic/views", parameters=url_parameters + ) + return github.View.View(self._requester, headers, data) + + def get_clones_traffic(self, per: Opt[str] = NotSet) -> Clones | None: + """ + :calls: `GET /repos/{owner}/{repo}/traffic/clones `_ + :param per: string, must be one of day or week, day by default + :rtype: None or list of :class:`github.Clones.Clones` + """ + assert per in ["day", "week", NotSet], "per must be day or week, day by default" + url_parameters: dict[str, Any] = NotSet.remove_unset_items({"per": per}) + headers, data = self._requester.requestJsonAndCheck( + "GET", f"{self.url}/traffic/clones", parameters=url_parameters + ) + return github.Clones.Clones(self._requester, headers, data) + + def get_projects(self, state: Opt[str] = NotSet) -> PaginatedList[Project]: + """ + :calls: `GET /repos/{owner}/{repo}/projects `_ + :rtype: :class:`PaginatedList` of :class:`github.Project.Project` + :param state: string + """ + + url_parameters = dict() + if is_defined(state): + url_parameters["state"] = state + + return PaginatedList( + github.Project.Project, + self._requester, + f"{self.url}/projects", + url_parameters, + headers={"Accept": Consts.mediaTypeProjectsPreview}, + ) + + def get_autolinks(self) -> PaginatedList[Autolink]: + """ + :calls: `GET /repos/{owner}/{repo}/autolinks `_ + :rtype: :class:`PaginatedList` of :class:`github.Autolink.Autolink` + """ + return PaginatedList(github.Autolink.Autolink, self._requester, f"{self.url}/autolinks", None) + + def create_file( + self, + path: str, + message: str, + content: str | bytes, + branch: Opt[str] = NotSet, + committer: Opt[InputGitAuthor] = NotSet, + author: Opt[InputGitAuthor] = NotSet, + ) -> dict[str, ContentFile | Commit]: + """ + Create a file in this repository. + + :calls: `PUT /repos/{owner}/{repo}/contents/{path} `_ + :param path: string, (required), path of the file in the repository + :param message: string, (required), commit message + :param content: string, (required), the actual data in the file + :param branch: string, (optional), branch to create the commit on. Defaults to the default branch of the + repository + :param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information + will be used. You must specify both a name and email. + :param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If + passed, you must specify both a name and email. + :rtype: { 'content': :class:`ContentFile `:, 'commit': :class:`Commit + `} + + """ + assert isinstance(path, str) + assert isinstance(message, str) + assert isinstance(content, (str, bytes)) + assert is_optional(branch, str) + assert is_optional(author, github.InputGitAuthor) + assert is_optional(committer, github.InputGitAuthor) + + if not isinstance(content, bytes): + content = content.encode("utf-8") + content = b64encode(content).decode("utf-8") + put_parameters: dict[str, Any] = {"message": message, "content": content} + + if is_defined(branch): + put_parameters["branch"] = branch + if is_defined(author): + put_parameters["author"] = author._identity + if is_defined(committer): + put_parameters["committer"] = committer._identity + + headers, data = self._requester.requestJsonAndCheck( + "PUT", + f"{self.url}/contents/{urllib.parse.quote(path)}", + input=put_parameters, + ) + + return { + "content": github.ContentFile.ContentFile(self._requester, headers, data["content"], completed=False), + "commit": github.Commit.Commit(self._requester, headers, data["commit"], completed=True), + } + + def get_repository_advisories( + self, + ) -> PaginatedList[github.RepositoryAdvisory.RepositoryAdvisory]: + """ + :calls: `GET /repos/{owner}/{repo}/security-advisories `_ + :rtype: :class:`PaginatedList` of :class:`github.RepositoryAdvisory.RepositoryAdvisory` + """ + return PaginatedList( + github.RepositoryAdvisory.RepositoryAdvisory, + self._requester, + f"{self.url}/security-advisories", + None, + ) + + def get_repository_advisory(self, ghsa: str) -> github.RepositoryAdvisory.RepositoryAdvisory: + """ + :calls: `GET /repos/{owner}/{repo}/security-advisories/{ghsa} `_ + :param ghsa: string + :rtype: :class:`github.RepositoryAdvisory.RepositoryAdvisory` + """ + assert isinstance(ghsa, str), ghsa + ghsa = urllib.parse.quote(ghsa) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/security-advisories/{ghsa}") + return github.RepositoryAdvisory.RepositoryAdvisory(self._requester, headers, data) + + def update_file( + self, + path: str, + message: str, + content: bytes | str, + sha: str, + branch: Opt[str] = NotSet, + committer: Opt[InputGitAuthor] = NotSet, + author: Opt[InputGitAuthor] = NotSet, + ) -> dict[str, ContentFile | Commit]: + """ + This method updates a file in a repository. + + :calls: `PUT /repos/{owner}/{repo}/contents/{path} `_ + :param path: string, Required. The content path. + :param message: string, Required. The commit message. + :param content: string, Required. The updated file content, either base64 encoded, or ready to be encoded. + :param sha: string, Required. The blob SHA of the file being replaced. + :param branch: string. The branch name. Default: the repository’s default branch (usually master) + :param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information + will be used. You must specify both a name and email. + :param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If + passed, you must specify both a name and email. + :rtype: { 'content': :class:`ContentFile `:, 'commit': :class:`Commit + `} + + """ + assert isinstance(path, str) + assert isinstance(message, str) + assert isinstance(content, (str, bytes)) + assert isinstance(sha, str) + assert is_optional(branch, str) + assert is_optional(author, github.InputGitAuthor) + assert is_optional(committer, github.InputGitAuthor) + + if not isinstance(content, bytes): + content = content.encode("utf-8") + content = b64encode(content).decode("utf-8") + + put_parameters: dict[str, Any] = {"message": message, "content": content, "sha": sha} + + if is_defined(branch): + put_parameters["branch"] = branch + if is_defined(author): + put_parameters["author"] = author._identity + if is_defined(committer): + put_parameters["committer"] = committer._identity + + headers, data = self._requester.requestJsonAndCheck( + "PUT", + f"{self.url}/contents/{urllib.parse.quote(path)}", + input=put_parameters, + ) + + return { + "commit": github.Commit.Commit(self._requester, headers, data["commit"], completed=True), + "content": github.ContentFile.ContentFile(self._requester, headers, data["content"], completed=False), + } + + def delete_file( + self, + path: str, + message: str, + sha: str, + branch: Opt[str] = NotSet, + committer: Opt[InputGitAuthor] = NotSet, + author: Opt[InputGitAuthor] = NotSet, + ) -> dict[str, Commit | _NotSetType]: + """ + This method deletes a file in a repository. + + :calls: `DELETE /repos/{owner}/{repo}/contents/{path} `_ + :param path: string, Required. The content path. + :param message: string, Required. The commit message. + :param sha: string, Required. The blob SHA of the file being replaced. + :param branch: string. The branch name. Default: the repository’s default branch (usually master) + :param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information + will be used. You must specify both a name and email. + :param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If + passed, you must specify both a name and email. + :rtype: { 'content': :class:`null `:, 'commit': :class:`Commit `} + + """ + assert isinstance(path, str), "path must be str/unicode object" + assert isinstance(message, str), "message must be str/unicode object" + assert isinstance(sha, str), "sha must be a str/unicode object" + assert is_optional(branch, str), "branch must be a str/unicode object" + assert is_optional(author, github.InputGitAuthor), "author must be a github.InputGitAuthor object" + assert is_optional(committer, github.InputGitAuthor), "committer must be a github.InputGitAuthor object" + + url_parameters: dict[str, Any] = {"message": message, "sha": sha} + if is_defined(branch): + url_parameters["branch"] = branch + if is_defined(author): + url_parameters["author"] = author._identity + if is_defined(committer): + url_parameters["committer"] = committer._identity + + headers, data = self._requester.requestJsonAndCheck( + "DELETE", + f"{self.url}/contents/{urllib.parse.quote(path)}", + input=url_parameters, + ) + + return { + "commit": github.Commit.Commit(self._requester, headers, data["commit"], completed=True), + "content": NotSet, + } + + @deprecated( + reason=""" + Repository.get_dir_contents() is deprecated, use + Repository.get_contents() instead. + """ + ) + def get_dir_contents(self, path: str, ref: Opt[str] = NotSet) -> list[ContentFile]: + """ + :calls: `GET /repos/{owner}/{repo}/contents/{path} `_ + """ + return self.get_contents(path, ref=ref) # type: ignore + + def get_contributors(self, anon: Opt[str] = NotSet) -> PaginatedList[NamedUser]: + """ + :calls: `GET /repos/{owner}/{repo}/contributors `_ + :param anon: string + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + url_parameters = dict() + if is_defined(anon): + url_parameters["anon"] = anon + + return PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/contributors", + url_parameters, + ) + + def get_download(self, id: int) -> Download: + """ + :calls: `GET /repos/{owner}/{repo}/downloads/{id} `_ + :param id: integer + :rtype: :class:`github.Download.Download` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/downloads/{id}") + return github.Download.Download(self._requester, headers, data, completed=True) + + def get_downloads(self) -> PaginatedList[Download]: + """ + :calls: `GET /repos/{owner}/{repo}/downloads `_ + :rtype: :class:`PaginatedList` of :class:`github.Download.Download` + """ + return PaginatedList(github.Download.Download, self._requester, f"{self.url}/downloads", None) + + def get_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /repos/{owner}/{repo}/events `_ + :rtype: :class:`PaginatedList` of :class:`github.Event.Event` + """ + return PaginatedList(github.Event.Event, self._requester, f"{self.url}/events", None) + + def get_forks(self) -> PaginatedList[Repository]: + """ + :calls: `GET /repos/{owner}/{repo}/forks `_ + :rtype: :class:`PaginatedList` of :class:`github.Repository.Repository` + """ + return PaginatedList(Repository, self._requester, f"{self.url}/forks", None) + + def create_fork( + self, + organization: Organization | Opt[str] = NotSet, + name: Opt[str] = NotSet, + default_branch_only: Opt[bool] = NotSet, + ) -> Repository: + """ + :calls: `POST /repos/{owner}/{repo}/forks `_ + :param organization: :class:`github.Organization.Organization` or string + :param name: string + :param default_branch_only: bool + :rtype: :class:`github.Repository.Repository` + """ + post_parameters: dict[str, Any] = {} + if isinstance(organization, github.Organization.Organization): + post_parameters["organization"] = organization.login + elif isinstance(organization, str): + post_parameters["organization"] = organization + else: + assert is_undefined(organization), organization + assert is_optional(name, str), name + assert is_optional(default_branch_only, bool), default_branch_only + if is_defined(name): + post_parameters["name"] = name + if is_defined(default_branch_only): + post_parameters["default_branch_only"] = default_branch_only + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/forks", + input=post_parameters, + ) + return Repository(self._requester, headers, data, completed=True) + + def get_git_blob(self, sha: str) -> GitBlob: + """ + :calls: `GET /repos/{owner}/{repo}/git/blobs/{sha} `_ + :param sha: string + :rtype: :class:`github.GitBlob.GitBlob` + """ + assert isinstance(sha, str), sha + sha = urllib.parse.quote(sha) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/git/blobs/{sha}") + return github.GitBlob.GitBlob(self._requester, headers, data, completed=True) + + def get_git_commit(self, sha: str) -> GitCommit: + """ + :calls: `GET /repos/{owner}/{repo}/git/commits/{sha} `_ + :param sha: string + :rtype: :class:`github.GitCommit.GitCommit` + """ + assert isinstance(sha, str), sha + sha = urllib.parse.quote(sha) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/git/commits/{sha}") + return github.GitCommit.GitCommit(self._requester, headers, data, completed=True) + + def get_git_ref(self, ref: str) -> GitRef: + """ + :calls: `GET /repos/{owner}/{repo}/git/refs/{ref} `_ + :param ref: string + :rtype: :class:`github.GitRef.GitRef` + """ + prefix = "/git/refs/" + if not self._requester.FIX_REPO_GET_GIT_REF: + prefix = "/git/" + assert isinstance(ref, str), ref + ref = urllib.parse.quote(ref) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}{prefix}{ref}") + return github.GitRef.GitRef(self._requester, headers, data, completed=True) + + def get_git_refs(self) -> PaginatedList[GitRef]: + """ + :calls: `GET /repos/{owner}/{repo}/git/refs `_ + :rtype: :class:`PaginatedList` of :class:`github.GitRef.GitRef` + """ + return PaginatedList(github.GitRef.GitRef, self._requester, f"{self.url}/git/refs", None) + + def get_git_matching_refs(self, ref: str) -> PaginatedList[GitRef]: + """ + :calls: `GET /repos/{owner}/{repo}/git/matching-refs/{ref} `_ + :rtype: :class:`PaginatedList` of :class:`github.GitRef.GitRef` + """ + assert isinstance(ref, str), ref + ref = urllib.parse.quote(ref) + return PaginatedList( + github.GitRef.GitRef, + self._requester, + f"{self.url}/git/matching-refs/{ref}", + None, + ) + + def get_git_tag(self, sha: str) -> GitTag: + """ + :calls: `GET /repos/{owner}/{repo}/git/tags/{sha} `_ + :param sha: string + :rtype: :class:`github.GitTag.GitTag` + """ + assert isinstance(sha, str), sha + sha = urllib.parse.quote(sha) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/git/tags/{sha}") + return github.GitTag.GitTag(self._requester, headers, data, completed=True) + + def get_git_tree(self, sha: str, recursive: Opt[bool] = NotSet) -> GitTree: + """ + :calls: `GET /repos/{owner}/{repo}/git/trees/{sha} `_ + :param sha: string + :param recursive: bool + :rtype: :class:`github.GitTree.GitTree` + """ + assert isinstance(sha, str), sha + assert is_optional(recursive, bool), recursive + sha = urllib.parse.quote(sha) + url_parameters = dict() + if is_defined(recursive) and recursive: + # GitHub API requires the recursive parameter be set to 1. + url_parameters["recursive"] = 1 + headers, data = self._requester.requestJsonAndCheck( + "GET", f"{self.url}/git/trees/{sha}", parameters=url_parameters + ) + return github.GitTree.GitTree(self._requester, headers, data, completed=True) + + def get_hook(self, id: int) -> Hook: + """ + :calls: `GET /repos/{owner}/{repo}/hooks/{id} `_ + :param id: integer + :rtype: :class:`github.Hook.Hook` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/hooks/{id}") + return github.Hook.Hook(self._requester, headers, data, completed=True) + + def get_hooks(self) -> PaginatedList[Hook]: + """ + :calls: `GET /repos/{owner}/{repo}/hooks `_ + :rtype: :class:`PaginatedList` of :class:`github.Hook.Hook` + """ + return PaginatedList(github.Hook.Hook, self._requester, f"{self.url}/hooks", None) + + def get_hook_delivery(self, hook_id: int, delivery_id: int) -> github.HookDelivery.HookDelivery: + """ + :calls: `GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id} `_ + :param hook_id: integer + :param delivery_id: integer + :rtype: :class:`github.HookDelivery.HookDelivery` + """ + assert isinstance(hook_id, int), hook_id + assert isinstance(delivery_id, int), delivery_id + headers, data = self._requester.requestJsonAndCheck( + "GET", f"{self.url}/hooks/{hook_id}/deliveries/{delivery_id}" + ) + return github.HookDelivery.HookDelivery(self._requester, headers, data) + + def get_hook_deliveries(self, hook_id: int) -> PaginatedList[github.HookDelivery.HookDeliverySummary]: + """ + :calls: `GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries `_ + :param hook_id: integer + :rtype: :class:`PaginatedList` of :class:`github.HookDelivery.HookDeliverySummary` + """ + assert isinstance(hook_id, int), hook_id + + return PaginatedList( + github.HookDelivery.HookDeliverySummary, + self._requester, + f"{self.url}/hooks/{hook_id}/deliveries", + None, + ) + + def get_issue(self, number: int) -> Issue: + """ + :calls: `GET /repos/{owner}/{repo}/issues/{number} `_ + :param number: integer + :rtype: :class:`github.Issue.Issue` + """ + assert isinstance(number, int), number + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/issues/{number}") + return github.Issue.Issue(self._requester, headers, data, completed=True) + + def get_issues( + self, + milestone: Milestone | Opt[str] = NotSet, + state: Opt[str] = NotSet, + assignee: NamedUser | Opt[str] = NotSet, + mentioned: Opt[NamedUser] = NotSet, + labels: Opt[list[str] | list[Label]] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + creator: Opt[NamedUser] = NotSet, + ) -> PaginatedList[Issue]: + """ + :calls: `GET /repos/{owner}/{repo}/issues `_ + :param milestone: :class:`github.Milestone.Milestone` or "none" or "*" + :param state: string. `open`, `closed`, or `all`. If this is not set the GitHub API default behavior will be used. At the moment this is to return only open issues. This might change anytime on GitHub API side and it could be clever to explicitly specify the state value. + :param assignee: string or :class:`github.NamedUser.NamedUser` or "none" or "*" + :param mentioned: :class:`github.NamedUser.NamedUser` + :param labels: list of string or :class:`github.Label.Label` + :param sort: string + :param direction: string + :param since: datetime + :param creator: string or :class:`github.NamedUser.NamedUser` + :rtype: :class:`PaginatedList` of :class:`github.Issue.Issue` + """ + assert milestone in ["*", "none", NotSet] or isinstance(milestone, github.Milestone.Milestone), milestone + assert is_optional(state, str), state + assert is_optional(assignee, (str, github.NamedUser.NamedUser)), assignee + assert is_optional(mentioned, github.NamedUser.NamedUser), mentioned + assert is_optional_list(labels, (github.Label.Label, str)), labels + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + assert is_optional(since, datetime), since + assert is_optional(creator, (str, github.NamedUser.NamedUser)), creator + url_parameters: dict[str, Any] = {} + if is_defined(milestone): + if isinstance(milestone, github.Milestone.Milestone): + url_parameters["milestone"] = milestone._identity + else: + url_parameters["milestone"] = milestone + if is_defined(state): + url_parameters["state"] = state + if is_defined(assignee): + if isinstance(assignee, github.NamedUser.NamedUser): + url_parameters["assignee"] = assignee._identity + else: + url_parameters["assignee"] = assignee + if is_defined(mentioned): + url_parameters["mentioned"] = mentioned._identity + if is_defined(labels): + url_parameters["labels"] = ",".join( + [label.name if isinstance(label, github.Label.Label) else label for label in labels] # type: ignore + ) + if is_defined(sort): + url_parameters["sort"] = sort + if is_defined(direction): + url_parameters["direction"] = direction + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + if is_defined(creator): + if isinstance(creator, str): + url_parameters["creator"] = creator + else: + url_parameters["creator"] = creator._identity + return PaginatedList(github.Issue.Issue, self._requester, f"{self.url}/issues", url_parameters) + + def get_issues_comments( + self, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + ) -> PaginatedList[IssueComment]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/comments `_ + :param sort: string + :param direction: string + :param since: datetime + :rtype: :class:`PaginatedList` of :class:`github.IssueComment.IssueComment` + """ + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + assert is_optional(since, datetime), since + url_parameters = dict() + if is_defined(sort): + url_parameters["sort"] = sort + if is_defined(direction): + url_parameters["direction"] = direction + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + return PaginatedList( + github.IssueComment.IssueComment, + self._requester, + f"{self.url}/issues/comments", + url_parameters, + ) + + def get_issues_event(self, id: int) -> IssueEvent: + """ + :calls: `GET /repos/{owner}/{repo}/issues/events/{id} `_ + :param id: integer + :rtype: :class:`github.IssueEvent.IssueEvent` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/issues/events/{id}", + headers={"Accept": Consts.mediaTypeLockReasonPreview}, + ) + return github.IssueEvent.IssueEvent(self._requester, headers, data, completed=True) + + def get_issues_events(self) -> PaginatedList[IssueEvent]: + """ + :calls: `GET /repos/{owner}/{repo}/issues/events `_ + :rtype: :class:`PaginatedList` of :class:`github.IssueEvent.IssueEvent` + """ + return PaginatedList( + github.IssueEvent.IssueEvent, + self._requester, + f"{self.url}/issues/events", + None, + headers={"Accept": Consts.mediaTypeLockReasonPreview}, + ) + + def get_key(self, id: int) -> RepositoryKey: + """ + :calls: `GET /repos/{owner}/{repo}/keys/{id} `_ + :param id: integer + :rtype: :class:`github.RepositoryKey.RepositoryKey` + """ + assert isinstance(id, int), id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/keys/{id}") + return github.RepositoryKey.RepositoryKey(self._requester, headers, data, completed=True) + + def get_keys(self) -> PaginatedList[RepositoryKey]: + """ + :calls: `GET /repos/{owner}/{repo}/keys `_ + :rtype: :class:`PaginatedList` of :class:`github.RepositoryKey.RepositoryKey` + """ + return PaginatedList( + github.RepositoryKey.RepositoryKey, + self._requester, + f"{self.url}/keys", + None, + ) + + def get_label(self, name: str) -> Label: + """ + :calls: `GET /repos/{owner}/{repo}/labels/{name} `_ + :param name: string + :rtype: :class:`github.Label.Label` + """ + assert isinstance(name, str), name + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/labels/{urllib.parse.quote(name)}") + return github.Label.Label(self._requester, headers, data, completed=True) + + def get_labels(self) -> PaginatedList[Label]: + """ + :calls: `GET /repos/{owner}/{repo}/labels `_ + :rtype: :class:`PaginatedList` of :class:`github.Label.Label` + """ + return PaginatedList(github.Label.Label, self._requester, f"{self.url}/labels", None) + + def get_languages(self) -> dict[str, int]: + """ + :calls: `GET /repos/{owner}/{repo}/languages `_ + :rtype: dict of string to integer + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/languages") + return data + + def get_license(self) -> ContentFile: + """ + :calls: `GET /repos/{owner}/{repo}/license `_ + :rtype: :class:`github.ContentFile.ContentFile` + """ + + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/license") + return github.ContentFile.ContentFile(self._requester, headers, data, completed=True) + + def get_milestone(self, number: int) -> Milestone: + """ + :calls: `GET /repos/{owner}/{repo}/milestones/{number} `_ + :param number: integer + :rtype: :class:`github.Milestone.Milestone` + """ + assert isinstance(number, int), number + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/milestones/{number}") + return github.Milestone.Milestone(self._requester, headers, data, completed=True) + + def get_milestones( + self, + state: Opt[str] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + ) -> PaginatedList[Milestone]: + """ + :calls: `GET /repos/{owner}/{repo}/milestones `_ + :param state: string + :param sort: string + :param direction: string + :rtype: :class:`PaginatedList` of :class:`github.Milestone.Milestone` + """ + assert is_optional(state, str), state + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + url_parameters = dict() + if is_defined(state): + url_parameters["state"] = state + if is_defined(sort): + url_parameters["sort"] = sort + if is_defined(direction): + url_parameters["direction"] = direction + return PaginatedList( + github.Milestone.Milestone, + self._requester, + f"{self.url}/milestones", + url_parameters, + ) + + def get_network_events(self) -> PaginatedList[Event]: + """ + :calls: `GET /networks/{owner}/{repo}/events `_ + :rtype: :class:`PaginatedList` of :class:`github.Event.Event` + """ + return PaginatedList( + github.Event.Event, + self._requester, + f"/networks/{self.owner.login}/{self.name}/events", + None, + ) + + def get_public_key(self, secret_type: str = "actions") -> PublicKey: + """ + :calls: `GET /repos/{owner}/{repo}/actions/secrets/public-key `_ + :param secret_type: string options actions or dependabot + :rtype: :class:`github.PublicKey.PublicKey` + """ + assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot" + + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/{secret_type}/secrets/public-key") + return github.PublicKey.PublicKey(self._requester, headers, data, completed=True) + + def get_pull(self, number: int) -> PullRequest: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/{number} `_ + :param number: integer + :rtype: :class:`github.PullRequest.PullRequest` + """ + assert isinstance(number, int), number + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/pulls/{number}") + return github.PullRequest.PullRequest(self._requester, headers, data, completed=True) + + def get_pulls( + self, + state: Opt[str] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + base: Opt[str] = NotSet, + head: Opt[str] = NotSet, + ) -> PaginatedList[PullRequest]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls `_ + :param state: string + :param sort: string + :param direction: string + :param base: string + :param head: string + :rtype: :class:`PaginatedList` of :class:`github.PullRequest.PullRequest` + """ + assert is_optional(state, str), state + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + assert is_optional(base, str), base + assert is_optional(head, str), head + url_parameters = dict() + if is_defined(state): + url_parameters["state"] = state + if is_defined(sort): + url_parameters["sort"] = sort + if is_defined(direction): + url_parameters["direction"] = direction + if is_defined(base): + url_parameters["base"] = base + if is_defined(head): + url_parameters["head"] = head + return PaginatedList( + github.PullRequest.PullRequest, + self._requester, + f"{self.url}/pulls", + url_parameters, + ) + + def get_pulls_comments( + self, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + ) -> PaginatedList[PullRequestComment]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/comments `_ + :param sort: string + :param direction: string + :param since: datetime + :rtype: :class:`PaginatedList` of :class:`github.PullRequestComment.PullRequestComment` + """ + return self.get_pulls_review_comments(sort, direction, since) + + def get_pulls_review_comments( + self, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + since: Opt[datetime] = NotSet, + ) -> PaginatedList[PullRequestComment]: + """ + :calls: `GET /repos/{owner}/{repo}/pulls/comments `_ + :param sort: string 'created', 'updated', 'created_at' + :param direction: string 'asc' or 'desc' + :param since: datetime + :rtype: :class:`PaginatedList` of :class:`github.PullRequestComment.PullRequestComment` + """ + assert is_optional(sort, str), sort + assert is_optional(direction, str), direction + assert is_optional(since, datetime), since + url_parameters = dict() + if is_defined(sort): + url_parameters["sort"] = sort + if is_defined(direction): + url_parameters["direction"] = direction + if is_defined(since): + url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + return PaginatedList( + github.PullRequestComment.PullRequestComment, + self._requester, + f"{self.url}/pulls/comments", + url_parameters, + ) + + def get_readme(self, ref: Opt[str] = NotSet) -> ContentFile: + """ + :calls: `GET /repos/{owner}/{repo}/readme `_ + :param ref: string + :rtype: :class:`github.ContentFile.ContentFile` + """ + assert is_optional(ref, str), ref + url_parameters = dict() + if is_defined(ref): + url_parameters["ref"] = ref + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/readme", parameters=url_parameters) + return github.ContentFile.ContentFile(self._requester, headers, data, completed=True) + + def get_self_hosted_runner(self, runner_id: int) -> SelfHostedActionsRunner: + """ + :calls: `GET /repos/{owner}/{repo}/actions/runners/{id} `_ + :param runner_id: int + :rtype: :class:`github.SelfHostedActionsRunner.SelfHostedActionsRunner` + """ + assert isinstance(runner_id, int), runner_id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/runners/{runner_id}") + return github.SelfHostedActionsRunner.SelfHostedActionsRunner(self._requester, headers, data) + + def get_self_hosted_runners(self) -> PaginatedList[SelfHostedActionsRunner]: + """ + :calls: `GET /repos/{owner}/{repo}/actions/runners `_ + :rtype: :class:`PaginatedList` of :class:`github.SelfHostedActionsRunner.SelfHostedActionsRunner` + """ + return PaginatedList( + github.SelfHostedActionsRunner.SelfHostedActionsRunner, + self._requester, + f"{self.url}/actions/runners", + None, + list_item="runners", + ) + + def get_source_import(self) -> SourceImport | None: + """ + :calls: `GET /repos/{owner}/{repo}/import `_ + """ + import_header = {"Accept": Consts.mediaTypeImportPreview} + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/import", + headers=import_header, + ) + if not data: + return None + else: + return github.SourceImport.SourceImport(self._requester, headers, data, completed=True) + + def get_stargazers(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /repos/{owner}/{repo}/stargazers `_ + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/stargazers", None) + + def get_stargazers_with_dates(self) -> PaginatedList[Stargazer]: + """ + :calls: `GET /repos/{owner}/{repo}/stargazers `_ + :rtype: :class:`PaginatedList` of :class:`github.Stargazer.Stargazer` + """ + return PaginatedList( + github.Stargazer.Stargazer, + self._requester, + f"{self.url}/stargazers", + None, + headers={"Accept": Consts.mediaTypeStarringPreview}, + ) + + def get_stats_contributors(self) -> list[StatsContributor] | None: + """ + :calls: `GET /repos/{owner}/{repo}/stats/contributors `_ + :rtype: None or list of :class:`github.StatsContributor.StatsContributor` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/contributors") + if not data: + return None + else: + return [ + github.StatsContributor.StatsContributor(self._requester, headers, attributes) for attributes in data + ] + + def get_stats_commit_activity(self) -> list[StatsCommitActivity] | None: + """ + :calls: `GET /repos/{owner}/{repo}/stats/commit_activity `_ + :rtype: None or list of :class:`github.StatsCommitActivity.StatsCommitActivity` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/commit_activity") + if not data: + return None + else: + return [ + github.StatsCommitActivity.StatsCommitActivity(self._requester, headers, attributes) + for attributes in data + ] + + def get_stats_code_frequency(self) -> list[StatsCodeFrequency] | None: + """ + :calls: `GET /repos/{owner}/{repo}/stats/code_frequency `_ + :rtype: None or list of :class:`github.StatsCodeFrequency.StatsCodeFrequency` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/code_frequency") + if not data: + return None + else: + return [ + github.StatsCodeFrequency.StatsCodeFrequency(self._requester, headers, attributes) + for attributes in data + ] + + def get_stats_participation(self) -> StatsParticipation | None: + """ + :calls: `GET /repos/{owner}/{repo}/stats/participation `_ + :rtype: None or :class:`github.StatsParticipation.StatsParticipation` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/participation") + if not data: + return None + else: + return github.StatsParticipation.StatsParticipation(self._requester, headers, data) + + def get_stats_punch_card(self) -> StatsPunchCard | None: + """ + :calls: `GET /repos/{owner}/{repo}/stats/punch_card `_ + :rtype: None or :class:`github.StatsPunchCard.StatsPunchCard` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/punch_card") + if not data: + return None + else: + return github.StatsPunchCard.StatsPunchCard(self._requester, headers, data) + + def get_subscribers(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /repos/{owner}/{repo}/subscribers `_ + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/subscribers", None) + + def get_tags(self) -> PaginatedList[Tag]: + """ + :calls: `GET /repos/{owner}/{repo}/tags `_ + :rtype: :class:`PaginatedList` of :class:`github.Tag.Tag` + """ + return PaginatedList(github.Tag.Tag, self._requester, f"{self.url}/tags", None) + + def get_releases(self) -> PaginatedList[GitRelease]: + """ + :calls: `GET /repos/{owner}/{repo}/releases `_ + :rtype: :class:`PaginatedList` of :class:`github.GitRelease.GitRelease` + """ + return PaginatedList(github.GitRelease.GitRelease, self._requester, f"{self.url}/releases", None) + + def get_release(self, id: int | str) -> GitRelease: + """ + :calls: `GET /repos/{owner}/{repo}/releases/{id} `_ + :param id: int (release id), str (tag name) + :rtype: None or :class:`github.GitRelease.GitRelease` + """ + assert isinstance(id, (int, str)), id + if isinstance(id, int): + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/{id}") + return github.GitRelease.GitRelease(self._requester, headers, data, completed=True) + elif isinstance(id, str): + id = urllib.parse.quote(id) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/tags/{id}") + return github.GitRelease.GitRelease(self._requester, headers, data, completed=True) + + def get_latest_release(self) -> GitRelease: + """ + :calls: `GET /repos/{owner}/{repo}/releases/latest `_ + :rtype: :class:`github.GitRelease.GitRelease` + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/latest") + return github.GitRelease.GitRelease(self._requester, headers, data, completed=True) + + def get_teams(self) -> PaginatedList[Team]: + """ + :calls: `GET /repos/{owner}/{repo}/teams `_ + :rtype: :class:`PaginatedList` of :class:`github.Team.Team` + """ + return PaginatedList(github.Team.Team, self._requester, f"{self.url}/teams", None) + + def get_topics(self) -> list[str]: + """ + :calls: `GET /repos/{owner}/{repo}/topics `_ + :rtype: list of strings + """ + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/topics", + headers={"Accept": Consts.mediaTypeTopicsPreview}, + ) + return data["names"] + + def get_watchers(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /repos/{owner}/{repo}/watchers `_ + :rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser` + """ + return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/watchers", None) + + def get_workflows(self) -> PaginatedList[Workflow]: + """ + :calls: `GET /repos/{owner}/{repo}/actions/workflows `_ + :rtype: :class:`PaginatedList` of :class:`github.Workflow.Workflow` + """ + return PaginatedList( + github.Workflow.Workflow, + self._requester, + f"{self.url}/actions/workflows", + None, + list_item="workflows", + ) + + def get_workflow(self, id_or_file_name: str | int) -> Workflow: + """ + :calls: `GET /repos/{owner}/{repo}/actions/workflows/{workflow_id} `_ + :param id_or_file_name: int or string. Can be either a workflow ID or a filename. + :rtype: :class:`github.Workflow.Workflow` + """ + assert isinstance(id_or_file_name, (int, str)), id_or_file_name + id_or_file_name = urllib.parse.quote(str(id_or_file_name)) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/workflows/{id_or_file_name}") + return github.Workflow.Workflow(self._requester, headers, data, completed=True) + + def get_workflow_runs( + self, + actor: Opt[NamedUser] = NotSet, + branch: Opt[Branch] = NotSet, + event: Opt[str] = NotSet, + status: Opt[str] = NotSet, + exclude_pull_requests: Opt[bool] = NotSet, + head_sha: Opt[str] = NotSet, + created: Opt[str] = NotSet, + check_suite_id: Opt[int] = NotSet, + ) -> PaginatedList[WorkflowRun]: + """ + :calls: `GET /repos/{owner}/{repo}/actions/runs `_ + :param actor: :class:`github.NamedUser.NamedUser` or string + :param branch: :class:`github.Branch.Branch` or string + :param event: string + :param status: string `queued`, `in_progress`, `completed`, `success`, `failure`, `neutral`, `cancelled`, `skipped`, `timed_out`, or `action_required` + :param exclude_pull_requests: bool + :param head_sha: string + :param created: string Created filter, see https://docs.github.com/en/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax#query-for-dates + :param check_suite_id: int + + :rtype: :class:`PaginatedList` of :class:`github.WorkflowRun.WorkflowRun` + """ + assert is_optional(actor, (github.NamedUser.NamedUser, str)), actor + assert is_optional(branch, (github.Branch.Branch, str)), branch + assert is_optional(event, str), event + assert is_optional(status, str), status + assert is_optional(exclude_pull_requests, bool), exclude_pull_requests + assert is_optional(head_sha, str), head_sha + assert is_optional(created, str), created + assert is_optional(check_suite_id, int), check_suite_id + + url_parameters: dict[str, Any] = {} + if is_defined(actor): + if isinstance(actor, github.NamedUser.NamedUser): + url_parameters["actor"] = actor._identity + else: + url_parameters["actor"] = actor + if is_defined(branch): + if isinstance(branch, github.Branch.Branch): + url_parameters["branch"] = branch.name + else: + url_parameters["branch"] = branch + if is_defined(event): + url_parameters["event"] = event + if is_defined(status): + url_parameters["status"] = status + if is_defined(exclude_pull_requests) and exclude_pull_requests: + url_parameters["exclude_pull_requests"] = 1 + if is_defined(head_sha): + url_parameters["head_sha"] = head_sha + if is_defined(created): + url_parameters["created"] = created + if is_defined(check_suite_id): + url_parameters["check_suite_id"] = check_suite_id + + return PaginatedList( + github.WorkflowRun.WorkflowRun, + self._requester, + f"{self.url}/actions/runs", + url_parameters, + list_item="workflow_runs", + ) + + def get_workflow_run(self, id_: int) -> WorkflowRun: + """ + :calls: `GET /repos/{owner}/{repo}/actions/runs/{run_id} `_ + :param id_: int + :rtype: :class:`github.WorkflowRun.WorkflowRun` + """ + assert isinstance(id_, int) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/runs/{id_}") + return github.WorkflowRun.WorkflowRun(self._requester, headers, data, completed=True) + + def has_in_assignees(self, assignee: str | NamedUser) -> bool: + """ + :calls: `GET /repos/{owner}/{repo}/assignees/{assignee} `_ + :param assignee: string or :class:`github.NamedUser.NamedUser` + :rtype: bool + """ + assert isinstance(assignee, github.NamedUser.NamedUser) or isinstance(assignee, str), assignee + + if isinstance(assignee, github.NamedUser.NamedUser): + assignee = assignee._identity + else: + assignee = urllib.parse.quote(assignee) + + status, headers, data = self._requester.requestJson("GET", f"{self.url}/assignees/{assignee}") + return status == 204 + + def has_in_collaborators(self, collaborator: str | NamedUser) -> bool: + """ + :calls: `GET /repos/{owner}/{repo}/collaborators/{user} `_ + :param collaborator: string or :class:`github.NamedUser.NamedUser` + :rtype: bool + """ + assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator + + if isinstance(collaborator, github.NamedUser.NamedUser): + collaborator = collaborator._identity + else: + collaborator = urllib.parse.quote(collaborator) + + status, headers, data = self._requester.requestJson("GET", f"{self.url}/collaborators/{collaborator}") + return status == 204 + + def _legacy_convert_issue(self, attributes: dict[str, Any]) -> dict[str, Any]: + convertedAttributes = { + "number": attributes["number"], + "url": f"/repos{urllib.parse.urlparse(attributes['html_url']).path}", + "user": { + "login": attributes["user"], + "url": f"/users/{attributes['user']}", + }, + } + if "labels" in attributes: # pragma no branch + convertedAttributes["labels"] = [{"name": label} for label in attributes["labels"]] + for attr in ("title", "created_at", "comments", "body", "updated_at", "state"): + if attr in attributes: # pragma no branch + convertedAttributes[attr] = attributes[attr] + return convertedAttributes + + def legacy_search_issues(self, state: str, keyword: str) -> list[Issue]: + """ + :calls: `GET /legacy/issues/search/{owner}/{repository}/{state}/{keyword} `_ + :param state: "open" or "closed" + :param keyword: string + :rtype: List of :class:`github.Issue.Issue` + """ + assert state in ["open", "closed"], state + assert isinstance(keyword, str), keyword + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"/legacy/issues/search/{self.owner.login}/{self.name}/{state}/{urllib.parse.quote(keyword)}", + ) + return [ + github.Issue.Issue( + self._requester, + headers, + self._legacy_convert_issue(element), + completed=False, + ) + for element in data["issues"] + ] + + def get_notifications( + self, + all: Opt[bool] = NotSet, + participating: Opt[bool] = NotSet, + since: Opt[datetime] = NotSet, + before: Opt[datetime] = NotSet, + ) -> PaginatedList[Notification]: + """ + :calls: `GET /repos/{owner}/{repo}/notifications `_ + :param all: bool + :param participating: bool + :param since: datetime + :param before: datetime + :rtype: :class:`PaginatedList` of :class:`github.Notification.Notification` + """ + + assert is_optional(all, bool), all + assert is_optional(participating, bool), participating + assert is_optional(since, datetime), since + assert is_optional(before, datetime), before + + params = NotSet.remove_unset_items({"all": all, "participating": participating}) + if is_defined(since): + params["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ") + if is_defined(before): + params["before"] = before.strftime("%Y-%m-%dT%H:%M:%SZ") + + return PaginatedList( + github.Notification.Notification, + self._requester, + f"{self.url}/notifications", + params, + ) + + def mark_notifications_as_read(self, last_read_at: datetime = datetime.now(timezone.utc)) -> None: + """ + :calls: `PUT /repos/{owner}/{repo}/notifications `_ + :param last_read_at: datetime + """ + assert isinstance(last_read_at, datetime) + put_parameters = {"last_read_at": last_read_at.strftime("%Y-%m-%dT%H:%M:%SZ")} + + headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/notifications", input=put_parameters) + + def merge(self, base: str, head: str, commit_message: Opt[str] = NotSet) -> Commit | None: + """ + :calls: `POST /repos/{owner}/{repo}/merges `_ + :param base: string + :param head: string + :param commit_message: string + :rtype: :class:`github.Commit.Commit` + """ + assert isinstance(base, str), base + assert isinstance(head, str), head + assert is_optional(commit_message, str), commit_message + post_parameters = { + "base": base, + "head": head, + } + if is_defined(commit_message): + post_parameters["commit_message"] = commit_message + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/merges", input=post_parameters) + if data is None: + return None + else: + return github.Commit.Commit(self._requester, headers, data, completed=True) + + def merge_upstream(self, branch: str) -> MergedUpstream: + """ + :calls: `POST /repos/{owner}/{repo}/merge-upstream `_ + :param branch: string + :rtype: :class:`github.MergedUpstream.MergedUpstream` + :raises: :class:`GithubException` for error status codes + """ + assert isinstance(branch, str), branch + post_parameters = {"branch": branch} + headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/merge-upstream", input=post_parameters) + return github.MergedUpstream.MergedUpstream(self._requester, headers, data) + + def replace_topics(self, topics: list[str]) -> None: + """ + :calls: `PUT /repos/{owner}/{repo}/topics `_ + :param topics: list of strings + :rtype: None + """ + post_parameters = {"names": topics} + headers, data = self._requester.requestJsonAndCheck( + "PUT", + f"{self.url}/topics", + headers={"Accept": Consts.mediaTypeTopicsPreview}, + input=post_parameters, + ) + + def get_vulnerability_alert(self) -> bool: + """ + :calls: `GET /repos/{owner}/{repo}/vulnerability-alerts `_ + :rtype: bool + """ + status, _, _ = self._requester.requestJson( + "GET", + f"{self.url}/vulnerability-alerts", + headers={"Accept": Consts.vulnerabilityAlertsPreview}, + ) + return status == 204 + + def enable_vulnerability_alert(self) -> bool: + """ + :calls: `PUT /repos/{owner}/{repo}/vulnerability-alerts `_ + :rtype: bool + """ + status, _, _ = self._requester.requestJson( + "PUT", + f"{self.url}/vulnerability-alerts", + headers={"Accept": Consts.vulnerabilityAlertsPreview}, + ) + return status == 204 + + def disable_vulnerability_alert(self) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/vulnerability-alerts `_ + :rtype: bool + """ + status, _, _ = self._requester.requestJson( + "DELETE", + f"{self.url}/vulnerability-alerts", + headers={"Accept": Consts.vulnerabilityAlertsPreview}, + ) + return status == 204 + + def enable_automated_security_fixes(self) -> bool: + """ + :calls: `PUT /repos/{owner}/{repo}/automated-security-fixes `_ + :rtype: bool + """ + status, _, _ = self._requester.requestJson( + "PUT", + f"{self.url}/automated-security-fixes", + headers={"Accept": Consts.automatedSecurityFixes}, + ) + return status == 204 + + def disable_automated_security_fixes(self) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/automated-security-fixes `_ + :rtype: bool + """ + status, _, _ = self._requester.requestJson( + "DELETE", + f"{self.url}/automated-security-fixes", + headers={"Accept": Consts.automatedSecurityFixes}, + ) + return status == 204 + + def remove_from_collaborators(self, collaborator: str | NamedUser) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/collaborators/{user} `_ + :param collaborator: string or :class:`github.NamedUser.NamedUser` + :rtype: None + """ + assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator + + if isinstance(collaborator, github.NamedUser.NamedUser): + collaborator = collaborator._identity + else: + collaborator = urllib.parse.quote(collaborator) + + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/collaborators/{collaborator}") + + def remove_self_hosted_runner(self, runner: SelfHostedActionsRunner | int) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/actions/runners/{runner_id} `_ + :param runner: int or :class:`github.SelfHostedActionsRunner.SelfHostedActionsRunner` + :rtype: bool + """ + assert isinstance(runner, github.SelfHostedActionsRunner.SelfHostedActionsRunner) or isinstance( + runner, int + ), runner + + if isinstance(runner, github.SelfHostedActionsRunner.SelfHostedActionsRunner): + runner = runner.id + + status, _, _ = self._requester.requestJson("DELETE", f"{self.url}/actions/runners/{runner}") + return status == 204 + + def remove_autolink(self, autolink: Autolink | int) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/autolinks/{id} `_ + :param autolink: int or :class:`github.Autolink.Autolink` + :rtype: None + """ + is_autolink = isinstance(autolink, github.Autolink.Autolink) + assert is_autolink or isinstance(autolink, int), autolink + + status, _, _ = self._requester.requestJson( + "DELETE", f"{self.url}/autolinks/{autolink.id if is_autolink else autolink}" # type: ignore + ) + return status == 204 + + def subscribe_to_hub(self, event: str, callback: str, secret: Opt[str] = NotSet) -> None: + """ + :calls: `POST /hub `_ + :param event: string + :param callback: string + :param secret: string + :rtype: None + """ + return self._hub("subscribe", event, callback, secret) + + def unsubscribe_from_hub(self, event: str, callback: str) -> None: + """ + :calls: `POST /hub `_ + :param event: string + :param callback: string + :param secret: string + :rtype: None + """ + return self._hub("unsubscribe", event, callback, NotSet) + + def create_check_suite(self, head_sha: str) -> CheckSuite: + """ + :calls: `POST /repos/{owner}/{repo}/check-suites `_ + :param head_sha: string + :rtype: :class:`github.CheckSuite.CheckSuite` + """ + assert isinstance(head_sha, str), head_sha + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/check-suites", + input={"head_sha": head_sha}, + ) + return github.CheckSuite.CheckSuite(self._requester, headers, data, completed=True) + + def get_check_suite(self, check_suite_id: int) -> CheckSuite: + """ + :calls: `GET /repos/{owner}/{repo}/check-suites/{check_suite_id} `_ + :param check_suite_id: int + :rtype: :class:`github.CheckSuite.CheckSuite` + """ + assert isinstance(check_suite_id, int), check_suite_id + requestHeaders = {"Accept": "application/vnd.github.v3+json"} + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/check-suites/{check_suite_id}", + headers=requestHeaders, + ) + return github.CheckSuite.CheckSuite(self._requester, headers, data) + + def update_check_suites_preferences( + self, auto_trigger_checks: list[dict[str, bool | int]] + ) -> RepositoryPreferences: + """ + :calls: `PATCH /repos/{owner}/{repo}/check-suites/preferences `_ + :param auto_trigger_checks: list of dict + :rtype: :class:`github.RepositoryPreferences.RepositoryPreferences` + """ + assert all(isinstance(element, dict) for element in auto_trigger_checks), auto_trigger_checks + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + f"{self.url}/check-suites/preferences", + input={"auto_trigger_checks": auto_trigger_checks}, + ) + return github.RepositoryPreferences.RepositoryPreferences(self._requester, headers, data) + + def _hub(self, mode: str, event: str, callback: str, secret: Opt[str]) -> None: + assert isinstance(mode, str), mode + assert isinstance(event, str), event + assert isinstance(callback, str), callback + assert is_optional(secret, str), secret + event = urllib.parse.quote(event) + + post_parameters = collections.OrderedDict() + post_parameters["hub.callback"] = callback + post_parameters["hub.topic"] = f"https://github.com/{self.full_name}/events/{event}" + post_parameters["hub.mode"] = mode + if is_defined(secret): + post_parameters["hub.secret"] = secret + + headers, output = self._requester.requestMultipartAndCheck("POST", "/hub", input=post_parameters) + + def get_release_asset(self, id: int) -> GitReleaseAsset: + assert isinstance(id, (int)), id + resp_headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/assets/{id}") + return github.GitReleaseAsset.GitReleaseAsset(self._requester, resp_headers, data, completed=True) + + def create_check_run( + self, + name: str, + head_sha: str, + details_url: Opt[str] = NotSet, + external_id: Opt[str] = NotSet, + status: Opt[str] = NotSet, + started_at: Opt[datetime] = NotSet, + conclusion: Opt[str] = NotSet, + completed_at: Opt[datetime] = NotSet, + output: Opt[dict[str, str | list[dict[str, str | int]]]] = NotSet, + actions: Opt[list[dict[str, str]]] = NotSet, + ) -> CheckRun: + """ + :calls: `POST /repos/{owner}/{repo}/check-runs `_ + :param name: string + :param head_sha: string + :param details_url: string + :param external_id: string + :param status: string + :param started_at: datetime + :param conclusion: string + :param completed_at: datetime + :param output: dict + :param actions: list of dict + :rtype: :class:`github.CheckRun.CheckRun` + """ + assert isinstance(name, str), name + assert isinstance(head_sha, str), head_sha + assert is_optional(details_url, str), details_url + assert is_optional(external_id, str), external_id + assert is_optional(status, str), status + assert is_optional(started_at, datetime), started_at + assert is_optional(conclusion, str), conclusion + assert is_optional(completed_at, datetime), completed_at + assert is_optional(output, dict), output + assert is_optional_list(actions, dict), actions + + post_parameters = NotSet.remove_unset_items( + { + "name": name, + "head_sha": head_sha, + "details_url": details_url, + "external_id": external_id, + "status": status, + "conclusion": conclusion, + "output": output, + "actions": actions, + } + ) + + if is_defined(started_at): + post_parameters["started_at"] = started_at.strftime("%Y-%m-%dT%H:%M:%SZ") + if is_defined(completed_at): + post_parameters["completed_at"] = completed_at.strftime("%Y-%m-%dT%H:%M:%SZ") + + headers, data = self._requester.requestJsonAndCheck( + "POST", + f"{self.url}/check-runs", + input=post_parameters, + ) + return github.CheckRun.CheckRun(self._requester, headers, data, completed=True) + + def get_check_run(self, check_run_id: int) -> CheckRun: + """ + :calls: `GET /repos/{owner}/{repo}/check-runs/{check_run_id} `_ + :param check_run_id: int + :rtype: :class:`github.CheckRun.CheckRun` + """ + assert isinstance(check_run_id, int), check_run_id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/check-runs/{check_run_id}") + return github.CheckRun.CheckRun(self._requester, headers, data, completed=True) + + def get_artifacts(self, name: Opt[str] = NotSet) -> PaginatedList[Artifact]: + """ + :calls: `GET /repos/{owner}/{repo}/actions/artifacts `_ + :param name: str + :rtype: :class:`PaginatedList` of :class:`github.Artifact.Artifact` + """ + + assert is_optional(name, str), name + + param = {key: value for key, value in {"name": name}.items() if is_defined(value)} + + return PaginatedList( + github.Artifact.Artifact, + self._requester, + f"{self.url}/actions/artifacts", + firstParams=param, + list_item="artifacts", + ) + + def get_artifact(self, artifact_id: int) -> Artifact: + """ + :calls: `GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id} `_ + :param artifact_id: int + :rtype: :class:`github.Artifact.Artifact` + """ + assert isinstance(artifact_id, int), artifact_id + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/artifacts/{artifact_id}") + return github.Artifact.Artifact(self._requester, headers, data) + + def get_codescan_alerts(self) -> PaginatedList[CodeScanAlert]: + """ + :calls: `GET https://api.github.com/repos/{owner}/{repo}/code-scanning/alerts `_ + :rtype: :class:`PaginatedList` of :class:`github.CodeScanAlert.CodeScanAlert` + """ + return PaginatedList( + github.CodeScanAlert.CodeScanAlert, + self._requester, + f"{self.url}/code-scanning/alerts", + None, + ) + + def get_environments(self) -> PaginatedList[Environment]: + """ + :calls: `GET /repositories/{self._repository.id}/environments/{self.environment_name}/environments `_ + :rtype: :class:`PaginatedList` of :class:`github.Environment.Environment` + """ + return PaginatedList( + Environment, + self._requester, + f"{self.url}/environments", + None, + attributesTransformer=PaginatedList.override_attributes( + {"environments_url": f"/repositories/{self.id}/environments"} + ), + list_item="environments", + ) + + def get_environment(self, environment_name: str) -> Environment: + """ + :calls: `GET /repositories/{self._repository.id}/environments/{self.environment_name}/environments/{environment_name} `_ + :rtype: :class:`github.Environment.Environment` + """ + assert isinstance(environment_name, str), environment_name + environment_name = urllib.parse.quote(environment_name) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/environments/{environment_name}") + data["environments_url"] = f"/repositories/{self.id}/environments" + return Environment(self._requester, headers, data, completed=True) + + def create_environment( + self, + environment_name: str, + wait_timer: int = 0, + reviewers: list[ReviewerParams] = [], + deployment_branch_policy: EnvironmentDeploymentBranchPolicyParams | None = None, + ) -> Environment: + """ + :calls: `PUT /repositories/{self._repository.id}/environments/{self.environment_name}/environments/{environment_name} `_ + :param environment_name: string + :param wait_timer: int + :param reviews: List[:class:github.EnvironmentDeploymentBranchPolicy.EnvironmentDeploymentBranchPolicyParams] + :param deployment_branch_policy: Optional[:class:github.EnvironmentDeploymentBranchPolicy.EnvironmentDeploymentBranchPolicyParams`] + :rtype: :class:`github.Environment.Environment` + """ + assert isinstance(environment_name, str), environment_name + assert isinstance(wait_timer, int) + assert isinstance(reviewers, list) + assert all( + [isinstance(reviewer, github.EnvironmentProtectionRuleReviewer.ReviewerParams) for reviewer in reviewers] + ) + assert ( + isinstance( + deployment_branch_policy, + github.EnvironmentDeploymentBranchPolicy.EnvironmentDeploymentBranchPolicyParams, + ) + or deployment_branch_policy is None + ) + environment_name = urllib.parse.quote(environment_name) + + put_parameters = { + "wait_timer": wait_timer, + "reviewers": [reviewer._asdict() for reviewer in reviewers], + "deployment_branch_policy": deployment_branch_policy._asdict() if deployment_branch_policy else None, + } + + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/environments/{environment_name}", input=put_parameters + ) + data["environments_url"] = f"/repositories/{self.id}/environments" + return Environment(self._requester, headers, data, completed=True) + + def delete_environment(self, environment_name: str) -> None: + """ + :calls: `DELETE /repositories/{self._repository.id}/environments/{self.environment_name}/environments/{environment_name} `_ + :param environment_name: string + :rtype: None + """ + assert isinstance(environment_name, str), environment_name + environment_name = urllib.parse.quote(environment_name) + + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/environments/{environment_name}") + + def get_dependabot_alerts( + self, + state: Opt[str] = NotSet, + severity: Opt[str] = NotSet, + ecosystem: Opt[str] = NotSet, + package: Opt[str] = NotSet, + manifest: Opt[str] = NotSet, + scope: Opt[str] = NotSet, + sort: Opt[str] = NotSet, + direction: Opt[str] = NotSet, + ) -> PaginatedList[DependabotAlert]: + """ + :calls: `GET /repos/{owner}/{repo}/dependabot/alerts `_ + :param state: Optional string + :param severity: Optional string + :param ecosystem: Optional string + :param package: Optional string + :param manifest: Optional string + :param scope: Optional string + :param sort: Optional string + :param direction: Optional string + :rtype: :class:`PaginatedList` of :class:`github.DependabotAlert.DependabotAlert` + """ + allowed_states = ["auto_dismissed", "dismissed", "fixed", "open"] + allowed_severities = ["low", "medium", "high", "critical"] + allowed_ecosystems = ["composer", "go", "maven", "npm", "nuget", "pip", "pub", "rubygems", "rust"] + allowed_scopes = ["development", "runtime"] + allowed_sorts = ["created", "updated"] + allowed_directions = ["asc", "desc"] + assert state in allowed_states + [NotSet], f"State can be one of {', '.join(allowed_states)}" + assert severity in allowed_severities + [NotSet], f"Severity can be one of {', '.join(allowed_severities)}" + assert ecosystem in allowed_ecosystems + [NotSet], f"Ecosystem can be one of {', '.join(allowed_ecosystems)}" + assert scope in allowed_scopes + [NotSet], f"Scope can be one of {', '.join(allowed_scopes)}" + assert sort in allowed_sorts + [NotSet], f"Sort can be one of {', '.join(allowed_sorts)}" + assert direction in allowed_directions + [NotSet], f"Direction can be one of {', '.join(allowed_directions)}" + url_parameters = NotSet.remove_unset_items( + { + "state": state, + "severity": severity, + "ecosystem": ecosystem, + "package": package, + "manifest": manifest, + "scope": scope, + "sort": sort, + "direction": direction, + } + ) + return PaginatedList( + github.DependabotAlert.DependabotAlert, + self._requester, + f"{self.url}/dependabot/alerts", + url_parameters, + ) + + def get_dependabot_alert(self, number: int) -> DependabotAlert: + """ + :calls: `GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number} `_ + :param number: int + :rtype: :class:`github.DependabotAlert.DependabotAlert` + """ + assert isinstance(number, int), number + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/dependabot/alerts/{number}") + return github.DependabotAlert.DependabotAlert(self._requester, headers, data) + + def update_dependabot_alert( + self, number: int, state: str, dismissed_reason: Opt[str] = NotSet, dismissed_comment: Opt[str] = NotSet + ) -> DependabotAlert: + """ + :calls: `PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number} `_ + :param number: int + :param state: string + :param dismissed_reason: Optional string + :param dismissed_comment: Optional string + :rtype: :class:`github.DependabotAlert.DependabotAlert` + """ + assert isinstance(number, int), number + assert isinstance(state, str), state + assert state in ["dismissed", "open"], "State can be one of ['dismissed', 'open']" + if state == "dismissed": + assert is_defined(dismissed_reason) + assert dismissed_reason in [ + "fix_started", + "inaccurate", + "no_bandwidth", + "not_used", + "tolerable_risk", + ], "Dismissed reason can be one of ['fix_started', 'inaccurate', 'no_bandwidth', 'not_used', 'tolerable_risk']" + assert is_optional(dismissed_comment, str), dismissed_comment + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + f"{self.url}/dependabot/alerts/{number}", + input=NotSet.remove_unset_items( + {"state": state, "dismissed_reason": dismissed_reason, "dismissed_comment": dismissed_comment} + ), + ) + return github.DependabotAlert.DependabotAlert(self._requester, headers, data) + + def get_custom_properties(self) -> dict[str, None | str | list]: + """ + :calls: `GET /repos/{owner}/{repo}/properties/values `_ + :rtype: dict[str, None | str | list] + """ + url = f"{self.url}/properties/values" + _, data = self._requester.requestJsonAndCheck("GET", url) + custom_properties = {p["property_name"]: p["value"] for p in data} + self._custom_properties = self._makeDictAttribute(custom_properties) + return custom_properties + + def update_custom_properties(self, properties: dict[str, None | str | list]) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/properties/values `_ + :rtype: None + """ + assert all(isinstance(v, (type(None), str, list)) for v in properties.values()), properties + url = f"{self.url}/properties/values" + patch_parameters: dict[str, list] = { + "properties": [{"property_name": k, "value": v} for k, v in properties.items()] + } + self._requester.requestJsonAndCheck("PATCH", url, input=patch_parameters) + + def attach_security_config(self, id: int) -> None: + """ + :calls: `POST /orgs/{org}/code-security/configurations/{configuration_id}/attach `_ + """ + self.organization.attach_security_config_to_repositories( + id=id, scope="selected", selected_repository_ids=[self.id] + ) + + def detach_security_config(self) -> None: + """ + :calls: `DELETE /orgs/{org}/code-security/configurations/detach `_ + """ + self.organization.detach_security_config_from_repositories(selected_repository_ids=[self.id]) + + def get_security_config(self) -> RepoCodeSecurityConfig | None: + """ + :calls: `GET /repos/{owner}/{repo}/code-security-configuration `_ + :rtype: RepoCodeSecurityConfig | None + """ + #### TODO(napier): this is actually a special type not CodeSecurityConfig + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/code-security-configuration") + if data is None: + return None + return github.RepoCodeSecurityConfig.RepoCodeSecurityConfig(self._requester, headers, data) + + def transfer_ownership(self, new_owner: str, new_name: Opt[str] = NotSet, teams: Opt[list[int]] = NotSet) -> bool: + """ + :calls: `POST /repos/{owner}/{repo}/transfer `_ + :param new_owner: string + :param new_name: Optional string + :param teams: Optional list of int + :rtype: bool + """ + assert isinstance(new_owner, str), new_owner + assert is_optional(new_name, str), new_name + assert is_optional_list(teams, int), teams + + post_parameters = NotSet.remove_unset_items({"new_owner": new_owner, "new_name": new_name, "team_ids": teams}) + + _, _ = self._requester.requestJsonAndCheck("POST", f"{self.url}/transfer", input=post_parameters) + + return True + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "allow_auto_merge" in attributes: # pragma no branch + self._allow_auto_merge = self._makeBoolAttribute(attributes["allow_auto_merge"]) + if "allow_forking" in attributes: # pragma no branch + self._allow_forking = self._makeBoolAttribute(attributes["allow_forking"]) + if "allow_merge_commit" in attributes: # pragma no branch + self._allow_merge_commit = self._makeBoolAttribute(attributes["allow_merge_commit"]) + if "allow_rebase_merge" in attributes: # pragma no branch + self._allow_rebase_merge = self._makeBoolAttribute(attributes["allow_rebase_merge"]) + if "allow_squash_merge" in attributes: # pragma no branch + self._allow_squash_merge = self._makeBoolAttribute(attributes["allow_squash_merge"]) + if "allow_update_branch" in attributes: # pragma no branch + self._allow_update_branch = self._makeBoolAttribute(attributes["allow_update_branch"]) + if "anonymous_access_enabled" in attributes: # pragma no branch + self._anonymous_access_enabled = self._makeBoolAttribute(attributes["anonymous_access_enabled"]) + if "archive_url" in attributes: # pragma no branch + self._archive_url = self._makeStringAttribute(attributes["archive_url"]) + if "archived" in attributes: # pragma no branch + self._archived = self._makeBoolAttribute(attributes["archived"]) + if "assignees_url" in attributes: # pragma no branch + self._assignees_url = self._makeStringAttribute(attributes["assignees_url"]) + if "blobs_url" in attributes: # pragma no branch + self._blobs_url = self._makeStringAttribute(attributes["blobs_url"]) + if "branches_url" in attributes: # pragma no branch + self._branches_url = self._makeStringAttribute(attributes["branches_url"]) + if "clone_url" in attributes: # pragma no branch + self._clone_url = self._makeStringAttribute(attributes["clone_url"]) + if "code_of_conduct" in attributes: # pragma no branch + self._code_of_conduct = self._makeDictAttribute(attributes["code_of_conduct"]) + if "collaborators_url" in attributes: # pragma no branch + self._collaborators_url = self._makeStringAttribute(attributes["collaborators_url"]) + if "comments_url" in attributes: # pragma no branch + self._comments_url = self._makeStringAttribute(attributes["comments_url"]) + if "commits_url" in attributes: # pragma no branch + self._commits_url = self._makeStringAttribute(attributes["commits_url"]) + if "compare_url" in attributes: # pragma no branch + self._compare_url = self._makeStringAttribute(attributes["compare_url"]) + if "contents_url" in attributes: # pragma no branch + self._contents_url = self._makeStringAttribute(attributes["contents_url"]) + if "contributors_url" in attributes: # pragma no branch + self._contributors_url = self._makeStringAttribute(attributes["contributors_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "custom_properties" in attributes: # pragma no branch + self._custom_properties = self._makeDictAttribute(attributes["custom_properties"]) + if "default_branch" in attributes: # pragma no branch + self._default_branch = self._makeStringAttribute(attributes["default_branch"]) + if "delete_branch_on_merge" in attributes: # pragma no branch + self._delete_branch_on_merge = self._makeBoolAttribute(attributes["delete_branch_on_merge"]) + if "deployments_url" in attributes: # pragma no branch + self._deployments_url = self._makeStringAttribute(attributes["deployments_url"]) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "disabled" in attributes: # pragma no branch + self._disabled = self._makeBoolAttribute(attributes["disabled"]) + if "downloads_url" in attributes: # pragma no branch + self._downloads_url = self._makeStringAttribute(attributes["downloads_url"]) + if "events_url" in attributes: # pragma no branch + self._events_url = self._makeStringAttribute(attributes["events_url"]) + if "fork" in attributes: # pragma no branch + self._fork = self._makeBoolAttribute(attributes["fork"]) + if "forks" in attributes: # pragma no branch + self._forks = self._makeIntAttribute(attributes["forks"]) + if "forks_count" in attributes: # pragma no branch + self._forks_count = self._makeIntAttribute(attributes["forks_count"]) + if "forks_url" in attributes: # pragma no branch + self._forks_url = self._makeStringAttribute(attributes["forks_url"]) + if "full_name" in attributes: # pragma no branch + self._full_name = self._makeStringAttribute(attributes["full_name"]) + if "git_commits_url" in attributes: # pragma no branch + self._git_commits_url = self._makeStringAttribute(attributes["git_commits_url"]) + if "git_refs_url" in attributes: # pragma no branch + self._git_refs_url = self._makeStringAttribute(attributes["git_refs_url"]) + if "git_tags_url" in attributes: # pragma no branch + self._git_tags_url = self._makeStringAttribute(attributes["git_tags_url"]) + if "git_url" in attributes: # pragma no branch + self._git_url = self._makeStringAttribute(attributes["git_url"]) + if "has_discussions" in attributes: # pragma no branch + self._has_discussions = self._makeBoolAttribute(attributes["has_discussions"]) + if "has_downloads" in attributes: # pragma no branch + self._has_downloads = self._makeBoolAttribute(attributes["has_downloads"]) + if "has_issues" in attributes: # pragma no branch + self._has_issues = self._makeBoolAttribute(attributes["has_issues"]) + if "has_pages" in attributes: # pragma no branch + self._has_pages = self._makeBoolAttribute(attributes["has_pages"]) + if "has_projects" in attributes: # pragma no branch + self._has_projects = self._makeBoolAttribute(attributes["has_projects"]) + if "has_wiki" in attributes: # pragma no branch + self._has_wiki = self._makeBoolAttribute(attributes["has_wiki"]) + if "homepage" in attributes: # pragma no branch + self._homepage = self._makeStringAttribute(attributes["homepage"]) + if "hooks_url" in attributes: # pragma no branch + self._hooks_url = self._makeStringAttribute(attributes["hooks_url"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "is_template" in attributes: # pragma no branch + self._is_template = self._makeBoolAttribute(attributes["is_template"]) + if "issue_comment_url" in attributes: # pragma no branch + self._issue_comment_url = self._makeStringAttribute(attributes["issue_comment_url"]) + if "issue_events_url" in attributes: # pragma no branch + self._issue_events_url = self._makeStringAttribute(attributes["issue_events_url"]) + if "issues_url" in attributes: # pragma no branch + self._issues_url = self._makeStringAttribute(attributes["issues_url"]) + if "keys_url" in attributes: # pragma no branch + self._keys_url = self._makeStringAttribute(attributes["keys_url"]) + if "labels_url" in attributes: # pragma no branch + self._labels_url = self._makeStringAttribute(attributes["labels_url"]) + if "language" in attributes: # pragma no branch + self._language = self._makeStringAttribute(attributes["language"]) + if "languages_url" in attributes: # pragma no branch + self._languages_url = self._makeStringAttribute(attributes["languages_url"]) + if "license" in attributes: # pragma no branch + self._license = self._makeClassAttribute(github.License.License, attributes["license"]) + if "master_branch" in attributes: # pragma no branch + self._master_branch = self._makeStringAttribute(attributes["master_branch"]) + if "merge_commit_message" in attributes: # pragma no branch + self._merge_commit_message = self._makeStringAttribute(attributes["merge_commit_message"]) + if "merge_commit_title" in attributes: # pragma no branch + self._merge_commit_title = self._makeStringAttribute(attributes["merge_commit_title"]) + if "merges_url" in attributes: # pragma no branch + self._merges_url = self._makeStringAttribute(attributes["merges_url"]) + if "milestones_url" in attributes: # pragma no branch + self._milestones_url = self._makeStringAttribute(attributes["milestones_url"]) + if "mirror_url" in attributes: # pragma no branch + self._mirror_url = self._makeStringAttribute(attributes["mirror_url"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "network_count" in attributes: # pragma no branch + self._network_count = self._makeIntAttribute(attributes["network_count"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "notifications_url" in attributes: # pragma no branch + self._notifications_url = self._makeStringAttribute(attributes["notifications_url"]) + if "open_issues" in attributes: # pragma no branch + self._open_issues = self._makeIntAttribute(attributes["open_issues"]) + if "open_issues_count" in attributes: # pragma no branch + self._open_issues_count = self._makeIntAttribute(attributes["open_issues_count"]) + if "organization" in attributes: # pragma no branch + self._organization = self._makeClassAttribute(github.Organization.Organization, attributes["organization"]) + if "owner" in attributes: # pragma no branch + self._owner = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["owner"]) + if "parent" in attributes: # pragma no branch + self._parent = self._makeClassAttribute(Repository, attributes["parent"]) + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeClassAttribute(github.Permissions.Permissions, attributes["permissions"]) + if "private" in attributes: # pragma no branch + self._private = self._makeBoolAttribute(attributes["private"]) + if "pulls_url" in attributes: # pragma no branch + self._pulls_url = self._makeStringAttribute(attributes["pulls_url"]) + if "pushed_at" in attributes: # pragma no branch + self._pushed_at = self._makeDatetimeAttribute(attributes["pushed_at"]) + if "releases_url" in attributes: # pragma no branch + self._releases_url = self._makeStringAttribute(attributes["releases_url"]) + if "role_name" in attributes: # pragma no branch + self._role_name = self._makeStringAttribute(attributes["role_name"]) + if "security_and_analysis" in attributes: # pragma no branch + self._security_and_analysis = self._makeClassAttribute( + github.SecurityAndAnalysis.SecurityAndAnalysis, attributes["security_and_analysis"] + ) + if "size" in attributes: # pragma no branch + self._size = self._makeIntAttribute(attributes["size"]) + if "source" in attributes: # pragma no branch + self._source = self._makeClassAttribute(Repository, attributes["source"]) + if "squash_merge_commit_message" in attributes: # pragma no branch + self._squash_merge_commit_message = self._makeStringAttribute(attributes["squash_merge_commit_message"]) + if "squash_merge_commit_title" in attributes: # pragma no branch + self._squash_merge_commit_title = self._makeStringAttribute(attributes["squash_merge_commit_title"]) + if "ssh_url" in attributes: # pragma no branch + self._ssh_url = self._makeStringAttribute(attributes["ssh_url"]) + if "stargazers_count" in attributes: # pragma no branch + self._stargazers_count = self._makeIntAttribute(attributes["stargazers_count"]) + if "stargazers_url" in attributes: # pragma no branch + self._stargazers_url = self._makeStringAttribute(attributes["stargazers_url"]) + if "starred_at" in attributes: # pragma no branch + self._starred_at = self._makeStringAttribute(attributes["starred_at"]) + if "statuses_url" in attributes: # pragma no branch + self._statuses_url = self._makeStringAttribute(attributes["statuses_url"]) + if "subscribers_count" in attributes: # pragma no branch + self._subscribers_count = self._makeIntAttribute(attributes["subscribers_count"]) + if "subscribers_url" in attributes: # pragma no branch + self._subscribers_url = self._makeStringAttribute(attributes["subscribers_url"]) + if "subscription_url" in attributes: # pragma no branch + self._subscription_url = self._makeStringAttribute(attributes["subscription_url"]) + if "svn_url" in attributes: # pragma no branch + self._svn_url = self._makeStringAttribute(attributes["svn_url"]) + if "tags_url" in attributes: # pragma no branch + self._tags_url = self._makeStringAttribute(attributes["tags_url"]) + if "teams_url" in attributes: # pragma no branch + self._teams_url = self._makeStringAttribute(attributes["teams_url"]) + if "temp_clone_token" in attributes: # pragma no branch + self._temp_clone_token = self._makeStringAttribute(attributes["temp_clone_token"]) + if "template_repository" in attributes: # pragma no branch + self._template_repository = self._makeClassAttribute( + github.Repository.Repository, attributes["template_repository"] + ) + if "topics" in attributes: # pragma no branch + self._topics = self._makeListOfStringsAttribute(attributes["topics"]) + if "trees_url" in attributes: # pragma no branch + self._trees_url = self._makeStringAttribute(attributes["trees_url"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "use_squash_pr_title_as_default" in attributes: # pragma no branch + self._use_squash_pr_title_as_default = self._makeBoolAttribute(attributes["use_squash_pr_title_as_default"]) + if "visibility" in attributes: # pragma no branch + self._visibility = self._makeStringAttribute(attributes["visibility"]) + if "watchers" in attributes: # pragma no branch + self._watchers = self._makeIntAttribute(attributes["watchers"]) + if "watchers_count" in attributes: # pragma no branch + self._watchers_count = self._makeIntAttribute(attributes["watchers_count"]) + if "web_commit_signoff_required" in attributes: # pragma no branch + self._web_commit_signoff_required = self._makeBoolAttribute(attributes["web_commit_signoff_required"]) diff --git a/python_embeded/Lib/site-packages/github/RepositoryAdvisory.py b/python_embeded/Lib/site-packages/github/RepositoryAdvisory.py new file mode 100644 index 0000000000000000000000000000000000000000..4b98e3753b7dba5dc2515137f4d43af4f5f0f84d --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RepositoryAdvisory.py @@ -0,0 +1,424 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Jonathan Leitschuh # +# Copyright 2023 Joseph Henrich # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Thomas Cooper # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any, Iterable + +import github.AdvisoryCredit +import github.AdvisoryCreditDetailed +import github.AdvisoryVulnerability +import github.NamedUser +import github.Repository +import github.Team +from github.AdvisoryBase import AdvisoryBase +from github.GithubObject import Attribute, NotSet, Opt + +if TYPE_CHECKING: + from github.AdvisoryCredit import AdvisoryCredit, Credit + from github.AdvisoryCreditDetailed import AdvisoryCreditDetailed + from github.AdvisoryVulnerability import AdvisoryVulnerability, AdvisoryVulnerabilityInput + from github.NamedUser import NamedUser + from github.Repository import Repository + from github.Team import Team + + +class RepositoryAdvisory(AdvisoryBase): + """ + This class represents a RepositoryAdvisory. + + The reference can be found here + https://docs.github.com/en/rest/security-advisories/repository-advisories + + The OpenAPI schema can be found at + - /components/schemas/repository-advisory + + """ + + def _initAttributes(self) -> None: + super()._initAttributes() + self._author: Attribute[NamedUser] = NotSet + self._closed_at: Attribute[datetime] = NotSet + self._collaborating_teams: Attribute[list[Team]] = NotSet + self._collaborating_users: Attribute[list[NamedUser]] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._credits: Attribute[list[AdvisoryCredit]] = NotSet + self._credits_detailed: Attribute[list[AdvisoryCreditDetailed]] = NotSet + self._cwe_ids: Attribute[list[str]] = NotSet + self._private_fork: Attribute[Repository] = NotSet + self._publisher: Attribute[NamedUser] = NotSet + self._state: Attribute[str] = NotSet + self._submission: Attribute[dict[str, Any]] = NotSet + self._vulnerabilities: Attribute[list[AdvisoryVulnerability]] = NotSet + super()._initAttributes() + + @property + def author(self) -> NamedUser: + return self._author.value + + @property + def closed_at(self) -> datetime: + return self._closed_at.value + + @property + def collaborating_teams(self) -> list[Team]: + return self._collaborating_teams.value + + @property + def collaborating_users(self) -> list[NamedUser]: + return self._collaborating_users.value + + @property + def created_at(self) -> datetime: + return self._created_at.value + + @property + def credits( + self, + ) -> list[AdvisoryCredit]: + return self._credits.value + + @property + def credits_detailed( + self, + ) -> list[AdvisoryCreditDetailed]: + return self._credits_detailed.value + + @property + def cwe_ids(self) -> list[str]: + return self._cwe_ids.value + + @property + def private_fork(self) -> Repository: + return self._private_fork.value + + @property + def publisher(self) -> NamedUser: + return self._publisher.value + + @property + def state(self) -> str: + return self._state.value + + @property + def submission(self) -> dict[str, Any]: + return self._submission.value + + @property + def vulnerabilities(self) -> list[AdvisoryVulnerability]: + return self._vulnerabilities.value + + def add_vulnerability( + self, + ecosystem: str, + package_name: str | None = None, + vulnerable_version_range: str | None = None, + patched_versions: str | None = None, + vulnerable_functions: list[str] | None = None, + ) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id `\ + """ + return self.add_vulnerabilities( + [ + { + "package": { + "ecosystem": ecosystem, + "name": package_name, + }, + "vulnerable_version_range": vulnerable_version_range, + "patched_versions": patched_versions, + "vulnerable_functions": vulnerable_functions, + } + ] + ) + + def add_vulnerabilities(self, vulnerabilities: Iterable[AdvisoryVulnerabilityInput]) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id ` + """ + assert isinstance(vulnerabilities, Iterable), vulnerabilities + for vulnerability in vulnerabilities: + github.AdvisoryVulnerability.AdvisoryVulnerability._validate_vulnerability(vulnerability) + + post_parameters = { + "vulnerabilities": [ + github.AdvisoryVulnerability.AdvisoryVulnerability._to_github_dict(vulnerability) + for vulnerability in (self.vulnerabilities + list(vulnerabilities)) + ] + } + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=post_parameters, + ) + self._useAttributes(data) + + def offer_credit( + self, + login_or_user: str | github.NamedUser.NamedUser, + credit_type: str, + ) -> None: + """ + Offers credit to a user for a vulnerability in a repository. + + Unless you are giving credit to yourself, the user having credit offered will need to explicitly accept the credit. + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id ` + + """ + self.offer_credits([{"login": login_or_user, "type": credit_type}]) + + def offer_credits( + self, + credited: Iterable[Credit], + ) -> None: + """ + Offers credit to a list of users for a vulnerability in a repository. + + Unless you are giving credit to yourself, the user having credit offered will need to explicitly accept the credit. + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id ` + :param credited: iterable of dict with keys "login" and "type" + + """ + assert isinstance(credited, Iterable), credited + for credit in credited: + github.AdvisoryCredit.AdvisoryCredit._validate_credit(credit) + + patch_parameters = { + "credits": [ + github.AdvisoryCredit.AdvisoryCredit._to_github_dict(credit) + for credit in (self.credits + list(credited)) + ] + } + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + ) + self._useAttributes(data) + + def revoke_credit(self, login_or_user: str | github.NamedUser.NamedUser) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id `_ + """ + assert isinstance(login_or_user, (str, github.NamedUser.NamedUser)), login_or_user + if isinstance(login_or_user, github.NamedUser.NamedUser): + login_or_user = login_or_user.login + patch_parameters = { + "credits": [ + dict(login=credit.login, type=credit.type) for credit in self.credits if credit.login != login_or_user + ] + } + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + ) + self._useAttributes(data) + + def clear_credits(self) -> None: + """ + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id `_ + """ + patch_parameters: dict[str, Any] = {"credits": []} + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + ) + self._useAttributes(data) + + def edit( + self, + summary: Opt[str] = NotSet, + description: Opt[str] = NotSet, + severity_or_cvss_vector_string: Opt[str] = NotSet, + cve_id: Opt[str] = NotSet, + vulnerabilities: Opt[Iterable[AdvisoryVulnerabilityInput]] = NotSet, + cwe_ids: Opt[Iterable[str]] = NotSet, + credits: Opt[Iterable[Credit]] = NotSet, + state: Opt[str] = NotSet, + ) -> RepositoryAdvisory: + """ + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id `_ + """ + assert summary is NotSet or isinstance(summary, str), summary + assert description is NotSet or isinstance(description, str), description + assert severity_or_cvss_vector_string is NotSet or isinstance( + severity_or_cvss_vector_string, str + ), severity_or_cvss_vector_string + assert cve_id is NotSet or isinstance(cve_id, str), cve_id + assert vulnerabilities is NotSet or isinstance(vulnerabilities, Iterable), vulnerabilities + if isinstance(vulnerabilities, Iterable): + for vulnerability in vulnerabilities: + github.AdvisoryVulnerability.AdvisoryVulnerability._validate_vulnerability(vulnerability) + assert cwe_ids is NotSet or ( + isinstance(cwe_ids, Iterable) and all(isinstance(element, str) for element in cwe_ids) + ), cwe_ids + if isinstance(credits, Iterable): + for credit in credits: + github.AdvisoryCredit.AdvisoryCredit._validate_credit(credit) + assert state is NotSet or isinstance(state, str), state + patch_parameters: dict[str, Any] = {} + if summary is not NotSet: + patch_parameters["summary"] = summary + if description is not NotSet: + patch_parameters["description"] = description + if isinstance(severity_or_cvss_vector_string, str): + if severity_or_cvss_vector_string.startswith("CVSS:"): + patch_parameters["cvss_vector_string"] = severity_or_cvss_vector_string + else: + patch_parameters["severity"] = severity_or_cvss_vector_string + if cve_id is not NotSet: + patch_parameters["cve_id"] = cve_id + if isinstance(vulnerabilities, Iterable): + patch_parameters["vulnerabilities"] = [ + github.AdvisoryVulnerability.AdvisoryVulnerability._to_github_dict(vulnerability) + for vulnerability in vulnerabilities + ] + if isinstance(cwe_ids, Iterable): + patch_parameters["cwe_ids"] = list(cwe_ids) + if isinstance(credits, Iterable): + patch_parameters["credits"] = [ + github.AdvisoryCredit.AdvisoryCredit._to_github_dict(credit) for credit in credits + ] + if state is not NotSet: + patch_parameters["state"] = state + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + ) + self._useAttributes(data) + return self + + def accept_report(self) -> None: + """ + Accepts the advisory reported from an external reporter via private vulnerability reporting. + + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id ` + + """ + patch_parameters = {"state": "draft"} + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + ) + self._useAttributes(data) + + def publish(self) -> None: + """ + Publishes the advisory. + + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id ` + + """ + patch_parameters = {"state": "published"} + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + ) + self._useAttributes(data) + + def request_cve(self) -> None: + """ + Requests a CVE for the advisory. + + :calls: `POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve `_ + + """ + self._requester.requestJsonAndCheck( + "POST", + self.url + "/cve", + ) + + def close(self) -> None: + """ + Closes the advisory. + + :calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id ` + + """ + patch_parameters = {"state": "closed"} + headers, data = self._requester.requestJsonAndCheck( + "PATCH", + self.url, + input=patch_parameters, + ) + self._useAttributes(data) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "author" in attributes: # pragma no branch + self._author = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["author"]) + if "closed_at" in attributes: # pragma no branch + assert attributes["closed_at"] is None or isinstance(attributes["closed_at"], str), attributes["closed_at"] + self._closed_at = self._makeDatetimeAttribute(attributes["closed_at"]) + if "collaborating_teams" in attributes: # pragma no branch + self._collaborating_teams = self._makeListOfClassesAttribute( + github.Team.Team, attributes["collaborating_teams"] + ) + if "collaborating_users" in attributes: # pragma no branch + self._collaborating_users = self._makeListOfClassesAttribute( + github.NamedUser.NamedUser, attributes["collaborating_users"] + ) + if "created_at" in attributes: # pragma no branch + assert attributes["created_at"] is None or isinstance(attributes["created_at"], str), attributes[ + "created_at" + ] + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "credits" in attributes: # pragma no branch + self._credits = self._makeListOfClassesAttribute( + github.AdvisoryCredit.AdvisoryCredit, + attributes["credits"], + ) + if "credits_detailed" in attributes: # pragma no branch + self._credits_detailed = self._makeListOfClassesAttribute( + github.AdvisoryCreditDetailed.AdvisoryCreditDetailed, + attributes["credits_detailed"], + ) + if "cwe_ids" in attributes: # pragma no branch + self._cwe_ids = self._makeListOfStringsAttribute(attributes["cwe_ids"]) + if "private_fork" in attributes: # pragma no branch + self._private_fork = self._makeClassAttribute(github.Repository.Repository, attributes["private_fork"]) + if "publisher" in attributes: # pragma no branch + self._publisher = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["publisher"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "submission" in attributes: # pragma no branch + self._submission = self._makeDictAttribute(attributes["submission"]) + if "vulnerabilities" in attributes: + self._vulnerabilities = self._makeListOfClassesAttribute( + github.AdvisoryVulnerability.AdvisoryVulnerability, + attributes["vulnerabilities"], + ) + super()._useAttributes(attributes) diff --git a/python_embeded/Lib/site-packages/github/RepositoryDiscussion.py b/python_embeded/Lib/site-packages/github/RepositoryDiscussion.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7624f869edb227ebb93d7d619d1b82d53b5dce --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RepositoryDiscussion.py @@ -0,0 +1,213 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2024 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github +import github.Label +import github.NamedUser +import github.Reaction +import github.Repository +import github.RepositoryDiscussionCategory +import github.RepositoryDiscussionComment +from github.DiscussionBase import DiscussionBase +from github.GithubObject import ( + Attribute, + GraphQlObject, + NotSet, + as_rest_api_attributes, + as_rest_api_attributes_list, + is_undefined, +) +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.Label import Label + from github.NamedUser import NamedUser + from github.Reaction import Reaction + from github.Repository import Repository + from github.RepositoryDiscussionCategory import RepositoryDiscussionCategory + from github.RepositoryDiscussionComment import RepositoryDiscussionComment + + +class RepositoryDiscussion(GraphQlObject, DiscussionBase): + """ + This class represents GraphQL Discussion. + + The reference can be found here + https://docs.github.com/en/graphql/reference/objects#discussion + + """ + + def _initAttributes(self) -> None: + super()._initAttributes() + self._answer: Attribute[RepositoryDiscussionComment | None] = NotSet + self._body_text: Attribute[str] = NotSet + self._category: Attribute[RepositoryDiscussionCategory] = NotSet + self._comments_page = None + self._database_id: Attribute[int] = NotSet + self._editor: Attribute[NamedUser] = NotSet + self._id: Attribute[str] = NotSet + self._labels_page = None + self._reactions_page = None + self._repository: Attribute[Repository] = NotSet + + @property + def answer(self) -> RepositoryDiscussionComment | None: + return self._answer.value + + @property + def body_text(self) -> str: + return self._body_text.value + + @property + def category(self) -> RepositoryDiscussionCategory: + return self._category.value + + @property + def database_id(self) -> int: + return self._database_id.value + + @property + def editor(self) -> NamedUser: + return self._editor.value + + @property + def id(self) -> str: + return self._id.value + + @property + def node_id(self) -> str: + return self.id + + @property + def repository(self) -> Repository: + return self._repository.value + + def get_comments(self, comment_graphql_schema: str) -> PaginatedList[RepositoryDiscussionComment]: + if self._comments_page is not None: + return PaginatedList( + github.RepositoryDiscussionComment.RepositoryDiscussionComment, + self._requester, + firstData=self._comments_page, + firstHeaders={}, + ) + + if is_undefined(self._id): + raise RuntimeError("Retrieving discussion comments requires the discussion field 'id'") + if not comment_graphql_schema.startswith("\n"): + comment_graphql_schema = f" {comment_graphql_schema} " + + query = ( + """ + query Q($discussionId: ID!, $first: Int, $last: Int, $before: String, $after: String) { + node(id: $discussionId) { + ... on Discussion { + comments(first: $first, last: $last, before: $before, after: $after) { + totalCount + pageInfo { + startCursor + endCursor + hasNextPage + hasPreviousPage + } + nodes {""" + + comment_graphql_schema + + """} + } + } + } + }""" + ) + variables = {"discussionId": self.node_id} + return PaginatedList( + github.RepositoryDiscussionComment.RepositoryDiscussionComment, + self._requester, + graphql_query=query, + graphql_variables=variables, + list_item=["node", "comments"], + ) + + def get_labels(self) -> PaginatedList[Label]: + if self._labels_page is None: + raise RuntimeError("Fetching labels not implemented") + return PaginatedList(github.Label.Label, self._requester, firstData=self._labels_page, firstHeaders={}) + + def get_reactions(self) -> PaginatedList[Reaction]: + if self._reactions_page is None: + raise RuntimeError("Fetching reactions not implemented") + return PaginatedList(github.Reaction.Reaction, self._requester, firstData=self._reactions_page, firstHeaders={}) + + def add_comment( + self, body: str, reply_to: RepositoryDiscussionComment | str | None = None, output_schema: str = "id" + ) -> RepositoryDiscussionComment: + reply_to_id = ( + reply_to.id + if isinstance(reply_to, github.RepositoryDiscussionComment.RepositoryDiscussionComment) + else reply_to + ) + if not output_schema.startswith("\n"): + output_schema = f" {output_schema} " + + variables = {"body": body, "discussionId": self.id, "replyToId": reply_to_id} + return self._requester.graphql_named_mutation_class( + "addDiscussionComment", + NotSet.remove_unset_items(variables), + f"comment {{{output_schema}}}", + "comment", + github.RepositoryDiscussionComment.RepositoryDiscussionComment, + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + # super class is a REST API GithubObject, attributes are coming from GraphQL + super()._useAttributes(as_rest_api_attributes(attributes)) + if "answer" in attributes: # pragma no branch + self._answer = self._makeClassAttribute( + github.RepositoryDiscussionComment.RepositoryDiscussionComment, attributes["answer"] + ) + if "bodyText" in attributes: # pragma no branch + self._body_text = self._makeStringAttribute(attributes["bodyText"]) + if "category" in attributes: # pragma no branch + self._category = self._makeClassAttribute( + github.RepositoryDiscussionCategory.RepositoryDiscussionCategory, attributes["category"] + ) + if "comments" in attributes: # pragma no branch + # comments are GraphQL API objects + self._comments_page = attributes["comments"]["nodes"] + if "databaseId" in attributes: # pragma no branch + self._database_id = self._makeIntAttribute(attributes["databaseId"]) + if "editor" in attributes: # pragma no branch + self._editor = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["editor"]) + if "id" in attributes: # pragma no branch + self._id = self._makeStringAttribute(attributes["id"]) + if "labels" in attributes: # pragma no branch + # labels are REST API objects + self._labels_page = as_rest_api_attributes_list(attributes["labels"]["nodes"]) # type: ignore + if "reactions" in attributes: # pragma no branch + # reactions are REST API objects + self._reactions_page = as_rest_api_attributes_list(attributes["reactions"]["nodes"]) # type: ignore + if "repository" in attributes: # pragma no branch + self._repository = self._makeClassAttribute( + github.Repository.Repository, as_rest_api_attributes(attributes["repository"]) + ) diff --git a/python_embeded/Lib/site-packages/github/RepositoryDiscussionCategory.py b/python_embeded/Lib/site-packages/github/RepositoryDiscussionCategory.py new file mode 100644 index 0000000000000000000000000000000000000000..0a832134037f31a83c46fb4d5ee98246032d8628 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RepositoryDiscussionCategory.py @@ -0,0 +1,142 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 Victor Zeng # +# Copyright 2022 Eric Nieuwland # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.Reaction +from github.GithubObject import Attribute, GraphQlObject, NonCompletableGithubObject, NotSet, as_rest_api_attributes + +if TYPE_CHECKING: + from github.Repository import Repository + + +class RepositoryDiscussionCategory(GraphQlObject, NonCompletableGithubObject): + """ + This class represents GraphQL DiscussionCategory. + + The reference can be found here + https://docs.github.com/en/graphql/reference/objects#discussioncategory + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._description: Attribute[str] = NotSet + self._emoji: Attribute[str] = NotSet + self._emoji_html: Attribute[str] = NotSet + self._id: Attribute[str] = NotSet + self._is_answerable: Attribute[bool] = NotSet + self._name: Attribute[str] = NotSet + self._repository: Attribute[Repository] = NotSet + self._slug: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + + @property + def created_at(self) -> datetime: + return self._created_at.value + + @property + def description(self) -> str: + return self._description.value + + @property + def emoji(self) -> str: + return self._emoji.value + + @property + def emoji_html(self) -> str: + return self._emoji_html.value + + @property + def id(self) -> str: + return self._id.value + + @property + def is_answerable(self) -> bool: + return self._is_answerable.value + + @property + def name(self) -> str: + return self._name.value + + @property + def node_id(self) -> str: + return self.id + + @property + def repository(self) -> Repository: + return self._repository.value + + @property + def slug(self) -> str: + return self._slug.value + + @property + def updated_at(self) -> datetime: + return self._updated_at.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "createdAt" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["createdAt"]) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "emoji" in attributes: # pragma no branch + self._emoji = self._makeStringAttribute(attributes["emoji"]) + if "emojiHTML" in attributes: # pragma no branch + self._emoji_html = self._makeStringAttribute(attributes["emojiHTML"]) + if "id" in attributes: # pragma no branch + self._id = self._makeStringAttribute(attributes["id"]) + if "isAnswerable" in attributes: # pragma no branch + self._is_answerable = self._makeBoolAttribute(attributes["isAnswerable"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "repository" in attributes: # pragma no branch + # repository is a REST API object + self._repository = self._makeClassAttribute( + github.Repository.Repository, as_rest_api_attributes(attributes["repository"]) + ) + if "slug" in attributes: # pragma no branch + self._slug = self._makeStringAttribute(attributes["slug"]) + if "updatedAt" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updatedAt"]) diff --git a/python_embeded/Lib/site-packages/github/RepositoryDiscussionComment.py b/python_embeded/Lib/site-packages/github/RepositoryDiscussionComment.py new file mode 100644 index 0000000000000000000000000000000000000000..ef33a5abdab1642d2d5fba9ca3f00c08fc0f406b --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RepositoryDiscussionComment.py @@ -0,0 +1,149 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2024 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.NamedUser +import github.Reaction +from github.DiscussionCommentBase import DiscussionCommentBase +from github.GithubObject import ( + Attribute, + GraphQlObject, + NotSet, + as_rest_api_attributes, + as_rest_api_attributes_list, + is_defined, +) +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + from github.Reaction import Reaction + from github.RepositoryDiscussion import RepositoryDiscussion + + +class RepositoryDiscussionComment(GraphQlObject, DiscussionCommentBase): + """ + This class represents GraphQL DiscussionComment. + + The reference can be found here + https://docs.github.com/en/graphql/reference/objects#discussioncomment + + """ + + def _initAttributes(self) -> None: + super()._initAttributes() + self._body_text: Attribute[str] = NotSet + self._database_id: Attribute[int] = NotSet + self._discussion: Attribute[RepositoryDiscussion] + self._editor: Attribute[NamedUser] = NotSet + self._id: Attribute[str] = NotSet + self._reactions_page = None + self._replies_page = None + + @property + def body_text(self) -> str: + return self._body_text.value + + @property + def database_id(self) -> int: + return self._database_id.value + + @property + def discussion(self) -> RepositoryDiscussion: + return self._discussion.value + + @property + def editor(self) -> NamedUser: + return self._editor.value + + @property + def id(self) -> str: + return self._id.value + + @property + def node_id(self) -> str: + if is_defined(self._node_id): + return super().node_id + return self.id + + def get_reactions(self) -> PaginatedList[Reaction]: + if self._reactions_page is None: + raise RuntimeError("Fetching reactions not implemented") + return PaginatedList(github.Reaction.Reaction, self._requester, firstData=self._reactions_page, firstHeaders={}) + + def get_replies(self) -> PaginatedList[RepositoryDiscussionComment]: + if self._replies_page is None: + raise RuntimeError("Fetching replies not implemented") + return PaginatedList( + RepositoryDiscussionComment, self._requester, firstData=self._replies_page, firstHeaders={} + ) + + def edit(self, body: str, output_schema: str = "id") -> RepositoryDiscussionComment: + if not output_schema.startswith("\n"): + output_schema = f" {output_schema} " + return self._requester.graphql_named_mutation_class( + "updateDiscussionComment", + {"commentId": self.node_id, "body": body}, + f"comment {{{output_schema}}}", + "comment", + github.RepositoryDiscussionComment.RepositoryDiscussionComment, + ) + + def delete(self, output_schema: str = "id") -> RepositoryDiscussionComment: + if not output_schema.startswith("\n"): + output_schema = f" {output_schema} " + return self._requester.graphql_named_mutation_class( + "deleteDiscussionComment", + {"id": self.id}, + f"comment {{{output_schema}}}", + "comment", + github.RepositoryDiscussionComment.RepositoryDiscussionComment, + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + # super class is a REST API GithubObject, attributes are coming from GraphQL + super()._useAttributes(as_rest_api_attributes(attributes)) + if "bodyText" in attributes: # pragma no branch + self._body_text = self._makeStringAttribute(attributes["bodyText"]) + if "databaseId" in attributes: # pragma no branch + self._database_id = self._makeIntAttribute(attributes["databaseId"]) + if "discussion" in attributes: # pragma no branch + # RepositoryDiscussion is a GraphQL API object + self._discussion = self._makeClassAttribute( + github.RepositoryDiscussion.RepositoryDiscussion, attributes["discussion"] + ) + if "editor" in attributes: # pragma no branch + # NamedUser is a REST API object + self._editor = self._makeClassAttribute( + github.NamedUser.NamedUser, as_rest_api_attributes(attributes["editor"]) + ) + if "id" in attributes: # pragma no branch + self._id = self._makeStringAttribute(attributes["id"]) + if "reactions" in attributes: # pragma no branch + # reactions are REST API objects + self._reactions_page = as_rest_api_attributes_list(attributes["reactions"]["nodes"]) # type: ignore + if "replies" in attributes: # pragma no branch + # replies are GraphQL API objects + self._replies_page = attributes["replies"]["nodes"] diff --git a/python_embeded/Lib/site-packages/github/RepositoryKey.py b/python_embeded/Lib/site-packages/github/RepositoryKey.py new file mode 100644 index 0000000000000000000000000000000000000000..84dec926b3f8976ecc8ac0022d3808453ab8e912 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RepositoryKey.py @@ -0,0 +1,152 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Srijan Choudhary # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Jimmy Zelinskie # +# Copyright 2017 Simon # +# Copyright 2018 Laurent Raufaste # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Floyd Hightower # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Ramiro Morales # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class RepositoryKey(CompletableGithubObject): + """ + This class represents RepositoryKeys. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#deploy-keys + + The OpenAPI schema can be found at + - /components/schemas/deploy-key + + """ + + def _initAttributes(self) -> None: + self._added_by: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._id: Attribute[int] = NotSet + self._key: Attribute[str] = NotSet + self._last_used: Attribute[datetime] = NotSet + self._read_only: Attribute[bool] = NotSet + self._title: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + self._verified: Attribute[bool] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "title": self._title.value}) + + @property + def added_by(self) -> str: + self._completeIfNotSet(self._added_by) + return self._added_by.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def key(self) -> str: + self._completeIfNotSet(self._key) + return self._key.value + + @property + def last_used(self) -> datetime: + self._completeIfNotSet(self._last_used) + return self._last_used.value + + @property + def read_only(self) -> bool: + self._completeIfNotSet(self._read_only) + return self._read_only.value + + @property + def title(self) -> str: + self._completeIfNotSet(self._title) + return self._title.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def verified(self) -> bool: + self._completeIfNotSet(self._verified) + return self._verified.value + + def delete(self) -> None: + """ + :calls: `DELETE /repos/{owner}/{repo}/keys/{id} `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "added_by" in attributes: # pragma no branch + self._added_by = self._makeStringAttribute(attributes["added_by"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "key" in attributes: # pragma no branch + self._key = self._makeStringAttribute(attributes["key"]) + if "last_used" in attributes: # pragma no branch + assert attributes["last_used"] is None or isinstance(attributes["last_used"], str), attributes["last_used"] + self._last_used = self._makeDatetimeAttribute(attributes["last_used"]) + if "read_only" in attributes: # pragma no branch + self._read_only = self._makeBoolAttribute(attributes["read_only"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "verified" in attributes: # pragma no branch + self._verified = self._makeBoolAttribute(attributes["verified"]) diff --git a/python_embeded/Lib/site-packages/github/RepositoryPreferences.py b/python_embeded/Lib/site-packages/github/RepositoryPreferences.py new file mode 100644 index 0000000000000000000000000000000000000000..426329abdf225e55f2f15d01150dd505dddb907b --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RepositoryPreferences.py @@ -0,0 +1,80 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Nick Campbell # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Dhruv Manilawala # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.Repository +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.Repository import Repository + + +class RepositoryPreferences(NonCompletableGithubObject): + """ + This class represents repository preferences. + + The reference can be found here + https://docs.github.com/en/free-pro-team@latest/rest/reference/checks#update-repository-preferences-for-check-suites + + The OpenAPI schema can be found at + - /components/schemas/check-suite-preference + + """ + + def _initAttributes(self) -> None: + self._preferences: Attribute[dict[str, list[dict[str, bool | int]]]] = NotSet + self._repository: Attribute[Repository] = NotSet + + @property + def preferences(self) -> dict[str, list[dict[str, bool | int]]]: + return self._preferences.value + + @property + def repository(self) -> Repository: + return self._repository.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "preferences" in attributes: # pragma no branch + self._preferences = self._makeDictAttribute(attributes["preferences"]) + if "repository" in attributes: # pragma no branch + self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"]) diff --git a/python_embeded/Lib/site-packages/github/Requester.py b/python_embeded/Lib/site-packages/github/Requester.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e5eb554c0b588b6648a31424e97267f0d98ff7 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Requester.py @@ -0,0 +1,1317 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Andrew Bettison # +# Copyright 2012 Dima Kukushkin # +# Copyright 2012 Michael Woodworth # +# Copyright 2012 Petteri Muilu # +# Copyright 2012 Steve English # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Cameron White # +# Copyright 2013 Ed Jackson # +# Copyright 2013 Jonathan J Hunt # +# Copyright 2013 Mark Roddy # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Jimmy Zelinskie # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Brian Eugley # +# Copyright 2015 Daniel Pocock # +# Copyright 2016 Denis K # +# Copyright 2016 Jared K. Smith # +# Copyright 2016 Mathieu Mitchell # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Chris McBride # +# Copyright 2017 Hugo # +# Copyright 2017 Simon # +# Copyright 2018 Arda Kuyumcu # +# Copyright 2018 Dylan # +# Copyright 2018 Maarten Fonville # +# Copyright 2018 Mike Miller # +# Copyright 2018 R1kk3r # +# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Tuuu Nya # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Isac Souza # +# Copyright 2019 Rigas Papathanasopoulos # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Jesse Li # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Amador Pahim # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2022 Liuyang Wan # +# Copyright 2023 Denis Blanchette # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Heitor Polidoro # +# Copyright 2023 Hemslo Wang # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Phillip Tran # +# Copyright 2023 Trim21 # +# Copyright 2023 adosibalo <94008816+adosibalo@users.noreply.github.com> # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Jonathan Kliem # +# Copyright 2024 Kobbi Gal <85439776+kgal-pan@users.noreply.github.com> # +# Copyright 2024 Min RK # +# Copyright 2025 Enrico Minack # +# Copyright 2025 Neel Malik <41765022+neel-m@users.noreply.github.com> # +# Copyright 2025 Timothy Klopotoski # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +import io +import json +import logging +import mimetypes +import os +import re +import threading +import time +import urllib +import urllib.parse +from collections import deque +from datetime import datetime, timezone +from io import IOBase +from typing import ( + TYPE_CHECKING, + Any, + BinaryIO, + Callable, + Deque, + Dict, + Generic, + ItemsView, + Iterator, + List, + Optional, + Tuple, + Type, + TypeVar, + Union, +) + +import requests +import requests.adapters +from urllib3 import Retry + +import github.Consts as Consts +import github.GithubException +import github.GithubException as GithubException +from github.GithubObject import as_rest_api_attributes + +if TYPE_CHECKING: + from .AppAuthentication import AppAuthentication + from .Auth import Auth + from .GithubObject import GithubObject + from .InstallationAuthorization import InstallationAuthorization + +T = TypeVar("T") +T_gh = TypeVar("T_gh", bound="GithubObject") + +# For App authentication, time remaining before token expiration to request a new one +ACCESS_TOKEN_REFRESH_THRESHOLD_SECONDS = 20 + + +class RequestsResponse: + # mimic the httplib response object + def __init__(self, r: requests.Response): + self.status = r.status_code + self.headers = r.headers + self.response = r + + def getheaders(self) -> ItemsView[str, str]: + return self.headers.items() + + def read(self) -> str: + return self.response.text + + def iter_content(self, chunk_size: Union[int, None] = 1) -> Iterator: + return self.response.iter_content(chunk_size=chunk_size) + + def raise_for_status(self) -> None: + self.response.raise_for_status() + + +class HTTPSRequestsConnectionClass: + retry: Union[int, Retry] + + # mimic the httplib connection object + def __init__( + self, + host: str, + port: Optional[int] = None, + strict: bool = False, + timeout: Optional[int] = None, + retry: Optional[Union[int, Retry]] = None, + pool_size: Optional[int] = None, + **kwargs: Any, + ) -> None: + self.port = port if port else 443 + self.host = host + self.protocol = "https" + self.timeout = timeout + self.verify = kwargs.get("verify", True) + self.session = requests.Session() + # having Session.auth set something other than None disables falling back to .netrc file + # https://github.com/psf/requests/blob/d63e94f552ebf77ccf45d97e5863ac46500fa2c7/src/requests/sessions.py#L480-L481 + # see https://github.com/PyGithub/PyGithub/pull/2703 + self.session.auth = Requester.noopAuth + + if retry is None: + self.retry = requests.adapters.DEFAULT_RETRIES + else: + self.retry = retry + + if pool_size is None: + self.pool_size = requests.adapters.DEFAULT_POOLSIZE + else: + self.pool_size = pool_size + + self.adapter = requests.adapters.HTTPAdapter( + max_retries=self.retry, + pool_connections=self.pool_size, + pool_maxsize=self.pool_size, + ) + self.session.mount("https://", self.adapter) + + def request( + self, + verb: str, + url: str, + input: Optional[Union[str, io.BufferedReader]], + headers: Dict[str, str], + stream: bool = False, + ) -> None: + self.verb = verb + self.url = url + self.input = input + self.headers = headers + self.stream = stream + + def getresponse(self) -> RequestsResponse: + verb = getattr(self.session, self.verb.lower()) + url = f"{self.protocol}://{self.host}:{self.port}{self.url}" + r = verb( + url, + headers=self.headers, + data=self.input, + timeout=self.timeout, + verify=self.verify, + allow_redirects=False, + ) + return RequestsResponse(r) + + def close(self) -> None: + self.session.close() + + +class HTTPRequestsConnectionClass: + # mimic the httplib connection object + def __init__( + self, + host: str, + port: Optional[int] = None, + strict: bool = False, + timeout: Optional[int] = None, + retry: Optional[Union[int, Retry]] = None, + pool_size: Optional[int] = None, + **kwargs: Any, + ): + self.port = port if port else 80 + self.host = host + self.protocol = "http" + self.timeout = timeout + self.verify = kwargs.get("verify", True) + self.session = requests.Session() + # having Session.auth set something other than None disables falling back to .netrc file + # https://github.com/psf/requests/blob/d63e94f552ebf77ccf45d97e5863ac46500fa2c7/src/requests/sessions.py#L480-L481 + # see https://github.com/PyGithub/PyGithub/pull/2703 + self.session.auth = Requester.noopAuth + + if retry is None: + self.retry = requests.adapters.DEFAULT_RETRIES + else: + self.retry = retry # type: ignore + + if pool_size is None: + self.pool_size = requests.adapters.DEFAULT_POOLSIZE + else: + self.pool_size = pool_size + + self.adapter = requests.adapters.HTTPAdapter( + max_retries=self.retry, + pool_connections=self.pool_size, + pool_maxsize=self.pool_size, + ) + self.session.mount("http://", self.adapter) + + def request(self, verb: str, url: str, input: None, headers: Dict[str, str], stream: bool = False) -> None: + self.verb = verb + self.url = url + self.input = input + self.headers = headers + self.stream = stream + + def getresponse(self) -> RequestsResponse: + verb = getattr(self.session, self.verb.lower()) + url = f"{self.protocol}://{self.host}:{self.port}{self.url}" + r = verb( + url, + headers=self.headers, + data=self.input, + timeout=self.timeout, + verify=self.verify, + allow_redirects=False, + ) + return RequestsResponse(r) + + def close(self) -> None: + self.session.close() + + +class Requester: + __installation_authorization: Optional["InstallationAuthorization"] + __app_auth: Optional["AppAuthentication"] + + __httpConnectionClass = HTTPRequestsConnectionClass + __httpsConnectionClass = HTTPSRequestsConnectionClass + __persist = True + __logger: Optional[logging.Logger] = None + + _frameBuffer: List[Any] + + @staticmethod + def noopAuth(request: requests.models.PreparedRequest) -> requests.models.PreparedRequest: + return request + + @classmethod + def injectConnectionClasses( + cls, + httpConnectionClass: Type[HTTPRequestsConnectionClass], + httpsConnectionClass: Type[HTTPSRequestsConnectionClass], + ) -> None: + cls.__persist = False + cls.__httpConnectionClass = httpConnectionClass + cls.__httpsConnectionClass = httpsConnectionClass + + @classmethod + def resetConnectionClasses(cls) -> None: + cls.__persist = True + cls.__httpConnectionClass = HTTPRequestsConnectionClass + cls.__httpsConnectionClass = HTTPSRequestsConnectionClass + + @classmethod + def injectLogger(cls, logger: logging.Logger) -> None: + cls.__logger = logger + + @classmethod + def resetLogger(cls) -> None: + cls.__logger = None + + ############################################################# + # For Debug + @classmethod + def setDebugFlag(cls, flag: bool) -> None: + cls.DEBUG_FLAG = flag + + @classmethod + def setOnCheckMe(cls, onCheckMe: Callable) -> None: + cls.ON_CHECK_ME = onCheckMe + + DEBUG_FLAG = False + + DEBUG_FRAME_BUFFER_SIZE = 1024 + + DEBUG_HEADER_KEY = "DEBUG_FRAME" + + ON_CHECK_ME: Optional[Callable] = None + + def NEW_DEBUG_FRAME(self, requestHeader: Dict[str, str]) -> None: + """ + Initialize a debug frame with requestHeader + Frame count is updated and will be attached to respond header + The structure of a frame: [requestHeader, statusCode, responseHeader, raw_data] + Some of them may be None + """ + if self.DEBUG_FLAG: # pragma no branch (Flag always set in tests) + new_frame = [requestHeader, None, None, None] + if self._frameCount < self.DEBUG_FRAME_BUFFER_SIZE - 1: # pragma no branch (Should be covered) + self._frameBuffer.append(new_frame) + else: + self._frameBuffer[0] = new_frame # pragma no cover (Should be covered) + + self._frameCount = len(self._frameBuffer) - 1 + + def DEBUG_ON_RESPONSE(self, statusCode: int, responseHeader: Dict[str, Union[str, int]], data: str) -> None: + """ + Update current frame with response Current frame index will be attached to responseHeader. + """ + if self.DEBUG_FLAG: # pragma no branch (Flag always set in tests) + self._frameBuffer[self._frameCount][1:4] = [ + statusCode, + responseHeader, + data, + ] + responseHeader[self.DEBUG_HEADER_KEY] = self._frameCount + + def check_me(self, obj: "GithubObject") -> None: + if self.DEBUG_FLAG and self.ON_CHECK_ME is not None: # pragma no branch (Flag always set in tests) + frame = None + if self.DEBUG_HEADER_KEY in obj._headers: + frame_index = obj._headers[self.DEBUG_HEADER_KEY] + frame = self._frameBuffer[frame_index] # type: ignore + self.ON_CHECK_ME(obj, frame) + + def _initializeDebugFeature(self) -> None: + self._frameCount = 0 + self._frameBuffer = [] + + ############################################################# + + _frameCount: int + __connectionClass: Union[Type[HTTPRequestsConnectionClass], Type[HTTPSRequestsConnectionClass]] + __hostname: str + __authorizationHeader: Optional[str] + __seconds_between_requests: Optional[float] + __seconds_between_writes: Optional[float] + + # keep arguments in-sync with github.MainClass and GithubIntegration + def __init__( + self, + auth: Optional["Auth"], + base_url: str, + timeout: int, + user_agent: str, + per_page: int, + verify: Union[bool, str], + retry: Optional[Union[int, Retry]], + pool_size: Optional[int], + seconds_between_requests: Optional[float] = None, + seconds_between_writes: Optional[float] = None, + lazy: bool = False, + ): + self._initializeDebugFeature() + + self.__auth = auth + self.__base_url = base_url + + o = urllib.parse.urlparse(base_url) + self.__graphql_prefix = self.get_graphql_prefix(o.path) + self.__graphql_url = urllib.parse.urlunparse(o._replace(path=self.__graphql_prefix)) + self.__hostname = o.hostname # type: ignore + self.__port = o.port + self.__prefix = o.path + self.__timeout = timeout + self.__retry = retry # NOTE: retry can be either int or an urllib3 Retry object + self.__pool_size = pool_size + self.__seconds_between_requests = seconds_between_requests + self.__seconds_between_writes = seconds_between_writes + self.__last_requests: Dict[str, float] = dict() + self.__scheme = o.scheme + if o.scheme == "https": + self.__connectionClass = self.__httpsConnectionClass + elif o.scheme == "http": + self.__connectionClass = self.__httpConnectionClass + else: + assert False, "Unknown URL scheme" + self.__connection: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None + self.__connection_lock = threading.Lock() + self.__custom_connections: Deque[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = deque() + self.rate_limiting = (-1, -1) + self.rate_limiting_resettime = 0 + self.FIX_REPO_GET_GIT_REF = True + self.per_page = per_page + + self.oauth_scopes = None + + assert user_agent is not None, ( + "github now requires a user-agent. " + "See https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required" + ) + self.__userAgent = user_agent + self.__verify = verify + self.__lazy = lazy + + self.__installation_authorization = None + + # provide auth implementations that require a requester with this requester + if isinstance(self.__auth, WithRequester): + self.__auth.withRequester(self) + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + # __connection_lock is not picklable + del state["_Requester__connection_lock"] + # __connection is not usable on remote, so ignore it + del state["_Requester__connection"] + # __custom_connections is not usable on remote, so ignore it + del state["_Requester__custom_connections"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + self.__connection_lock = threading.Lock() + self.__connection = None + self.__custom_connections = deque() + + @staticmethod + # replace with str.removesuffix once support for Python 3.8 is dropped + def remove_suffix(string: str, suffix: str) -> str: + if string.endswith(suffix): + return string[: -len(suffix)] + return string + + @staticmethod + def get_graphql_prefix(path: Optional[str]) -> str: + if path is None or path in ["", "/"]: + path = "" + if path.endswith(("/v3", "/v3/")): + path = Requester.remove_suffix(path, "/") + path = Requester.remove_suffix(path, "/v3") + return path + "/graphql" + + @staticmethod + def get_parameters_of_url(url: str) -> Dict[str, list]: + query = urllib.parse.urlparse(url)[4] + return urllib.parse.parse_qs(query) + + @staticmethod + def add_parameters_to_url( + url: str, + parameters: Dict[str, Any], + ) -> str: + scheme, netloc, url, params, query, fragment = urllib.parse.urlparse(url) + url_params = urllib.parse.parse_qs(query) + # union parameters in url with given parameters, the latter have precedence + url_params.update(**{k: v if isinstance(v, list) else [v] for k, v in parameters.items()}) + parameter_list = [(key, value) for key, values in url_params.items() for value in values] + # remove query from url + url = urllib.parse.urlunparse((scheme, netloc, url, params, "", fragment)) + + if len(parameter_list) == 0: + return url + else: + return f"{url}?{urllib.parse.urlencode(parameter_list)}" + + def close(self) -> None: + """ + Close the connection to the server. + """ + with self.__connection_lock: + if self.__connection is not None: + self.__connection.close() + self.__connection = None + while self.__custom_connections: + self.__custom_connections.popleft().close() + + @property + def kwargs(self) -> Dict[str, Any]: + """ + Returns arguments required to recreate this Requester with Requester.__init__, as well as with + MainClass.__init__ and GithubIntegration.__init__. + """ + return dict( + auth=self.__auth, + base_url=self.__base_url, + timeout=self.__timeout, + user_agent=self.__userAgent, + per_page=self.per_page, + verify=self.__verify, + retry=self.__retry, + pool_size=self.__pool_size, + seconds_between_requests=self.__seconds_between_requests, + seconds_between_writes=self.__seconds_between_writes, + lazy=self.__lazy, + ) + + @property + def base_url(self) -> str: + return self.__base_url + + @property + def graphql_url(self) -> str: + return self.__graphql_url + + @property + def scheme(self) -> str: + return self.__scheme + + @property + def hostname(self) -> str: + return self.__hostname + + @property + def hostname_and_port(self) -> str: + if self.__port is None: + return self.hostname + return f"{self.hostname}:{self.__port}" + + @property + def auth(self) -> Optional["Auth"]: + return self.__auth + + def withAuth(self, auth: Optional["Auth"]) -> "Requester": + """ + Create a new requester instance with identical configuration but the given authentication method. + + :param auth: authentication method + :return: new Requester instance + + """ + kwargs = self.kwargs + kwargs.update(auth=auth) + return Requester(**kwargs) + + @property + def is_lazy(self) -> bool: + return self.__lazy + + @property + def is_not_lazy(self) -> bool: + return not self.__lazy + + def withLazy(self, lazy: bool) -> "Requester": + """ + Create a new requester instance with identical configuration but the given lazy setting. + + :param lazy: completable objects created from this instance are lazy, as well as completable objects created + from those, and so on + :return: new Requester instance + + """ + kwargs = self.kwargs + kwargs.update(lazy=lazy) + return Requester(**kwargs) + + def requestJsonAndCheck( + self, + verb: str, + url: str, + parameters: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + input: Optional[Any] = None, + follow_302_redirect: bool = False, + ) -> Tuple[Dict[str, Any], Any]: + """ + Send a request with JSON body. + + :param input: request body, serialized to JSON if specified + + :return: ``(headers: dict, JSON Response: Any)`` + :raises: :class:`GithubException` for error status codes + + """ + return self.__check( + *self.requestJson( + verb, + url, + parameters, + headers, + input, + self.__customConnection(url), + follow_302_redirect=follow_302_redirect, + ) + ) + + def requestMultipartAndCheck( + self, + verb: str, + url: str, + parameters: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, Any]] = None, + input: Optional[Dict[str, str]] = None, + ) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]: + """ + Send a request with multi-part-encoded body. + + :param input: request body, will be multi-part encoded if specified + + :return: ``(headers: dict, JSON Response: Any)`` + :raises: :class:`GithubException` for error status codes + + """ + return self.__check(*self.requestMultipart(verb, url, parameters, headers, input, self.__customConnection(url))) + + def requestBlobAndCheck( + self, + verb: str, + url: str, + parameters: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + input: Optional[str] = None, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None, + ) -> Tuple[Dict[str, Any], Dict[str, Any]]: + """ + Send a request with a file for the body. + + :param input: path to a file to use for the request body + + :return: ``(headers: dict, JSON Response: Any)`` + :raises: :class:`GithubException` for error status codes + + """ + return self.__check(*self.requestBlob(verb, url, parameters, headers, input, self.__customConnection(url))) + + def graphql_query(self, query: str, variables: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: + """ + :calls: `POST /graphql `_ + """ + input_ = {"query": query, "variables": variables} + + response_headers, data = self.requestJsonAndCheck("POST", self.graphql_url, input=input_) + if "errors" in data: + if len(data["errors"]) == 1: + error = data["errors"][0] + if error.get("type") == "NOT_FOUND": + raise github.UnknownObjectException(404, data, response_headers, error.get("message")) + raise self.createException(400, response_headers, data) + return response_headers, data + + @classmethod + def paths_of_dict(cls, d: dict) -> dict: + return {key: cls.paths_of_dict(val) if isinstance(val, dict) else None for key, val in d.items()} + + def data_as_class( + self, headers: Dict[str, Any], data: Dict[str, Any], data_path: List[str], klass: Type[T_gh] + ) -> T_gh: + for item in data_path: + if item not in data: + raise RuntimeError(f"GraphQL path {data_path} not found in data: {self.paths_of_dict(data)}") + data = data[item] + if klass.is_rest(): + data = as_rest_api_attributes(data) + return klass(self, headers, data) + + def graphql_node(self, node_id: str, graphql_schema: str, node_type: str) -> Tuple[Dict[str, Any], Dict[str, Any]]: + """ + :calls: `POST /graphql `_ + """ + if not graphql_schema.startswith("\n"): + graphql_schema = f" {graphql_schema} " + query = ( + """ + query Q($id: ID!) { + node(id: $id) { + __typename + ... on """ + + f"{node_type} {{{graphql_schema}}}" + + """ + } + } + """ + ) + + headers, data = self.graphql_query(query, {"id": node_id}) + actual_node_type = data.get("data", {}).get("node", {}).get("__typename", node_type) + if actual_node_type != node_type: + raise github.GithubException( + 400, + data, + message=f"Retrieved {node_type} object is of different type: {actual_node_type}", + ) + return headers, data + + def graphql_node_class( + self, node_id: str, graphql_schema: str, klass: Type[T_gh], node_type: Optional[str] = None + ) -> T_gh: + """ + :calls: `POST /graphql `_ + """ + if node_type is None: + node_type = klass.__name__ + + headers, data = self.graphql_node(node_id, graphql_schema, node_type) + return self.data_as_class(headers, data, ["data", "node"], klass) + + def graphql_query_class( + self, query: str, variables: Dict[str, Any], data_path: List[str], klass: Type[T_gh] + ) -> T_gh: + """ + :calls: `POST /graphql `_ + """ + headers, data = self.graphql_query(query, variables) + return self.data_as_class(headers, data, ["data"] + data_path, klass) + + def graphql_named_mutation( + self, mutation_name: str, mutation_input: Dict[str, Any], output_schema: str + ) -> Tuple[Dict[str, Any], Dict[str, Any]]: + """ + Create a mutation in the format: + mutation Mutation($input: MutationNameInput!) { + mutationName(input: $input) { } + } + and call the self.graphql_query method. + + Returns the response data according to given output schema. + """ + mutation_input_name = mutation_name[:1].upper() + mutation_name[1:] + "Input!" + query = f"mutation Mutation($input: {mutation_input_name}) {{ {mutation_name}(input: $input) {{ {output_schema} }} }}" + headers, data = self.graphql_query(query, {"input": mutation_input}) + return headers, data.get("data", {}).get(mutation_name, {}) + + def graphql_named_mutation_class( + self, mutation_name: str, mutation_input: Dict[str, Any], output_schema: str, item: str, klass: Type[T_gh] + ) -> T_gh: + """ + Executes a mutation and returns the output object as the given GithubObject. + + See {@link graphql_named_mutation}. + + """ + headers, data = self.graphql_named_mutation(mutation_name, mutation_input, output_schema) + return self.data_as_class(headers, data, [item], klass) + + def __check( + self, + status: int, + responseHeaders: Dict[str, Any], + output: str, + ) -> Tuple[Dict[str, Any], Any]: + data = self.__structuredFromJson(output) + if status >= 400: + raise self.createException(status, responseHeaders, data) + return responseHeaders, data + + def __customConnection( + self, url: str + ) -> Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]]: + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None + if not url.startswith("/"): + o = urllib.parse.urlparse(url) + if ( + o.hostname != self.__hostname + or (o.port and o.port != self.__port) + or (o.scheme != self.__scheme and not (o.scheme == "https" and self.__scheme == "http")) + ): # issue80 + if o.scheme == "http": + cnx = self.__httpConnectionClass( + o.hostname, # type: ignore + o.port, + retry=self.__retry, + pool_size=self.__pool_size, + ) + self.__custom_connections.append(cnx) + elif o.scheme == "https": + cnx = self.__httpsConnectionClass( + o.hostname, # type: ignore + o.port, + retry=self.__retry, + pool_size=self.__pool_size, + ) + self.__custom_connections.append(cnx) + return cnx + + @classmethod + def createException( + cls, + status: int, + headers: Dict[str, Any], + output: Dict[str, Any], + ) -> GithubException.GithubException: + message = output.get("message") if output else None + lc_message = message.lower() if message else "" + + msg = None + exc = GithubException.GithubException + if status == 401 and lc_message == "bad credentials": + exc = GithubException.BadCredentialsException + elif status == 401 and Consts.headerOTP in headers and re.match(r".*required.*", headers[Consts.headerOTP]): + exc = GithubException.TwoFactorException + elif status == 403 and lc_message.startswith("missing or invalid user agent string"): + exc = GithubException.BadUserAgentException + elif status == 403 and cls.isRateLimitError(lc_message): + exc = GithubException.RateLimitExceededException + elif status == 404 and (lc_message == "not found" or "no object found" in lc_message): + exc = GithubException.UnknownObjectException + else: + # for general GithubException, provide the actual message + msg = message + + return exc(status, output, headers, msg) + + @classmethod + def isRateLimitError(cls, message: str) -> bool: + return cls.isPrimaryRateLimitError(message) or cls.isSecondaryRateLimitError(message) + + @classmethod + def isPrimaryRateLimitError(cls, message: str) -> bool: + if not message: + return False + + message = message.lower() + return message.startswith("api rate limit exceeded") + + @classmethod + def isSecondaryRateLimitError(cls, message: str) -> bool: + if not message: + return False + + message = message.lower() + return ( + message.startswith("you have exceeded a secondary rate limit") + or message.endswith("please retry your request again later.") + or message.endswith("please wait a few minutes before you try again.") + ) + + def __structuredFromJson(self, data: str) -> Any: + if len(data) == 0: + return None + else: + if isinstance(data, bytes): + data = data.decode("utf-8") + try: + return json.loads(data) + except ValueError: + if data.startswith("{") or data.startswith("["): + raise + return {"data": data} + + def getFile( + self, + url: str, + path: str, + parameters: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None, + chunk_size: Optional[Union[int, None]] = 1, + ) -> None: + """ + GET a file from the server and save it to the given path, which includes the filename. + """ + _, _, stream_chunk_iterator = self.getStream(url, parameters, headers, cnx, chunk_size=chunk_size) + with open(path, "wb") as f: + for chunk in stream_chunk_iterator: + if chunk: + f.write(chunk) + + def getStream( + self, + url: str, + parameters: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None, + chunk_size: Optional[Union[int, None]] = 1, + ) -> Tuple[int, Dict[str, Any], Iterator]: + """ + GET a stream from the server. + + :returns:``(status, headers, stream_chunk_iterator)`` + + """ + if headers is None: + headers = {} + headers["Accept"] = "application/octet-stream" + + def encode(_: Any) -> Tuple[str, str]: + return "", "" + + status, responseHeaders, output = self.__requestEncode( + cnx, "GET", url, parameters, headers, None, encode, stream=True, follow_302_redirect=True + ) + if isinstance(output, RequestsResponse) or ( + hasattr(output, "iter_content") and hasattr(output, "raise_for_status") + ): + output.raise_for_status() + return status, responseHeaders, output.iter_content(chunk_size=chunk_size) + raise TypeError(f"Expected a RequestsResponse object: {type(output)}") + + def requestJson( + self, + verb: str, + url: str, + parameters: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, Any]] = None, + input: Optional[Any] = None, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None, + follow_302_redirect: bool = False, + ) -> Tuple[int, Dict[str, Any], str]: + """ + Send a request with JSON input. + + :param input: request body, will be serialized as JSON + :returns:``(status, headers, body)`` + + """ + + def encode(input: Any) -> Tuple[str, str]: + return "application/json", json.dumps(input) + + status, responseHeaders, output = self.__requestEncode( + cnx, verb, url, parameters, headers, input, encode, follow_302_redirect=follow_302_redirect + ) + if isinstance(output, str): + return status, responseHeaders, output + raise ValueError("requestJson() Expected a str, should never happen") + + def requestMultipart( + self, + verb: str, + url: str, + parameters: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, Any]] = None, + input: Optional[Dict[str, str]] = None, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None, + ) -> Tuple[int, Dict[str, Any], str]: + """ + Send a request with multi-part encoding. + + :param input: request body, will be serialized as multipart form data + :returns:``(status, headers, body)`` + + """ + + def encode(input: Dict[str, Any]) -> Tuple[str, str]: + boundary = "----------------------------3c3ba8b523b2" + eol = "\r\n" + + encoded_input = "" + for name, value in input.items(): + encoded_input += f"--{boundary}{eol}" + encoded_input += f'Content-Disposition: form-data; name="{name}"{eol}' + encoded_input += eol + encoded_input += value + eol + encoded_input += f"--{boundary}--{eol}" + return f"multipart/form-data; boundary={boundary}", encoded_input + + status, responseHeaders, output = self.__requestEncode(cnx, verb, url, parameters, headers, input, encode) + if isinstance(output, str): + return status, responseHeaders, output + raise ValueError("requestMultipart() Expected a str, should never happen") + + def requestBlob( + self, + verb: str, + url: str, + parameters: Optional[Dict[str, str]] = None, + headers: Optional[Dict[str, str]] = None, + input: Optional[str] = None, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None, + ) -> Tuple[int, Dict[str, Any], str]: + """ + Send a request with a file as request body. + + :param input: path to a local file to use for request body + :returns:``(status, headers, body)`` + + """ + if headers is None: + headers = {} + + def encode(local_path: str) -> Tuple[str, Any]: + if "Content-Type" in headers: # type: ignore + mime_type = headers["Content-Type"] # type: ignore + else: + guessed_type = mimetypes.guess_type(local_path) + mime_type = guessed_type[0] if guessed_type[0] is not None else Consts.defaultMediaType + f = open(local_path, "rb") + return mime_type, f + + if input: + headers["Content-Length"] = str(os.path.getsize(input)) + + status, responseHeaders, output = self.__requestEncode(cnx, verb, url, parameters, headers, input, encode) + if isinstance(output, str): + return status, responseHeaders, output + raise ValueError("requestBlob() Expected a str, should never happen") + + def requestMemoryBlobAndCheck( + self, + verb: str, + url: str, + parameters: Any, + headers: Dict[str, Any], + file_like: BinaryIO, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None, + ) -> Tuple[Dict[str, Any], Any]: + """ + Send a request with a binary file-like for the body. + + :param file_like: file-like object to use for the request body + :return: ``(headers: dict, JSON Response: Any)`` + :raises: :class:`GithubException` for error status codes + + """ + + # The expected signature of encode means that the argument is ignored. + def encode(_: Any) -> Tuple[str, Any]: + return headers["Content-Type"], file_like + + if not cnx: + cnx = self.__customConnection(url) + + status, responseHeaders, output = self.__requestEncode(cnx, verb, url, parameters, headers, file_like, encode) + if isinstance(output, str): + return self.__check(status, responseHeaders, output) + raise ValueError("requestMemoryBlobAndCheck() Expected a str, should never happen") + + def __requestEncode( + self, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]], + verb: str, + url: str, + parameters: Optional[Dict[str, str]], + requestHeaders: Optional[Dict[str, str]], + input: Optional[T], + encode: Callable[[T], Tuple[str, Any]], + stream: bool = False, + follow_302_redirect: bool = False, + ) -> Tuple[int, Dict[str, Any], Union[str, object]]: + assert verb in ["HEAD", "GET", "POST", "PATCH", "PUT", "DELETE"] + if parameters is None: + parameters = {} + if requestHeaders is None: + requestHeaders = {} + + if self.__auth is not None: + self.__auth.authentication(requestHeaders) + requestHeaders["User-Agent"] = self.__userAgent + + url = self.__makeAbsoluteUrl(url) + url = Requester.add_parameters_to_url(url, parameters) + + encoded_input = None + if input is not None: + requestHeaders["Content-Type"], encoded_input = encode(input) + + self.NEW_DEBUG_FRAME(requestHeaders) + + status, responseHeaders, output = self.__requestRaw( + cnx, verb, url, requestHeaders, encoded_input, stream=stream, follow_302_redirect=follow_302_redirect + ) + + if Consts.headerRateRemaining in responseHeaders and Consts.headerRateLimit in responseHeaders: + self.rate_limiting = ( + # ints expected but sometimes floats returned: https://github.com/PyGithub/PyGithub/pull/2697 + int(float(responseHeaders[Consts.headerRateRemaining])), + int(float(responseHeaders[Consts.headerRateLimit])), + ) + if Consts.headerRateReset in responseHeaders: + # ints expected but sometimes floats returned: https://github.com/PyGithub/PyGithub/pull/2697 + self.rate_limiting_resettime = int(float(responseHeaders[Consts.headerRateReset])) + + if Consts.headerOAuthScopes in responseHeaders: + self.oauth_scopes = responseHeaders[Consts.headerOAuthScopes].split(", ") + + self.DEBUG_ON_RESPONSE(status, responseHeaders, output if isinstance(output, str) else "stream") + + return status, responseHeaders, output + + def __requestRaw( + self, + cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]], + verb: str, + url: str, + requestHeaders: Dict[str, str], + input: Optional[Any], + stream: bool = False, + follow_302_redirect: bool = False, + ) -> Tuple[int, Dict[str, Any], Union[str, object]]: + self.__deferRequest(verb) + + try: + original_cnx = cnx + if cnx is None: + cnx = self.__createConnection() + cnx.request(verb, url, input, requestHeaders, stream) + response = cnx.getresponse() + output = response if stream else response.read() + status = response.status + responseHeaders = {k.lower(): v for k, v in response.getheaders()} + + if input: + if isinstance(input, IOBase): + input.close() + + self.__log(verb, url, requestHeaders, input, status, responseHeaders, output) + + if status == 202 and ( + verb == "GET" or verb == "HEAD" + ): # only for requests that are considered 'safe' in RFC 2616 + time.sleep(Consts.PROCESSING_202_WAIT_TIME) + return self.__requestRaw(original_cnx, verb, url, requestHeaders, input, stream=stream) + + if status == 301 and "location" in responseHeaders: + location = responseHeaders["location"] + o = urllib.parse.urlparse(location) + if o.scheme != self.__scheme: + raise RuntimeError( + f"Github server redirected from {self.__scheme} protocol to {o.scheme}, " + f"please correct your Github server URL via base_url: Github(base_url=...)" + ) + if o.hostname != self.__hostname: + raise RuntimeError( + f"Github server redirected from host {self.__hostname} to {o.hostname}, " + f"please correct your Github server URL via base_url: Github(base_url=...)" + ) + if o.path == url: + port = ":" + str(self.__port) if self.__port is not None else "" + requested_location = f"{self.__scheme}://{self.__hostname}{port}{url}" + raise RuntimeError( + f"Requested {requested_location} but server redirected to {location}, " + f"you may need to correct your Github server URL " + f"via base_url: Github(base_url=...)" + ) + if self._logger.isEnabledFor(logging.INFO): + self._logger.info(f"Following Github server redirection from {url} to {o.path}") + return self.__requestRaw(original_cnx, verb, o.path, requestHeaders, input, stream=stream) + if status == 302 and follow_302_redirect and "location" in responseHeaders: + location = responseHeaders["location"] + o = urllib.parse.urlparse(location) + cnx = self.__customConnection(location) + path = self.__makeAbsoluteUrl(location) + if self._logger.isEnabledFor(logging.DEBUG): + self._logger.debug(f"Following Github server redirection (302) from {url} to {o.path}") + # remove auth to not leak authentication to redirection location + if o.hostname != self.__hostname: + del requestHeaders["Authorization"] + return self.__requestRaw( + cnx, verb, path, requestHeaders, input, stream=stream, follow_302_redirect=True + ) + return status, responseHeaders, output + finally: + # we record the time of this request after it finished + # to defer next request starting from this request's end, not start + self.__recordRequestTime(verb) + + def __deferRequest(self, verb: str) -> None: + # Ensures at least self.__seconds_between_requests seconds have passed since any last request + # and self.__seconds_between_writes seconds have passed since last write request (if verb refers to a write). + # Uses self.__last_requests. + requests = self.__last_requests.values() + writes = [l for v, l in self.__last_requests.items() if v != "GET"] + + last_request = max(requests) if requests else 0 + last_write = max(writes) if writes else 0 + + next_request = (last_request + self.__seconds_between_requests) if self.__seconds_between_requests else 0 + next_write = (last_write + self.__seconds_between_writes) if self.__seconds_between_writes else 0 + + next = next_request if verb == "GET" else max(next_request, next_write) + defer = max(next - datetime.now(timezone.utc).timestamp(), 0) + if defer > 0: + if self.__logger is None: + self.__logger = logging.getLogger(__name__) + self.__logger.debug(f"sleeping {defer}s before next GitHub request") + time.sleep(defer) + + def __recordRequestTime(self, verb: str) -> None: + # Updates self.__last_requests with current timestamp for given verb + self.__last_requests[verb] = datetime.now(timezone.utc).timestamp() + + def __makeAbsoluteUrl(self, url: str) -> str: + # URLs generated locally will be relative to __base_url + # URLs returned from the server will start with __base_url + if url.startswith("/"): + url = f"{self.__prefix}{url}" + else: + o = urllib.parse.urlparse(url) + assert o.hostname in [ + self.__hostname, + "uploads.github.com", + "status.github.com", + "github.com", + "objects.githubusercontent.com", + ], o.hostname + assert o.path.startswith((self.__prefix, self.__graphql_prefix, "/api/", "/login/oauth")), o.path + assert o.port == self.__port, o.port + url = o.path + if o.query != "": + url += f"?{o.query}" + return url + + def __createConnection( + self, hostname: Optional[str] = None + ) -> Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]: + if self.__persist and self.__connection is not None and hostname is not None and hostname == self.__hostname: + return self.__connection + + with self.__connection_lock: + if self.__connection is not None and hostname is not None and hostname == self.__hostname: + if self.__persist: + return self.__connection + if self.__connection is not None: + self.__connection.close() + self.__connection = None + self.__connection = self.__connectionClass( + hostname if hostname is not None else self.__hostname, + self.__port, + retry=self.__retry, + pool_size=self.__pool_size, + timeout=self.__timeout, + verify=self.__verify, + ) + + return self.__connection + + @property + def _logger(self) -> logging.Logger: + if self.__logger is None: + self.__logger = logging.getLogger(__name__) + return self.__logger + + def __log( + self, + verb: str, + url: str, + requestHeaders: Dict[str, str], + input: Optional[Any], + status: Optional[int], + responseHeaders: Dict[str, Any], + output: Optional[Union[str, object]], + ) -> None: + if self._logger.isEnabledFor(logging.DEBUG): + headersForRequest = requestHeaders.copy() + if self.__auth: + self.__auth.mask_authentication(headersForRequest) + self._logger.debug( + "%s %s://%s%s %s %s ==> %i %s %s", + verb, + self.__scheme, + self.__hostname, + url, + headersForRequest, + input, + status, + responseHeaders, + output if isinstance(output, str) else "stream", + ) + + +class WithRequester(Generic[T]): + """ + Mixin class that allows to set a requester. + """ + + __requester: Requester + + def __init__(self) -> None: + self.__requester: Optional[Requester] = None # type: ignore + + @property + def requester(self) -> Requester: + return self.__requester + + def withRequester(self, requester: Requester) -> "WithRequester[T]": + assert isinstance(requester, Requester), requester + self.__requester = requester + return self diff --git a/python_embeded/Lib/site-packages/github/RequiredPullRequestReviews.py b/python_embeded/Lib/site-packages/github/RequiredPullRequestReviews.py new file mode 100644 index 0000000000000000000000000000000000000000..410e0e745c7cc2b1d8258c86fd690445533abdf9 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RequiredPullRequestReviews.py @@ -0,0 +1,146 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Jannis Gebauer # +# Copyright 2017 Simon # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.NamedUser +import github.Team +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + from github.Team import Team + + +class RequiredPullRequestReviews(CompletableGithubObject): + """ + This class represents Required Pull Request Reviews. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#get-pull-request-review-protection + + The OpenAPI schema can be found at + - /components/schemas/protected-branch-pull-request-review + - /components/schemas/protected-branch/properties/required_pull_request_reviews + + """ + + def _initAttributes(self) -> None: + self._dismiss_stale_reviews: Attribute[bool] = NotSet + self._require_code_owner_reviews: Attribute[bool] = NotSet + self._require_last_push_approval: Attribute[bool] = NotSet + self._required_approving_review_count: Attribute[int] = NotSet + self._teams: Attribute[list[Team]] = NotSet + self._users: Attribute[list[NamedUser]] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "url": self._url.value, + "dismiss_stale_reviews": self._dismiss_stale_reviews.value, + "require_code_owner_reviews": self._require_code_owner_reviews.value, + "require_last_push_approval": self._require_last_push_approval.value, + } + ) + + @property + def dismiss_stale_reviews(self) -> bool: + self._completeIfNotSet(self._dismiss_stale_reviews) + return self._dismiss_stale_reviews.value + + @property + def dismissal_teams(self) -> list[Team]: + self._completeIfNotSet(self._teams) + return self._teams.value + + @property + def dismissal_users(self) -> list[NamedUser]: + self._completeIfNotSet(self._users) + return self._users.value + + @property + def require_code_owner_reviews(self) -> bool: + self._completeIfNotSet(self._require_code_owner_reviews) + return self._require_code_owner_reviews.value + + @property + def require_last_push_approval(self) -> bool: + self._completeIfNotSet(self._require_last_push_approval) + return self._require_last_push_approval.value + + @property + def required_approving_review_count(self) -> int: + self._completeIfNotSet(self._required_approving_review_count) + return self._required_approving_review_count.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "dismiss_stale_reviews" in attributes: # pragma no branch + self._dismiss_stale_reviews = self._makeBoolAttribute(attributes["dismiss_stale_reviews"]) + if "dismissal_restrictions" in attributes: # pragma no branch + if "users" in attributes["dismissal_restrictions"]: + self._users = self._makeListOfClassesAttribute( + github.NamedUser.NamedUser, + attributes["dismissal_restrictions"]["users"], + ) + if "teams" in attributes["dismissal_restrictions"]: # pragma no branch + self._teams = self._makeListOfClassesAttribute( + github.Team.Team, attributes["dismissal_restrictions"]["teams"] + ) + if "require_code_owner_reviews" in attributes: # pragma no branch + self._require_code_owner_reviews = self._makeBoolAttribute(attributes["require_code_owner_reviews"]) + if "require_last_push_approval" in attributes: # pragma no branch + self._require_last_push_approval = self._makeBoolAttribute(attributes["require_last_push_approval"]) + if "required_approving_review_count" in attributes: # pragma no branch + self._required_approving_review_count = self._makeIntAttribute( + attributes["required_approving_review_count"] + ) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/RequiredStatusChecks.py b/python_embeded/Lib/site-packages/github/RequiredStatusChecks.py new file mode 100644 index 0000000000000000000000000000000000000000..13bd5d962b40f4e727e9dbb41c736a89cf51c8c0 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/RequiredStatusChecks.py @@ -0,0 +1,92 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class RequiredStatusChecks(CompletableGithubObject): + """ + This class represents Required Status Checks. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#get-status-checks-protection + + The OpenAPI schema can be found at + - /components/schemas/protected-branch-pull-request-review + - /components/schemas/protected-branch-required-status-check + - /components/schemas/status-check-policy + + """ + + def _initAttributes(self) -> None: + self._contexts: Attribute[list[str]] = NotSet + self._strict: Attribute[bool] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"strict": self._strict.value, "url": self._url.value}) + + @property + def contexts(self) -> list[str]: + self._completeIfNotSet(self._contexts) + return self._contexts.value + + @property + def strict(self) -> bool: + self._completeIfNotSet(self._strict) + return self._strict.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "contexts" in attributes: # pragma no branch + self._contexts = self._makeListOfStringsAttribute(attributes["contexts"]) + if "strict" in attributes: # pragma no branch + self._strict = self._makeBoolAttribute(attributes["strict"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/Secret.py b/python_embeded/Lib/site-packages/github/Secret.py new file mode 100644 index 0000000000000000000000000000000000000000..82901aa4f494199537a291d869421d19964f1b76 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Secret.py @@ -0,0 +1,124 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from datetime import datetime +from typing import Any, Dict + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class Secret(CompletableGithubObject): + """ + This class represents a GitHub secret. + + The reference can be found here + https://docs.github.com/en/rest/actions/secrets + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._name: Attribute[str] = NotSet + self._secrets_url: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self.name}) + + @property + def created_at(self) -> datetime: + """ + :type: datetime.datetime + """ + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def name(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._name) + return self._name.value + + @property + def secrets_url(self) -> str: + """ + :type: string + """ + return self._secrets_url.value + + @property + def updated_at(self) -> datetime: + """ + :type: datetime.datetime + """ + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + """ + :type: string + """ + # Construct url from secrets_url and name, if self._url. is not set + if self._url is NotSet: + self._url = self._makeStringAttribute(self.secrets_url + "/" + self.name) + return self._url.value + + def delete(self) -> None: + """ + :calls: `DELETE {secret_url} `_ + :rtype: None + """ + self._requester.requestJsonAndCheck("DELETE", self.url) + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "created_at" in attributes: + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "name" in attributes: + self._name = self._makeStringAttribute(attributes["name"]) + if "secrets_url" in attributes: + self._secrets_url = self._makeStringAttribute(attributes["secrets_url"]) + if "updated_at" in attributes: + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/SecurityAndAnalysis.py b/python_embeded/Lib/site-packages/github/SecurityAndAnalysis.py new file mode 100644 index 0000000000000000000000000000000000000000..00fae0702562b2f2c06954b5d19533fe2ca877d0 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/SecurityAndAnalysis.py @@ -0,0 +1,141 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Nikolay Yurin # +# Copyright 2023 Trim21 # +# Copyright 2024 Caleb McCombs # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +import github.SecurityAndAnalysisFeature +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class SecurityAndAnalysis(NonCompletableGithubObject): + """ + This class represents Security and Analysis Settings. + + The OpenAPI schema can be found at + - /components/schemas/security-and-analysis + + """ + + def _initAttributes(self) -> None: + self._advanced_security: Attribute[github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature] = NotSet + self._dependabot_security_updates: Attribute[ + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature + ] = NotSet + self._secret_scanning: Attribute[github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature] = NotSet + self._secret_scanning_ai_detection: Attribute[str] = NotSet + self._secret_scanning_non_provider_patterns: Attribute[ + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature + ] = NotSet + self._secret_scanning_push_protection: Attribute[ + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature + ] = NotSet + self._secret_scanning_validity_checks: Attribute[ + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature + ] = NotSet + + def __repr__(self) -> str: + repr_attributes = { + "advanced_security": repr(self._advanced_security.value), + "dependabot_security_updates": repr(self._dependabot_security_updates.value), + "secret_scanning": repr(self._secret_scanning.value), + "secret_scanning_non_provider_patterns": repr(self._secret_scanning_non_provider_patterns.value), + "secret_scanning_push_protection": repr(self._secret_scanning_push_protection.value), + "secret_scanning_validity_checks": repr(self._secret_scanning_validity_checks.value), + } + + return self.get__repr__(repr_attributes) + + @property + def advanced_security(self) -> github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature: + return self._advanced_security.value + + @property + def dependabot_security_updates(self) -> github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature: + return self._dependabot_security_updates.value + + @property + def secret_scanning(self) -> github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature: + return self._secret_scanning.value + + @property + def secret_scanning_ai_detection(self) -> str: + return self._secret_scanning_ai_detection.value + + @property + def secret_scanning_non_provider_patterns(self) -> github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature: + return self._secret_scanning_non_provider_patterns.value + + @property + def secret_scanning_push_protection(self) -> github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature: + return self._secret_scanning_push_protection.value + + @property + def secret_scanning_validity_checks(self) -> github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature: + return self._secret_scanning_validity_checks.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "advanced_security" in attributes: # pragma no branch + self._advanced_security = self._makeClassAttribute( + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature, attributes["advanced_security"] + ) + if "dependabot_security_updates" in attributes: # pragma no branch + self._dependabot_security_updates = self._makeClassAttribute( + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature, attributes["dependabot_security_updates"] + ) + if "secret_scanning" in attributes: # pragma no branch + self._secret_scanning = self._makeClassAttribute( + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature, attributes["secret_scanning"] + ) + if "secret_scanning_ai_detection" in attributes: # pragma no branch + self._secret_scanning_ai_detection = self._makeStringAttribute(attributes["secret_scanning_ai_detection"]) + if "secret_scanning_non_provider_patterns" in attributes: # pragma no branch + self._secret_scanning_non_provider_patterns = self._makeClassAttribute( + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature, + attributes["secret_scanning_non_provider_patterns"], + ) + if "secret_scanning_push_protection" in attributes: # pragma no branch + self._secret_scanning_push_protection = self._makeClassAttribute( + github.SecurityAndAnalysisFeature.SecurityAndAnalysisFeature, + attributes["secret_scanning_push_protection"], + ) diff --git a/python_embeded/Lib/site-packages/github/SecurityAndAnalysisFeature.py b/python_embeded/Lib/site-packages/github/SecurityAndAnalysisFeature.py new file mode 100644 index 0000000000000000000000000000000000000000..6ca84191a3f18bd65e776d1db7787b58cca61855 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/SecurityAndAnalysisFeature.py @@ -0,0 +1,70 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Caleb McCombs # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class SecurityAndAnalysisFeature(NonCompletableGithubObject): + """ + This class represents a Security and Analysis feature status. + + The OpenAPI schema can be found at + - /components/schemas/security-and-analysis/properties/advanced_security + - /components/schemas/security-and-analysis/properties/dependabot_security_updates + - /components/schemas/security-and-analysis/properties/secret_scanning + - /components/schemas/security-and-analysis/properties/secret_scanning_non_provider_patterns + - /components/schemas/security-and-analysis/properties/secret_scanning_push_protection + + """ + + def _initAttributes(self) -> None: + self._status: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"status": self._status.value}) + + @property + def status(self) -> str: + return self._status.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) diff --git a/python_embeded/Lib/site-packages/github/SelfHostedActionsRunner.py b/python_embeded/Lib/site-packages/github/SelfHostedActionsRunner.py new file mode 100644 index 0000000000000000000000000000000000000000..134b1c50486bd1892d7a2ed811a84e02c86b787d --- /dev/null +++ b/python_embeded/Lib/site-packages/github/SelfHostedActionsRunner.py @@ -0,0 +1,113 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 Victor Zeng # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class SelfHostedActionsRunner(NonCompletableGithubObject): + """ + This class represents Self-hosted GitHub Actions Runners. + + The reference can be found at + https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#self-hosted-runners + + The OpenAPI schema can be found at + - /components/schemas/runner + + """ + + def _initAttributes(self) -> None: + self._busy: Attribute[bool] = NotSet + self._id: Attribute[int] = NotSet + self._labels: Attribute[list[dict[str, int | str]]] = NotSet + self._name: Attribute[str] = NotSet + self._os: Attribute[str] = NotSet + self._runner_group_id: Attribute[int] = NotSet + self._status: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value}) + + @property + def busy(self) -> bool: + return self._busy.value + + @property + def id(self) -> int: + return self._id.value + + @property + def labels(self) -> list[dict[str, int | str]]: + return self._labels.value + + @property + def name(self) -> str: + return self._name.value + + @property + def os(self) -> str: + return self._os.value + + @property + def runner_group_id(self) -> int: + return self._runner_group_id.value + + @property + def status(self) -> str: + return self._status.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "busy" in attributes: + self._busy = self._makeBoolAttribute(attributes["busy"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "labels" in attributes: + self._labels = self._makeListOfDictsAttribute(attributes["labels"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "os" in attributes: # pragma no branch + self._os = self._makeStringAttribute(attributes["os"]) + if "runner_group_id" in attributes: # pragma no branch + self._runner_group_id = self._makeIntAttribute(attributes["runner_group_id"]) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) diff --git a/python_embeded/Lib/site-packages/github/SourceImport.py b/python_embeded/Lib/site-packages/github/SourceImport.py new file mode 100644 index 0000000000000000000000000000000000000000..6c73bd5b649c0b9e2c588b88c48cdb1c856a65b5 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/SourceImport.py @@ -0,0 +1,255 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2018 Hayden Fuss # +# Copyright 2018 Wan Liuyang # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github import Consts +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class SourceImport(CompletableGithubObject): + """ + This class represents SourceImports. + + The reference can be found here + https://docs.github.com/en/rest/reference/migrations#source-imports + + The OpenAPI schema can be found at + - /components/schemas/import + + """ + + def _initAttributes(self) -> None: + self._authors_count: Attribute[int] = NotSet + self._authors_url: Attribute[str] = NotSet + self._commit_count: Attribute[int] = NotSet + self._error_message: Attribute[str] = NotSet + self._failed_step: Attribute[str] = NotSet + self._has_large_files: Attribute[bool] = NotSet + self._html_url: Attribute[str] = NotSet + self._import_percent: Attribute[int] = NotSet + self._large_files_count: Attribute[int] = NotSet + self._large_files_size: Attribute[int] = NotSet + self._message: Attribute[str] = NotSet + self._project_choices: Attribute[list[dict[str, Any]]] = NotSet + self._push_percent: Attribute[int] = NotSet + self._repository_url: Attribute[str] = NotSet + self._status: Attribute[str] = NotSet + self._status_text: Attribute[str] = NotSet + self._svc_root: Attribute[str] = NotSet + self._svn_root: Attribute[str] = NotSet + self._tfvc_project: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + self._use_lfs: Attribute[str] = NotSet + self._vcs: Attribute[str] = NotSet + self._vcs_url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "vcs_url": self._vcs_url.value, + "repository_url": self._repository_url.value, + "status": self._status.value, + "url": self._url.value, + } + ) + + @property + def authors_count(self) -> int: + self._completeIfNotSet(self._authors_count) + return self._authors_count.value + + @property + def authors_url(self) -> str: + self._completeIfNotSet(self._authors_url) + return self._authors_url.value + + @property + def commit_count(self) -> int: + self._completeIfNotSet(self._commit_count) + return self._commit_count.value + + @property + def error_message(self) -> str: + self._completeIfNotSet(self._error_message) + return self._error_message.value + + @property + def failed_step(self) -> str: + self._completeIfNotSet(self._failed_step) + return self._failed_step.value + + @property + def has_large_files(self) -> bool: + self._completeIfNotSet(self._has_large_files) + return self._has_large_files.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def import_percent(self) -> int: + self._completeIfNotSet(self._import_percent) + return self._import_percent.value + + @property + def large_files_count(self) -> int: + self._completeIfNotSet(self._large_files_count) + return self._large_files_count.value + + @property + def large_files_size(self) -> int: + self._completeIfNotSet(self._large_files_size) + return self._large_files_size.value + + @property + def message(self) -> str: + self._completeIfNotSet(self._message) + return self._message.value + + @property + def project_choices(self) -> list[dict[str, Any]]: + self._completeIfNotSet(self._project_choices) + return self._project_choices.value + + @property + def push_percent(self) -> int: + self._completeIfNotSet(self._push_percent) + return self._push_percent.value + + @property + def repository_url(self) -> str: + self._completeIfNotSet(self._repository_url) + return self._repository_url.value + + @property + def status(self) -> str: + self._completeIfNotSet(self._status) + return self._status.value + + @property + def status_text(self) -> str: + self._completeIfNotSet(self._status_text) + return self._status_text.value + + @property + def svc_root(self) -> str: + self._completeIfNotSet(self._svc_root) + return self._svc_root.value + + @property + def svn_root(self) -> str: + self._completeIfNotSet(self._svn_root) + return self._svn_root.value + + @property + def tfvc_project(self) -> str: + self._completeIfNotSet(self._tfvc_project) + return self._tfvc_project.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def use_lfs(self) -> str: + self._completeIfNotSet(self._use_lfs) + return self._use_lfs.value + + @property + def vcs(self) -> str: + self._completeIfNotSet(self._vcs) + return self._vcs.value + + @property + def vcs_url(self) -> str: + self._completeIfNotSet(self._vcs_url) + return self._vcs_url.value + + def update(self, additional_headers: None | dict[str, Any] = None) -> bool: + import_header = {"Accept": Consts.mediaTypeImportPreview} + return super().update(additional_headers=import_header) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "authors_count" in attributes: # pragma no branch + self._authors_count = self._makeIntAttribute(attributes["authors_count"]) + if "authors_url" in attributes: # pragma no branch + self._authors_url = self._makeStringAttribute(attributes["authors_url"]) + if "commit_count" in attributes: # pragma no branch + self._commit_count = self._makeIntAttribute(attributes["commit_count"]) + if "error_message" in attributes: # pragma no branch + self._error_message = self._makeStringAttribute(attributes["error_message"]) + if "failed_step" in attributes: # pragma no branch + self._failed_step = self._makeStringAttribute(attributes["failed_step"]) + if "has_large_files" in attributes: # pragma no branch + self._has_large_files = self._makeBoolAttribute(attributes["has_large_files"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "import_percent" in attributes: # pragma no branch + self._import_percent = self._makeIntAttribute(attributes["import_percent"]) + if "large_files_count" in attributes: # pragma no branch + self._large_files_count = self._makeIntAttribute(attributes["large_files_count"]) + if "large_files_size" in attributes: # pragma no branch + self._large_files_size = self._makeIntAttribute(attributes["large_files_size"]) + if "message" in attributes: # pragma no branch + self._message = self._makeStringAttribute(attributes["message"]) + if "project_choices" in attributes: # pragma no branch + self._project_choices = self._makeListOfDictsAttribute(attributes["project_choices"]) + if "push_percent" in attributes: # pragma no branch + self._push_percent = self._makeIntAttribute(attributes["push_percent"]) + if "repository_url" in attributes: # pragma no branch + self._repository_url = self._makeStringAttribute(attributes["repository_url"]) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) + if "status_text" in attributes: # pragma no branch + self._status_text = self._makeStringAttribute(attributes["status_text"]) + if "svc_root" in attributes: # pragma no branch + self._svc_root = self._makeStringAttribute(attributes["svc_root"]) + if "svn_root" in attributes: # pragma no branch + self._svn_root = self._makeStringAttribute(attributes["svn_root"]) + if "tfvc_project" in attributes: # pragma no branch + self._tfvc_project = self._makeStringAttribute(attributes["tfvc_project"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "use_lfs" in attributes: # pragma no branch + self._use_lfs = self._makeStringAttribute(attributes["use_lfs"]) + if "vcs" in attributes: # pragma no branch + self._vcs = self._makeStringAttribute(attributes["vcs"]) + if "vcs_url" in attributes: # pragma no branch + self._vcs_url = self._makeStringAttribute(attributes["vcs_url"]) diff --git a/python_embeded/Lib/site-packages/github/Stargazer.py b/python_embeded/Lib/site-packages/github/Stargazer.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d3fe7b623625ed9094c125e81cd06f6185e6fb --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Stargazer.py @@ -0,0 +1,87 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Dan Vanderkam # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import github.NamedUser +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.NamedUser import NamedUser + + +class Stargazer(NonCompletableGithubObject): + """ + This class represents Stargazers. + + The reference can be found here + https://docs.github.com/en/rest/reference/activity#starring + + """ + + def _initAttributes(self) -> None: + self._starred_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._user: Attribute[NamedUser] = NotSet + + def __repr__(self) -> str: + # this is not a type error, just we didn't type `NamedUser` yet. + # enable type checker here after we typed attribute of `NamedUser` + return self.get__repr__({"user": self._user.value._login.value}) # type: ignore + + @property + def starred_at(self) -> datetime: + return self._starred_at.value + + @property + def user(self) -> NamedUser: + return self._user.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "starred_at" in attributes: + self._starred_at = self._makeDatetimeAttribute(attributes["starred_at"]) + if "user" in attributes: + self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"]) diff --git a/python_embeded/Lib/site-packages/github/StatsCodeFrequency.py b/python_embeded/Lib/site-packages/github/StatsCodeFrequency.py new file mode 100644 index 0000000000000000000000000000000000000000..871317a4960de015e224a7813919b5910d673f27 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/StatsCodeFrequency.py @@ -0,0 +1,79 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class StatsCodeFrequency(NonCompletableGithubObject): + """ + This class represents statistics of StatsCodeFrequencies. + + The reference can be found here + https://docs.github.com/en/rest/metrics/statistics?apiVersion=2022-11-28#get-the-weekly-commit-activity + + The OpenAPI schema can be found at + - /components/schemas/code-frequency-stat + + """ + + def _initAttributes(self) -> None: + self._additions: Attribute[int] = NotSet + self._deletions: Attribute[int] = NotSet + self._week: Attribute[datetime] = NotSet + + @property + def additions(self) -> int: + return self._additions.value + + @property + def deletions(self) -> int: + return self._deletions.value + + @property + def week(self) -> datetime: + return self._week.value + + def _useAttributes(self, attributes: tuple[int, int, int]) -> None: + self._week = self._makeTimestampAttribute(attributes[0]) + self._additions = self._makeIntAttribute(attributes[1]) + self._deletions = self._makeIntAttribute(attributes[2]) diff --git a/python_embeded/Lib/site-packages/github/StatsCommitActivity.py b/python_embeded/Lib/site-packages/github/StatsCommitActivity.py new file mode 100644 index 0000000000000000000000000000000000000000..63ece53fb8d112bf635d15093dc041d2efedcf5a --- /dev/null +++ b/python_embeded/Lib/site-packages/github/StatsCommitActivity.py @@ -0,0 +1,82 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from datetime import datetime +from typing import Any, Dict + +import github.GithubObject +from github.GithubObject import Attribute + + +class StatsCommitActivity(github.GithubObject.NonCompletableGithubObject): + """ + This class represents StatsCommitActivities. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#get-the-last-year-of-commit-activity + + The OpenAPI schema can be found at + - /components/schemas/commit-activity + + """ + + def _initAttributes(self) -> None: + self._days: Attribute[int] = github.GithubObject.NotSet + self._total: Attribute[int] = github.GithubObject.NotSet + self._week: Attribute[datetime] = github.GithubObject.NotSet + + @property + def days(self) -> int: + return self._days.value + + @property + def total(self) -> int: + return self._total.value + + @property + def week(self) -> datetime: + return self._week.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "days" in attributes: # pragma no branch + self._days = self._makeListOfIntsAttribute(attributes["days"]) + if "total" in attributes: # pragma no branch + self._total = self._makeIntAttribute(attributes["total"]) + if "week" in attributes: # pragma no branch + self._week = self._makeTimestampAttribute(attributes["week"]) diff --git a/python_embeded/Lib/site-packages/github/StatsContributor.py b/python_embeded/Lib/site-packages/github/StatsContributor.py new file mode 100644 index 0000000000000000000000000000000000000000..76da7d745c0e1d183d59e5fd459d7870ba1d54ba --- /dev/null +++ b/python_embeded/Lib/site-packages/github/StatsContributor.py @@ -0,0 +1,124 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.NamedUser +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class StatsContributor(NonCompletableGithubObject): + """ + This class represents StatsContributors. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#get-all-contributor-commit-activity + + The OpenAPI schema can be found at + - /components/schemas/contributor-activity + + """ + + class Week(NonCompletableGithubObject): + """ + This class represents weekly statistics of a contributor. + + The OpenAPI schema can be found at + - /components/schemas/contributor-activity/properties/weeks/items + + """ + + def _initAttributes(self) -> None: + self._a: Attribute[int] = NotSet + self._c: Attribute[int] = NotSet + self._d: Attribute[int] = NotSet + self._w: Attribute[datetime] = NotSet + + @property + def a(self) -> int: + return self._a.value + + @property + def c(self) -> int: + return self._c.value + + @property + def d(self) -> int: + return self._d.value + + @property + def w(self) -> datetime: + return self._w.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "a" in attributes: # pragma no branch + self._a = self._makeIntAttribute(attributes["a"]) + if "c" in attributes: # pragma no branch + self._c = self._makeIntAttribute(attributes["c"]) + if "d" in attributes: # pragma no branch + self._d = self._makeIntAttribute(attributes["d"]) + if "w" in attributes: # pragma no branch + self._w = self._makeTimestampAttribute(attributes["w"]) + + def _initAttributes(self) -> None: + self._author: Attribute[github.NamedUser.NamedUser] = NotSet + self._total: Attribute[int] = NotSet + self._weeks: Attribute[list[StatsContributor.Week]] = NotSet + + @property + def author(self) -> github.NamedUser.NamedUser: + return self._author.value + + @property + def total(self) -> int: + return self._total.value + + @property + def weeks(self) -> list[Week]: + return self._weeks.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "author" in attributes: # pragma no branch + self._author = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["author"]) + if "total" in attributes: # pragma no branch + self._total = self._makeIntAttribute(attributes["total"]) + if "weeks" in attributes: # pragma no branch + self._weeks = self._makeListOfClassesAttribute(self.Week, attributes["weeks"]) diff --git a/python_embeded/Lib/site-packages/github/StatsParticipation.py b/python_embeded/Lib/site-packages/github/StatsParticipation.py new file mode 100644 index 0000000000000000000000000000000000000000..1ddb1207a0b112b32e71f3278985302f9ad3eae5 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/StatsParticipation.py @@ -0,0 +1,76 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class StatsParticipation(NonCompletableGithubObject): + """ + This class represents StatsParticipations. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#get-the-weekly-commit-count + + The OpenAPI schema can be found at + - /components/schemas/participation-stats + + """ + + def _initAttributes(self) -> None: + self._all: Attribute[list[int]] = NotSet + self._owner: Attribute[list[int]] = NotSet + + @property + def all(self) -> list[int]: + return self._all.value + + @property + def owner(self) -> list[int]: + return self._owner.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "all" in attributes: # pragma no branch + self._all = self._makeListOfIntsAttribute(attributes["all"]) + if "owner" in attributes: # pragma no branch + self._owner = self._makeListOfIntsAttribute(attributes["owner"]) diff --git a/python_embeded/Lib/site-packages/github/StatsPunchCard.py b/python_embeded/Lib/site-packages/github/StatsPunchCard.py new file mode 100644 index 0000000000000000000000000000000000000000..97f0fe9069dae5b6b0f2ab81db9cda5b01331b2a --- /dev/null +++ b/python_embeded/Lib/site-packages/github/StatsPunchCard.py @@ -0,0 +1,72 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Dominic Davis-Foster # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from typing import Any, Dict, Tuple + +import github.GithubObject +import github.NamedUser # TODO remove unused + + +class StatsPunchCard(github.GithubObject.NonCompletableGithubObject): + """ + This class represents StatsPunchCards. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#get-the-hourly-commit-count-for-each-day + + The OpenAPI schema can be found at + - /components/schemas/code-frequency-stat + + """ + + _dict: Dict[Tuple[int, int], int] + + def _initAttributes(self) -> None: + self._dict = {} + + def get(self, day: int, hour: int) -> int: + """ + Get a specific element. + """ + return self._dict[(day, hour)] + + def _useAttributes(self, attributes: Any) -> None: + for day, hour, commits in attributes: + self._dict[(day, hour)] = commits diff --git a/python_embeded/Lib/site-packages/github/Tag.py b/python_embeded/Lib/site-packages/github/Tag.py new file mode 100644 index 0000000000000000000000000000000000000000..c37a828318e98c28d01dec3b75895434e2362665 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Tag.py @@ -0,0 +1,106 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.Commit +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.Commit import Commit + + +class Tag(NonCompletableGithubObject): + """ + This class represents Tags. + + The reference can be found here + https://docs.github.com/en/rest/reference/repos#list-repository-tags + + The OpenAPI schema can be found at + - /components/schemas/tag + + """ + + def _initAttributes(self) -> None: + self._commit: Attribute[Commit] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._tarball_url: Attribute[str] = NotSet + self._zipball_url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value, "commit": self._commit.value}) + + @property + def commit(self) -> Commit: + return self._commit.value + + @property + def name(self) -> str: + return self._name.value + + @property + def node_id(self) -> str: + return self._node_id.value + + @property + def tarball_url(self) -> str: + return self._tarball_url.value + + @property + def zipball_url(self) -> str: + return self._zipball_url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "commit" in attributes: # pragma no branch + self._commit = self._makeClassAttribute(github.Commit.Commit, attributes["commit"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "tarball_url" in attributes: # pragma no branch + self._tarball_url = self._makeStringAttribute(attributes["tarball_url"]) + if "zipball_url" in attributes: # pragma no branch + self._zipball_url = self._makeStringAttribute(attributes["zipball_url"]) diff --git a/python_embeded/Lib/site-packages/github/Team.py b/python_embeded/Lib/site-packages/github/Team.py new file mode 100644 index 0000000000000000000000000000000000000000..6e32e9d6e7f1142e621c7700cba32d5df54d1940 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Team.py @@ -0,0 +1,521 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Jan Orel # +# Copyright 2014 Vincent Jacques # +# Copyright 2015 Aron Culotta # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2016 mattjmorrison # +# Copyright 2018 Isuru Fernando # +# Copyright 2018 Jacopo Notarstefano # +# Copyright 2018 James D'Amato # +# Copyright 2018 Maarten Fonville # +# Copyright 2018 Manu Hortet # +# Copyright 2018 Michał Górny # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Tim Boring # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Shibasis Patel # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Adrian Bridgett <58699309+tl-adrian-bridgett@users.noreply.github.com># +# Copyright 2020 Andy Grunwald # +# Copyright 2020 Gilad Shefer # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 Tal Machani <12785464+talmachani@users.noreply.github.com> # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2021 秋葉 # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Kevin Grandjean # +# Copyright 2023 Mark Amery # +# Copyright 2023 Trim21 # +# Copyright 2024 Andrii Kezikov # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +import urllib.parse +from datetime import datetime +from typing import TYPE_CHECKING, Any + +from deprecated import deprecated + +import github.NamedUser +import github.Organization +import github.PaginatedList +import github.Permissions +import github.Repository +import github.TeamDiscussion +from github import Consts +from github.GithubException import UnknownObjectException +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt + +if TYPE_CHECKING: + from github.Membership import Membership + from github.NamedUser import NamedUser + from github.Organization import Organization + from github.PaginatedList import PaginatedList + from github.Permissions import Permissions + from github.Repository import Repository + from github.TeamDiscussion import TeamDiscussion + + +class Team(CompletableGithubObject): + """ + This class represents Teams. + + The reference can be found here + https://docs.github.com/en/rest/reference/teams + + The OpenAPI schema can be found at + - /components/schemas/nullable-team-simple + - /components/schemas/team + - /components/schemas/team-full + - /components/schemas/team-simple + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._description: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._ldap_dn: Attribute[str] = NotSet + self._members_count: Attribute[int] = NotSet + self._members_url: Attribute[str] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._notification_setting: Attribute[str] = NotSet + self._organization: Attribute[Organization] = NotSet + self._parent: Attribute[github.Team.Team] = NotSet + self._permission: Attribute[str] = NotSet + self._permissions: Attribute[Permissions] = NotSet + self._privacy: Attribute[str] = NotSet + self._repos_count: Attribute[int] = NotSet + self._repositories_url: Attribute[str] = NotSet + self._slug: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "name": self._name.value}) + + @property + def _identity(self) -> int: + return self.id + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def description(self) -> str: + self._completeIfNotSet(self._description) + return self._description.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def ldap_dn(self) -> str: + self._completeIfNotSet(self._ldap_dn) + return self._ldap_dn.value + + @property + def members_count(self) -> int: + self._completeIfNotSet(self._members_count) + return self._members_count.value + + @property + def members_url(self) -> str: + self._completeIfNotSet(self._members_url) + return self._members_url.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def notification_setting(self) -> str: + self._completeIfNotSet(self._notification_setting) + return self._notification_setting.value + + @property + def organization(self) -> Organization: + self._completeIfNotSet(self._organization) + return self._organization.value + + @property + def parent(self) -> Team: + self._completeIfNotSet(self._parent) + return self._parent.value + + @property + def permission(self) -> str: + self._completeIfNotSet(self._permission) + return self._permission.value + + @property + def permissions(self) -> Permissions: + self._completeIfNotSet(self._permissions) + return self._permissions.value + + @property + def privacy(self) -> str: + self._completeIfNotSet(self._privacy) + return self._privacy.value + + @property + def repos_count(self) -> int: + self._completeIfNotSet(self._repos_count) + return self._repos_count.value + + @property + def repositories_url(self) -> str: + self._completeIfNotSet(self._repositories_url) + return self._repositories_url.value + + @property + def slug(self) -> str: + self._completeIfNotSet(self._slug) + return self._slug.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def add_to_members(self, member: NamedUser) -> None: + """ + This API call is deprecated. Use `add_membership` instead. + https://docs.github.com/en/rest/reference/teams#add-or-update-team-membership-for-a-user-legacy + + :calls: `PUT /teams/{id}/members/{user} `_ + """ + assert isinstance(member, github.NamedUser.NamedUser), member + headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/members/{member._identity}") + + def add_membership(self, member: NamedUser, role: Opt[str] = NotSet) -> None: + """ + :calls: `PUT /teams/{id}/memberships/{user} `_ + """ + assert isinstance(member, github.NamedUser.NamedUser), member + assert role is NotSet or isinstance(role, str), role + if role is not NotSet: + assert role in ["member", "maintainer"] + put_parameters = { + "role": role, + } + else: + put_parameters = { + "role": "member", + } + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/memberships/{member._identity}", input=put_parameters + ) + + def get_team_membership(self, member: str | NamedUser) -> Membership: + """ + :calls: `GET /orgs/{org}/memberships/team/{team_id}/{username} `_ + """ + assert isinstance(member, str) or isinstance(member, github.NamedUser.NamedUser), member + if isinstance(member, github.NamedUser.NamedUser): + member = member._identity + else: + member = urllib.parse.quote(member) + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/memberships/{member}") + return github.Membership.Membership(self._requester, headers, data, completed=True) + + def add_to_repos(self, repo: Repository) -> None: + """ + :calls: `PUT /teams/{id}/repos/{org}/{repo} `_ + """ + assert isinstance(repo, github.Repository.Repository), repo + headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/repos/{repo._identity}") + + def get_repo_permission(self, repo: Repository) -> Permissions | None: + """ + :calls: `GET /teams/{id}/repos/{org}/{repo} `_ + """ + assert isinstance(repo, github.Repository.Repository) or isinstance(repo, str), repo + if isinstance(repo, github.Repository.Repository): + repo = repo._identity # type: ignore + else: + repo = urllib.parse.quote(repo) + try: + headers, data = self._requester.requestJsonAndCheck( + "GET", + f"{self.url}/repos/{repo}", + headers={"Accept": Consts.teamRepositoryPermissions}, + ) + return github.Permissions.Permissions(self._requester, headers, data["permissions"]) + except UnknownObjectException: + return None + + @deprecated( + reason=""" + Team.set_repo_permission() is deprecated, use Team.update_team_repository() instead. + """ + ) + def set_repo_permission(self, repo: Repository, permission: str) -> None: + """ + :calls: `PUT /teams/{id}/repos/{org}/{repo} `_ + :param repo: :class:`github.Repository.Repository` + :param permission: string + :rtype: None + """ + + assert isinstance(repo, github.Repository.Repository), repo + put_parameters = { + "permission": permission, + } + headers, data = self._requester.requestJsonAndCheck( + "PUT", f"{self.url}/repos/{repo._identity}", input=put_parameters + ) + + def update_team_repository(self, repo: Repository, permission: str) -> bool: + """ + :calls: `PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo} `_ + """ + assert isinstance(repo, github.Repository.Repository) or isinstance(repo, str), repo + assert isinstance(permission, str), permission + if isinstance(repo, github.Repository.Repository): + repo_url_param = repo._identity + else: + repo_url_param = urllib.parse.quote(repo) + put_parameters = { + "permission": permission, + } + status, _, _ = self._requester.requestJson( + "PUT", + f"{self.organization.url}/teams/{self.slug}/repos/{repo_url_param}", + input=put_parameters, + ) + return status == 204 + + def delete(self) -> None: + """ + :calls: `DELETE /teams/{id} `_ + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def edit( + self, + name: str, + description: Opt[str] = NotSet, + permission: Opt[str] = NotSet, + privacy: Opt[str] = NotSet, + parent_team_id: Opt[int] = NotSet, + notification_setting: Opt[str] = NotSet, + ) -> None: + """ + :calls: `PATCH /teams/{id} `_ + """ + assert isinstance(name, str), name + assert description is NotSet or isinstance(description, str), description + assert permission is NotSet or isinstance(permission, str), permission + assert privacy is NotSet or isinstance(privacy, str), privacy + assert parent_team_id is NotSet or isinstance(parent_team_id, (int, type(None))), parent_team_id + assert notification_setting in ["notifications_enabled", "notifications_disabled", NotSet], notification_setting + post_parameters = NotSet.remove_unset_items( + { + "name": name, + "description": description, + "permission": permission, + "privacy": privacy, + "parent_team_id": parent_team_id, + "notification_setting": notification_setting, + } + ) + + headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters) + self._useAttributes(data) + + def get_teams(self) -> PaginatedList[Team]: + """ + :calls: `GET /teams/{id}/teams `_ + """ + return github.PaginatedList.PaginatedList( + github.Team.Team, + self._requester, + f"{self.url}/teams", + None, + ) + + def get_discussions(self) -> PaginatedList[TeamDiscussion]: + """ + :calls: `GET /teams/{id}/discussions `_ + """ + return github.PaginatedList.PaginatedList( + github.TeamDiscussion.TeamDiscussion, + self._requester, + f"{self.url}/discussions", + None, + headers={"Accept": Consts.mediaTypeTeamDiscussionsPreview}, + ) + + def get_members(self, role: Opt[str] = NotSet) -> PaginatedList[NamedUser]: + """ + :calls: `GET /teams/{id}/members `_ + """ + assert role is NotSet or isinstance(role, str), role + url_parameters: dict[str, Any] = {} + if role is not NotSet: + assert role in ["member", "maintainer", "all"] + url_parameters["role"] = role + return github.PaginatedList.PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/members", + url_parameters, + ) + + def get_repos(self) -> PaginatedList[Repository]: + """ + :calls: `GET /teams/{id}/repos `_ + """ + return github.PaginatedList.PaginatedList( + github.Repository.Repository, self._requester, f"{self.url}/repos", None + ) + + def invitations(self) -> PaginatedList[NamedUser]: + """ + :calls: `GET /teams/{id}/invitations `_ + """ + return github.PaginatedList.PaginatedList( + github.NamedUser.NamedUser, + self._requester, + f"{self.url}/invitations", + None, + headers={"Accept": Consts.mediaTypeOrganizationInvitationPreview}, + ) + + def has_in_members(self, member: NamedUser) -> bool: + """ + :calls: `GET /teams/{id}/members/{user} `_ + """ + assert isinstance(member, github.NamedUser.NamedUser), member + status, headers, data = self._requester.requestJson("GET", f"{self.url}/members/{member._identity}") + return status == 204 + + def has_in_repos(self, repo: Repository) -> bool: + """ + :calls: `GET /teams/{id}/repos/{owner}/{repo} `_ + """ + assert isinstance(repo, github.Repository.Repository), repo + status, headers, data = self._requester.requestJson("GET", f"{self.url}/repos/{repo._identity}") + return status == 204 + + def remove_membership(self, member: NamedUser) -> None: + """ + :calls: `DELETE /teams/{team_id}/memberships/{username} `_ + """ + assert isinstance(member, github.NamedUser.NamedUser), member + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/memberships/{member._identity}") + + def remove_from_members(self, member: NamedUser) -> None: + """ + This API call is deprecated. Use `remove_membership` instead: + https://docs.github.com/en/rest/reference/teams#add-or-update-team-membership-for-a-user-legacy + + :calls: `DELETE /teams/{id}/members/{user} `_ + """ + assert isinstance(member, github.NamedUser.NamedUser), member + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/members/{member._identity}") + + def remove_from_repos(self, repo: Repository) -> None: + """ + :calls: `DELETE /teams/{id}/repos/{owner}/{repo} `_ + """ + assert isinstance(repo, github.Repository.Repository), repo + headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/repos/{repo._identity}") + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "html_url" in attributes: + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "ldap_dn" in attributes: # pragma no branch + self._ldap_dn = self._makeStringAttribute(attributes["ldap_dn"]) + if "members_count" in attributes: # pragma no branch + self._members_count = self._makeIntAttribute(attributes["members_count"]) + if "members_url" in attributes: # pragma no branch + self._members_url = self._makeStringAttribute(attributes["members_url"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "notification_setting" in attributes: # pragma no branch + self._notification_setting = self._makeStringAttribute(attributes["notification_setting"]) + if "organization" in attributes: # pragma no branch + self._organization = self._makeClassAttribute(github.Organization.Organization, attributes["organization"]) + if "parent" in attributes: # pragma no branch + self._parent = self._makeClassAttribute(github.Team.Team, attributes["parent"]) + if "permission" in attributes: # pragma no branch + self._permission = self._makeStringAttribute(attributes["permission"]) + if "permissions" in attributes: # pragma no branch + self._permissions = self._makeClassAttribute(github.Permissions.Permissions, attributes["permissions"]) + if "privacy" in attributes: # pragma no branch + self._privacy = self._makeStringAttribute(attributes["privacy"]) + if "repos_count" in attributes: # pragma no branch + self._repos_count = self._makeIntAttribute(attributes["repos_count"]) + if "repositories_url" in attributes: # pragma no branch + self._repositories_url = self._makeStringAttribute(attributes["repositories_url"]) + if "slug" in attributes: # pragma no branch + self._slug = self._makeStringAttribute(attributes["slug"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/TeamDiscussion.py b/python_embeded/Lib/site-packages/github/TeamDiscussion.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e0ca5ca4539d03c08c9f12f73322f226cc2613 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/TeamDiscussion.py @@ -0,0 +1,130 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Chris McBride # +# Copyright 2017 Simon # +# Copyright 2018 Benoit Latinier # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 Yossarian King # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import Any + +from github.DiscussionBase import DiscussionBase +from github.GithubObject import Attribute, NotSet + + +class TeamDiscussion(DiscussionBase): + """ + This class represents TeamDiscussions. + + The reference can be found here + https://docs.github.com/en/rest/reference/teams#discussions + + """ + + def _initAttributes(self) -> None: + super()._initAttributes() + self._body_version: Attribute[str] = NotSet + self._comments_count: Attribute[int] = NotSet + self._comments_url: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._pinned: Attribute[bool] = NotSet + self._private: Attribute[bool] = NotSet + self._team_url: Attribute[str] = NotSet + + @property + def body_version(self) -> str: + self._completeIfNotSet(self._body_version) + return self._body_version.value + + @property + def comments_count(self) -> int: + self._completeIfNotSet(self._comments_count) + return self._comments_count.value + + @property + def comments_url(self) -> str: + self._completeIfNotSet(self._comments_url) + return self._comments_url.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def pinned(self) -> bool: + self._completeIfNotSet(self._pinned) + return self._pinned.value + + @property + def private(self) -> bool: + self._completeIfNotSet(self._private) + return self._private.value + + @property + def team_url(self) -> str: + self._completeIfNotSet(self._team_url) + return self._team_url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + super()._useAttributes(attributes) + if "body_version" in attributes: # pragma no branch + self._body_version = self._makeStringAttribute(attributes["body_version"]) + if "comments_count" in attributes: # pragma no branch + self._comments_count = self._makeIntAttribute(attributes["comments_count"]) + if "comments_url" in attributes: # pragma no branch + self._comments_url = self._makeStringAttribute(attributes["comments_url"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "pinned" in attributes: # pragma no branch + self._pinned = self._makeBoolAttribute(attributes["pinned"]) + if "private" in attributes: # pragma no branch + self._private = self._makeBoolAttribute(attributes["private"]) + if "team_url" in attributes: # pragma no branch + self._team_url = self._makeStringAttribute(attributes["team_url"]) diff --git a/python_embeded/Lib/site-packages/github/TimelineEvent.py b/python_embeded/Lib/site-packages/github/TimelineEvent.py new file mode 100644 index 0000000000000000000000000000000000000000..8d22cb765e03e1d9621b926908538728eb372795 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/TimelineEvent.py @@ -0,0 +1,154 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Aaron Levine # +# Copyright 2017 Mike Miller # +# Copyright 2018 Darragh Bailey # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Nick Campbell # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.NamedUser +import github.TimelineEventSource +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class TimelineEvent(NonCompletableGithubObject): + """ + This class represents IssueTimelineEvents. + + The reference can be found here + https://docs.github.com/en/rest/reference/issues#timeline + + """ + + def _initAttributes(self) -> None: + self._actor: Attribute[github.NamedUser.NamedUser] = NotSet + self._commit_id: Attribute[str] = NotSet + self._commit_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._event: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._node_id: Attribute[str] = NotSet + self._source: Attribute[github.TimelineEventSource.TimelineEventSource] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value}) + + @property + def actor(self) -> github.NamedUser.NamedUser: + return self._actor.value + + @property + def author_association(self) -> str | None: + if self.event == "commented" and self._author_association is not NotSet: + return self._author_association.value + return None + + @property + def body(self) -> str | None: + if self.event == "commented" and self._body is not NotSet: + return self._body.value + return None + + @property + def commit_id(self) -> str: + return self._commit_id.value + + @property + def commit_url(self) -> str: + return self._commit_url.value + + @property + def created_at(self) -> datetime: + return self._created_at.value + + @property + def event(self) -> str: + return self._event.value + + @property + def id(self) -> int: + return self._id.value + + @property + def node_id(self) -> str: + return self._node_id.value + + @property + def source(self) -> github.TimelineEventSource.TimelineEventSource | None: + # only available on `cross-referenced` events. + if self.event == "cross-referenced" and self._source is not NotSet: + return self._source.value + return None + + @property + def url(self) -> str: + return self._url.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "actor" in attributes: # pragma no branch + self._actor = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["actor"]) + if "author_association" in attributes: # pragma no branch + self._author_association = self._makeStringAttribute(attributes["author_association"]) + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "commit_id" in attributes: # pragma no branch + self._commit_id = self._makeStringAttribute(attributes["commit_id"]) + if "commit_url" in attributes: # pragma no branch + self._commit_url = self._makeStringAttribute(attributes["commit_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "event" in attributes: # pragma no branch + self._event = self._makeStringAttribute(attributes["event"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "source" in attributes: # pragma no branch + self._source = self._makeClassAttribute( + github.TimelineEventSource.TimelineEventSource, attributes["source"] + ) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/TimelineEventSource.py b/python_embeded/Lib/site-packages/github/TimelineEventSource.py new file mode 100644 index 0000000000000000000000000000000000000000..9e76b5bfe25ebe12649ee3b5a779af160d94be8b --- /dev/null +++ b/python_embeded/Lib/site-packages/github/TimelineEventSource.py @@ -0,0 +1,80 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Nick Campbell # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.Issue +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.Issue import Issue + + +class TimelineEventSource(NonCompletableGithubObject): + """ + This class represents IssueTimelineEventSource. + + The reference can be found here + https://docs.github.com/en/rest/reference/issues#timeline + + """ + + def _initAttributes(self) -> None: + self._issue: Attribute[Issue] = NotSet + self._type: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"type": self._type.value}) + + @property + def issue(self) -> Issue: + return self._issue.value + + @property + def type(self) -> str: + return self._type.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "issue" in attributes: # pragma no branch + self._issue = self._makeClassAttribute(github.Issue.Issue, attributes["issue"]) + if "type" in attributes: # pragma no branch + self._type = self._makeStringAttribute(attributes["type"]) diff --git a/python_embeded/Lib/site-packages/github/Topic.py b/python_embeded/Lib/site-packages/github/Topic.py new file mode 100644 index 0000000000000000000000000000000000000000..2a07a5316290f5e60b20f1a36dde6c9fa0b24138 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Topic.py @@ -0,0 +1,175 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Steve Kowalik # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class Topic(NonCompletableGithubObject): + """ + This class represents topics as used by https://github.com/topics. The object reference can be found here https://docs.github.com/en/rest/reference/search#search-topics + + The OpenAPI schema can be found at + - /components/schemas/topic-search-result-item + + """ + + def _initAttributes(self) -> None: + self._aliases: Attribute[list[dict[str, Any]]] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._created_by: Attribute[str] = NotSet + self._curated: Attribute[bool] = NotSet + self._description: Attribute[str] = NotSet + self._display_name: Attribute[str] = NotSet + self._featured: Attribute[bool] = NotSet + self._logo_url: Attribute[str] = NotSet + self._name: Attribute[str] = NotSet + self._related: Attribute[list[dict[str, Any]]] = NotSet + self._released: Attribute[str] = NotSet + self._repository_count: Attribute[int] = NotSet + self._score: Attribute[float] = NotSet + self._short_description: Attribute[str] = NotSet + self._text_matches: Attribute[dict[str, Any]] = NotSet + self._updated_at: Attribute[datetime] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value}) + + @property + def aliases(self) -> list[dict[str, Any]]: + return self._aliases.value + + @property + def created_at(self) -> datetime: + return self._created_at.value + + @property + def created_by(self) -> str: + return self._created_by.value + + @property + def curated(self) -> bool: + return self._curated.value + + @property + def description(self) -> str: + return self._description.value + + @property + def display_name(self) -> str: + return self._display_name.value + + @property + def featured(self) -> bool: + return self._featured.value + + @property + def logo_url(self) -> str: + return self._logo_url.value + + @property + def name(self) -> str: + return self._name.value + + @property + def related(self) -> list[dict[str, Any]]: + return self._related.value + + @property + def released(self) -> str: + return self._released.value + + @property + def repository_count(self) -> int: + return self._repository_count.value + + @property + def score(self) -> float: + return self._score.value + + @property + def short_description(self) -> str: + return self._short_description.value + + @property + def text_matches(self) -> dict[str, Any]: + return self._text_matches.value + + @property + def updated_at(self) -> datetime: + return self._updated_at.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "aliases" in attributes: # pragma no branch + self._aliases = self._makeListOfDictsAttribute(attributes["aliases"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "created_by" in attributes: # pragma no branch + self._created_by = self._makeStringAttribute(attributes["created_by"]) + if "curated" in attributes: # pragma no branch + self._curated = self._makeBoolAttribute(attributes["curated"]) + if "description" in attributes: # pragma no branch + self._description = self._makeStringAttribute(attributes["description"]) + if "display_name" in attributes: # pragma no branch + self._display_name = self._makeStringAttribute(attributes["display_name"]) + if "featured" in attributes: # pragma no branch + self._featured = self._makeBoolAttribute(attributes["featured"]) + if "logo_url" in attributes: # pragma no branch + self._logo_url = self._makeStringAttribute(attributes["logo_url"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "related" in attributes: # pragma no branch + self._related = self._makeListOfDictsAttribute(attributes["related"]) + if "released" in attributes: # pragma no branch + self._released = self._makeStringAttribute(attributes["released"]) + if "repository_count" in attributes: # pragma no branch + self._repository_count = self._makeIntAttribute(attributes["repository_count"]) + if "score" in attributes: # pragma no branch + self._score = self._makeFloatAttribute(attributes["score"]) + if "short_description" in attributes: # pragma no branch + self._short_description = self._makeStringAttribute(attributes["short_description"]) + if "text_matches" in attributes: # pragma no branch + self._text_matches = self._makeDictAttribute(attributes["text_matches"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) diff --git a/python_embeded/Lib/site-packages/github/Traffic.py b/python_embeded/Lib/site-packages/github/Traffic.py new file mode 100644 index 0000000000000000000000000000000000000000..629933ff55a08f8b93791be0e7b3ae0f48424e90 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Traffic.py @@ -0,0 +1,93 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Justin Kufro # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + + +class Traffic(NonCompletableGithubObject): + """ + This class represents traffic information at a specific point in time. + + The reference can be found here + https://docs.github.com/en/rest/metrics/traffic + + The OpenAPI schema can be found at + - /components/schemas/traffic + + """ + + def _initAttributes(self) -> None: + self._count: Attribute[int] = NotSet + self._timestamp: Attribute[datetime] = NotSet + self._uniques: Attribute[int] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "timestamp": self._timestamp.value, + "count": self._count.value, + "uniques": self._uniques.value, + } + ) + + @property + def count(self) -> int: + return self._count.value + + @property + def timestamp(self) -> datetime: + return self._timestamp.value + + @property + def uniques(self) -> int: + return self._uniques.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "count" in attributes: # pragma no branch + self._count = self._makeIntAttribute(attributes["count"]) + if "timestamp" in attributes: # pragma no branch + self._timestamp = self._makeDatetimeAttribute(attributes["timestamp"]) + if "uniques" in attributes: # pragma no branch + self._uniques = self._makeIntAttribute(attributes["uniques"]) diff --git a/python_embeded/Lib/site-packages/github/UserKey.py b/python_embeded/Lib/site-packages/github/UserKey.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a878fabbc4f205e5e87484a4a4ef1ce941b371 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/UserKey.py @@ -0,0 +1,130 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2013 martinqt # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Mark Walker # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class UserKey(CompletableGithubObject): + """ + This class represents UserKeys. + + The reference can be found here + https://docs.github.com/en/rest/reference/users#keys + + The OpenAPI schema can be found at + - /components/schemas/key + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._id: Attribute[int] = NotSet + self._key: Attribute[str] = NotSet + self._read_only: Attribute[bool] = NotSet + self._title: Attribute[str] = NotSet + self._url: Attribute[str] = NotSet + self._verified: Attribute[bool] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "title": self._title.value}) + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def key(self) -> str: + self._completeIfNotSet(self._key) + return self._key.value + + @property + def read_only(self) -> bool: + self._completeIfNotSet(self._read_only) + return self._read_only.value + + @property + def title(self) -> str: + self._completeIfNotSet(self._title) + return self._title.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def verified(self) -> bool: + self._completeIfNotSet(self._verified) + return self._verified.value + + def delete(self) -> None: + """ + :calls: `DELETE /user/keys/{id} `_ + :rtype: None + """ + headers, data = self._requester.requestJsonAndCheck("DELETE", self.url) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "key" in attributes: # pragma no branch + self._key = self._makeStringAttribute(attributes["key"]) + if "read_only" in attributes: # pragma no branch + self._read_only = self._makeBoolAttribute(attributes["read_only"]) + if "title" in attributes: # pragma no branch + self._title = self._makeStringAttribute(attributes["title"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "verified" in attributes: # pragma no branch + self._verified = self._makeBoolAttribute(attributes["verified"]) diff --git a/python_embeded/Lib/site-packages/github/Variable.py b/python_embeded/Lib/site-packages/github/Variable.py new file mode 100644 index 0000000000000000000000000000000000000000..6d69d268d3df2ec4c8402bf124c4549e3b72e790 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Variable.py @@ -0,0 +1,143 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Mauricio Alejandro Martínez Pacheco # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class Variable(CompletableGithubObject): + """ + This class represents a GitHub variable. + + The reference can be found here + https://docs.github.com/en/rest/actions/variables + + """ + + def _initAttributes(self) -> None: + self._created_at: Attribute[datetime] = NotSet + self._name: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._value: Attribute[str] = NotSet + self._variables_url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self.name}) + + @property + def created_at(self) -> datetime: + """ + :type: datetime.datetime + """ + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def name(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._name) + return self._name.value + + @property + def updated_at(self) -> datetime: + """ + :type: datetime.datetime + """ + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + """ + :type: string + """ + # Construct url from variables_url and name, if self._url. is not set + if self._url is NotSet: + self._url = self._makeStringAttribute(self.variables_url + "/" + self.name) + return self._url.value + + @property + def value(self) -> str: + """ + :type: string + """ + self._completeIfNotSet(self._value) + return self._value.value + + @property + def variables_url(self) -> str: + """ + :type: string + """ + return self._variables_url.value + + def edit(self, value: str) -> bool: + """ + :calls: `PATCH /repos/{owner}/{repo}/actions/variables/{variable_name} `_ + :param variable_name: string + :param value: string + :rtype: bool + """ + assert isinstance(value, str), value + patch_parameters = { + "name": self.name, + "value": value, + } + status, _, _ = self._requester.requestJson( + "PATCH", + self.url, + input=patch_parameters, + ) + return status == 204 + + def delete(self) -> None: + """ + :calls: `DELETE {variable_url} `_ + :rtype: None + """ + self._requester.requestJsonAndCheck("DELETE", self.url) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "created_at" in attributes: + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "name" in attributes: + self._name = self._makeStringAttribute(attributes["name"]) + if "updated_at" in attributes: + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: + self._url = self._makeStringAttribute(attributes["url"]) + if "value" in attributes: + self._value = self._makeStringAttribute(attributes["value"]) + if "variables_url" in attributes: + self._variables_url = self._makeStringAttribute(attributes["variables_url"]) diff --git a/python_embeded/Lib/site-packages/github/View.py b/python_embeded/Lib/site-packages/github/View.py new file mode 100644 index 0000000000000000000000000000000000000000..133dfb1c963b2e4c144d016c32f6d523cbd0da02 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/View.py @@ -0,0 +1,95 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Justin Kufro # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import github.Traffic +from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet + +if TYPE_CHECKING: + from github.Traffic import Traffic + + +class View(NonCompletableGithubObject): + """ + This class represents the total number of views and breakdown per day or week for a GitHub repository. + + The reference can be found here + https://docs.github.com/en/rest/metrics/traffic#get-page-views + + The OpenAPI schema can be found at + - /components/schemas/view-traffic + + """ + + def _initAttributes(self) -> None: + self._count: Attribute[int] = NotSet + self._uniques: Attribute[int] = NotSet + self._views: Attribute[list[Traffic]] = NotSet + + def __repr__(self) -> str: + return self.get__repr__( + { + "count": self._count.value, + "uniques": self._uniques.value, + } + ) + + @property + def count(self) -> int: + return self._count.value + + @property + def uniques(self) -> int: + return self._uniques.value + + @property + def views(self) -> list[Traffic]: + return self._views.value + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "count" in attributes: # pragma no branch + self._count = self._makeIntAttribute(attributes["count"]) + if "uniques" in attributes: # pragma no branch + self._uniques = self._makeIntAttribute(attributes["uniques"]) + if "views" in attributes: # pragma no branch + self._views = self._makeListOfClassesAttribute(github.Traffic.Traffic, attributes["views"]) diff --git a/python_embeded/Lib/site-packages/github/Workflow.py b/python_embeded/Lib/site-packages/github/Workflow.py new file mode 100644 index 0000000000000000000000000000000000000000..280c98550ca79b51aa97511bc7edfeb725f2c1df --- /dev/null +++ b/python_embeded/Lib/site-packages/github/Workflow.py @@ -0,0 +1,257 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 Jannis Gebauer # +# Copyright 2017 Simon # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Mahesh Raju # +# Copyright 2020 Steve Kowalik # +# Copyright 2021 Steve Kowalik # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Thomas Burghout # +# Copyright 2023 Trim21 # +# Copyright 2023 sd-kialo <138505487+sd-kialo@users.noreply.github.com> # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# Copyright 2025 Nick McClorey <32378821+nickrmcclorey@users.noreply.github.com># +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.Branch +import github.Commit +import github.GithubObject +import github.NamedUser +import github.Tag +import github.WorkflowRun +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt +from github.PaginatedList import PaginatedList + + +class Workflow(CompletableGithubObject): + """ + This class represents Workflows. + + The reference can be found here + https://docs.github.com/en/rest/reference/actions#workflows + + The OpenAPI schema can be found at + - /components/schemas/workflow + + """ + + def _initAttributes(self) -> None: + self._badge_url: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._deleted_at: Attribute[datetime] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._path: Attribute[str] = NotSet + self._state: Attribute[str] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"name": self._name.value, "url": self._url.value}) + + @property + def badge_url(self) -> str: + self._completeIfNotSet(self._badge_url) + return self._badge_url.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def deleted_at(self) -> datetime: + self._completeIfNotSet(self._deleted_at) + return self._deleted_at.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def path(self) -> str: + self._completeIfNotSet(self._path) + return self._path.value + + @property + def state(self) -> str: + self._completeIfNotSet(self._state) + return self._state.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + def create_dispatch( + self, ref: github.Branch.Branch | github.Tag.Tag | github.Commit.Commit | str, inputs: Opt[dict] = NotSet + ) -> bool: + """ + :calls: `POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches `_ + """ + assert ( + isinstance(ref, github.Branch.Branch) + or isinstance(ref, github.Tag.Tag) + or isinstance(ref, github.Commit.Commit) + or isinstance(ref, str) + ), ref + assert inputs is NotSet or isinstance(inputs, dict), inputs + if isinstance(ref, github.Branch.Branch): + ref = ref.name + elif isinstance(ref, github.Commit.Commit): + ref = ref.sha + elif isinstance(ref, github.Tag.Tag): + ref = ref.name + if inputs is NotSet: + inputs = {} + status, _, _ = self._requester.requestJson( + "POST", f"{self.url}/dispatches", input={"ref": ref, "inputs": inputs} + ) + return status == 204 + + def get_runs( + self, + actor: Opt[github.NamedUser.NamedUser | str] = NotSet, + branch: Opt[github.Branch.Branch | str] = NotSet, + event: Opt[str] = NotSet, + status: Opt[str] = NotSet, + created: Opt[str] = NotSet, + exclude_pull_requests: Opt[bool] = NotSet, + check_suite_id: Opt[int] = NotSet, + head_sha: Opt[str] = NotSet, + ) -> PaginatedList[github.WorkflowRun.WorkflowRun]: + """ + :calls: `GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs `_ + """ + assert actor is NotSet or isinstance(actor, github.NamedUser.NamedUser) or isinstance(actor, str), actor + assert branch is NotSet or isinstance(branch, github.Branch.Branch) or isinstance(branch, str), branch + assert event is NotSet or isinstance(event, str), event + assert status is NotSet or isinstance(status, str), status + assert created is NotSet or isinstance(created, str), created + assert exclude_pull_requests is NotSet or isinstance(exclude_pull_requests, bool), exclude_pull_requests + assert check_suite_id is NotSet or isinstance(check_suite_id, int), check_suite_id + assert head_sha is NotSet or isinstance(head_sha, str), head_sha + url_parameters: dict[str, Any] = dict() + if actor is not NotSet: + url_parameters["actor"] = actor._identity if isinstance(actor, github.NamedUser.NamedUser) else actor + if branch is not NotSet: + url_parameters["branch"] = branch.name if isinstance(branch, github.Branch.Branch) else branch + if event is not NotSet: + url_parameters["event"] = event + if status is not NotSet: + url_parameters["status"] = status + if created is not NotSet: + url_parameters["created"] = created + if exclude_pull_requests is not NotSet: + url_parameters["exclude_pull_requests"] = exclude_pull_requests + if check_suite_id is not NotSet: + url_parameters["check_suite_id"] = check_suite_id + if head_sha is not NotSet: + url_parameters["head_sha"] = head_sha + + return PaginatedList( + github.WorkflowRun.WorkflowRun, + self._requester, + f"{self.url}/runs", + url_parameters, + headers=None, + list_item="workflow_runs", + ) + + def disable(self) -> bool: + """ + :calls: `PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable `_ + :rtype: bool + """ + status, _, _ = self._requester.requestJson("PUT", f"{self.url}/disable") + return status == 204 + + def enable(self) -> bool: + """ + :calls: `PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable `_ + :rtype: bool + """ + status, _, _ = self._requester.requestJson("PUT", f"{self.url}/enable") + return status == 204 + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "badge_url" in attributes: # pragma no branch + self._badge_url = self._makeStringAttribute(attributes["badge_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "deleted_at" in attributes: # pragma no branch + self._deleted_at = self._makeDatetimeAttribute(attributes["deleted_at"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "path" in attributes: # pragma no branch + self._path = self._makeStringAttribute(attributes["path"]) + if "state" in attributes: # pragma no branch + self._state = self._makeStringAttribute(attributes["state"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/python_embeded/Lib/site-packages/github/WorkflowJob.py b/python_embeded/Lib/site-packages/github/WorkflowJob.py new file mode 100644 index 0000000000000000000000000000000000000000..4d979ed9115ec5cbfab9e3242074249d15d26401 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/WorkflowJob.py @@ -0,0 +1,243 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jeppe Fihl-Pearson # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2024 Xavi Vega # +# Copyright 2025 Enrico Minack # +# Copyright 2025 Yossi Rozantsev <54272821+Apakottur@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import github.GithubObject +import github.WorkflowStep +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class WorkflowJob(CompletableGithubObject): + """ + This class represents Workflow Jobs. + + The reference can be found here + https://docs.github.com/en/rest/reference/actions#workflow-jobs + + """ + + def _initAttributes(self) -> None: + self._check_run_url: Attribute[str] = NotSet + self._completed_at: Attribute[datetime] = NotSet + self._conclusion: Attribute[str | None] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._head_branch: Attribute[str] = NotSet + self._head_sha: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._labels: Attribute[list[str]] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._run_attempt: Attribute[int] = NotSet + self._run_id: Attribute[int] = NotSet + self._run_url: Attribute[str] = NotSet + self._runner_group_id: Attribute[int] = NotSet + self._runner_group_name: Attribute[str] = NotSet + self._runner_id: Attribute[int] = NotSet + self._runner_name: Attribute[str] = NotSet + self._started_at: Attribute[datetime] = NotSet + self._status: Attribute[str] = NotSet + self._steps: Attribute[list[github.WorkflowStep.WorkflowStep]] = NotSet + self._url: Attribute[str] = NotSet + self._workflow_name: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "url": self._url.value}) + + @property + def check_run_url(self) -> str: + self._completeIfNotSet(self._check_run_url) + return self._check_run_url.value + + @property + def completed_at(self) -> datetime: + self._completeIfNotSet(self._completed_at) + return self._completed_at.value + + @property + def conclusion(self) -> str | None: + self._completeIfNotSet(self._conclusion) + return self._conclusion.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def head_branch(self) -> str: + self._completeIfNotSet(self._head_branch) + return self._head_branch.value + + @property + def head_sha(self) -> str: + self._completeIfNotSet(self._head_sha) + return self._head_sha.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def labels(self) -> list[str]: + self._completeIfNotSet(self._labels) + return self._labels.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def run_attempt(self) -> int: + self._completeIfNotSet(self._run_attempt) + return self._run_attempt.value + + @property + def run_id(self) -> int: + self._completeIfNotSet(self._run_id) + return self._run_id.value + + @property + def run_url(self) -> str: + self._completeIfNotSet(self._run_url) + return self._run_url.value + + @property + def runner_group_id(self) -> int: + self._completeIfNotSet(self._runner_group_id) + return self._runner_group_id.value + + @property + def runner_group_name(self) -> str: + self._completeIfNotSet(self._runner_group_name) + return self._runner_group_name.value + + @property + def runner_id(self) -> int: + self._completeIfNotSet(self._runner_id) + return self._runner_id.value + + @property + def runner_name(self) -> str: + self._completeIfNotSet(self._runner_name) + return self._runner_name.value + + @property + def started_at(self) -> datetime: + self._completeIfNotSet(self._started_at) + return self._started_at.value + + @property + def status(self) -> str: + self._completeIfNotSet(self._status) + return self._status.value + + @property + def steps(self) -> list[github.WorkflowStep.WorkflowStep]: + self._completeIfNotSet(self._steps) + return self._steps.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def workflow_name(self) -> str: + self._completeIfNotSet(self._workflow_name) + return self._workflow_name.value + + def logs_url(self) -> str: + headers, _ = self._requester.requestBlobAndCheck("GET", f"{self.url}/logs") + return headers["location"] + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "check_run_url" in attributes: # pragma no branch + self._check_run_url = self._makeStringAttribute(attributes["check_run_url"]) + if "completed_at" in attributes: # pragma no branch + self._completed_at = self._makeDatetimeAttribute(attributes["completed_at"]) + if "conclusion" in attributes: # pragma no branch + self._conclusion = self._makeStringAttribute(attributes["conclusion"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "head_branch" in attributes: # pragma no branch + self._head_branch = self._makeStringAttribute(attributes["head_branch"]) + if "head_sha" in attributes: # pragma no branch + self._head_sha = self._makeStringAttribute(attributes["head_sha"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "labels" in attributes: # pragma no branch + self._labels = self._makeListOfStringsAttribute(attributes["labels"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "run_attempt" in attributes: # pragma no branch + self._run_attempt = self._makeIntAttribute(attributes["run_attempt"]) + if "run_id" in attributes: # pragma no branch + self._run_id = self._makeIntAttribute(attributes["run_id"]) + if "run_url" in attributes: # pragma no branch + self._run_url = self._makeStringAttribute(attributes["run_url"]) + if "runner_group_id" in attributes: # pragma no branch + self._runner_group_id = self._makeIntAttribute(attributes["runner_group_id"]) + if "runner_group_name" in attributes: # pragma no branch + self._runner_group_name = self._makeStringAttribute(attributes["runner_group_name"]) + if "runner_id" in attributes: # pragma no branch + self._runner_id = self._makeIntAttribute(attributes["runner_id"]) + if "runner_name" in attributes: # pragma no branch + self._runner_name = self._makeStringAttribute(attributes["runner_name"]) + if "started_at" in attributes: # pragma no branch + self._started_at = self._makeDatetimeAttribute(attributes["started_at"]) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) + if "steps" in attributes: # pragma no branch + self._steps = self._makeListOfClassesAttribute(github.WorkflowStep.WorkflowStep, attributes["steps"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "workflow_name" in attributes: # pragma no branch + self._workflow_name = self._makeStringAttribute(attributes["workflow_name"]) diff --git a/python_embeded/Lib/site-packages/github/WorkflowRun.py b/python_embeded/Lib/site-packages/github/WorkflowRun.py new file mode 100644 index 0000000000000000000000000000000000000000..928b930fcfb7648282aa609919671c9201312a28 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/WorkflowRun.py @@ -0,0 +1,448 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 Yannick Jadoul # +# Copyright 2021 Steve Kowalik # +# Copyright 2022 Aleksei Fedotov # +# Copyright 2022 Gabriele Oliaro # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jeppe Fihl-Pearson # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Sasha Chung <50770626+nuang-ee@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Chris Gavin # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Geoffrey # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from __future__ import annotations + +from datetime import datetime +from typing import TYPE_CHECKING, Any, NamedTuple + +import github.GitCommit +import github.NamedUser +import github.PullRequest +import github.Repository +import github.WorkflowJob +from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_optional +from github.PaginatedList import PaginatedList + +if TYPE_CHECKING: + from github.Artifact import Artifact + from github.GitCommit import GitCommit + from github.NamedUser import NamedUser + from github.PullRequest import PullRequest + from github.Repository import Repository + from github.WorkflowJob import WorkflowJob + + +class TimingData(NamedTuple): + billable: dict[str, dict[str, int]] + run_duration_ms: int + + +class WorkflowRun(CompletableGithubObject): + """ + This class represents Workflow Runs. + + The reference can be found here + https://docs.github.com/en/rest/reference/actions#workflow-runs + + The OpenAPI schema can be found at + - /components/schemas/artifact/properties/workflow_run + - /components/schemas/workflow-run + + """ + + def _initAttributes(self) -> None: + self._actor: Attribute[NamedUser] = NotSet + self._artifacts_url: Attribute[str] = NotSet + self._cancel_url: Attribute[str] = NotSet + self._check_suite_id: Attribute[int] = NotSet + self._check_suite_node_id: Attribute[str] = NotSet + self._check_suite_url: Attribute[str] = NotSet + self._conclusion: Attribute[str] = NotSet + self._created_at: Attribute[datetime] = NotSet + self._display_title: Attribute[str] = NotSet + self._event: Attribute[str] = NotSet + self._head_branch: Attribute[str] = NotSet + self._head_commit: Attribute[GitCommit] = NotSet + self._head_repository: Attribute[Repository] = NotSet + self._head_repository_id: Attribute[int] = NotSet + self._head_sha: Attribute[str] = NotSet + self._html_url: Attribute[str] = NotSet + self._id: Attribute[int] = NotSet + self._jobs_url: Attribute[str] = NotSet + self._logs_url: Attribute[str] = NotSet + self._name: Attribute[str] = NotSet + self._node_id: Attribute[str] = NotSet + self._path: Attribute[str] = NotSet + self._previous_attempt_url: Attribute[str] = NotSet + self._pull_requests: Attribute[list[PullRequest]] = NotSet + self._referenced_workflows: Attribute[list[dict[str, Any]]] = NotSet + self._repository: Attribute[Repository] = NotSet + self._repository_id: Attribute[int] = NotSet + self._rerun_url: Attribute[str] = NotSet + self._run_attempt: Attribute[int] = NotSet + self._run_number: Attribute[int] = NotSet + self._run_started_at: Attribute[datetime] = NotSet + self._status: Attribute[str] = NotSet + self._triggering_actor: Attribute[NamedUser] = NotSet + self._updated_at: Attribute[datetime] = NotSet + self._url: Attribute[str] = NotSet + self._workflow_id: Attribute[int] = NotSet + self._workflow_url: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"id": self._id.value, "url": self._url.value}) + + @property + def actor(self) -> NamedUser: + self._completeIfNotSet(self._actor) + return self._actor.value + + @property + def artifacts_url(self) -> str: + self._completeIfNotSet(self._artifacts_url) + return self._artifacts_url.value + + @property + def cancel_url(self) -> str: + self._completeIfNotSet(self._cancel_url) + return self._cancel_url.value + + @property + def check_suite_id(self) -> int: + self._completeIfNotSet(self._check_suite_id) + return self._check_suite_id.value + + @property + def check_suite_node_id(self) -> str: + self._completeIfNotSet(self._check_suite_node_id) + return self._check_suite_node_id.value + + @property + def check_suite_url(self) -> str: + self._completeIfNotSet(self._check_suite_url) + return self._check_suite_url.value + + @property + def conclusion(self) -> str: + self._completeIfNotSet(self._conclusion) + return self._conclusion.value + + @property + def created_at(self) -> datetime: + self._completeIfNotSet(self._created_at) + return self._created_at.value + + @property + def display_title(self) -> str: + self._completeIfNotSet(self._display_title) + return self._display_title.value + + @property + def event(self) -> str: + self._completeIfNotSet(self._event) + return self._event.value + + @property + def head_branch(self) -> str: + self._completeIfNotSet(self._head_branch) + return self._head_branch.value + + @property + def head_commit(self) -> GitCommit: + self._completeIfNotSet(self._head_commit) + return self._head_commit.value + + @property + def head_repository(self) -> Repository: + self._completeIfNotSet(self._head_repository) + return self._head_repository.value + + @property + def head_repository_id(self) -> int: + self._completeIfNotSet(self._head_repository_id) + return self._head_repository_id.value + + @property + def head_sha(self) -> str: + self._completeIfNotSet(self._head_sha) + return self._head_sha.value + + @property + def html_url(self) -> str: + self._completeIfNotSet(self._html_url) + return self._html_url.value + + @property + def id(self) -> int: + self._completeIfNotSet(self._id) + return self._id.value + + @property + def jobs_url(self) -> str: + self._completeIfNotSet(self._jobs_url) + return self._jobs_url.value + + @property + def logs_url(self) -> str: + self._completeIfNotSet(self._logs_url) + return self._logs_url.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def node_id(self) -> str: + self._completeIfNotSet(self._node_id) + return self._node_id.value + + @property + def path(self) -> str: + self._completeIfNotSet(self._path) + return self._path.value + + @property + def previous_attempt_url(self) -> str: + self._completeIfNotSet(self._previous_attempt_url) + return self._previous_attempt_url.value + + @property + def pull_requests(self) -> list[PullRequest]: + self._completeIfNotSet(self._pull_requests) + return self._pull_requests.value + + @property + def referenced_workflows(self) -> list[dict[str, Any]]: + self._completeIfNotSet(self._referenced_workflows) + return self._referenced_workflows.value + + @property + def repository(self) -> Repository: + self._completeIfNotSet(self._repository) + return self._repository.value + + @property + def repository_id(self) -> int: + self._completeIfNotSet(self._repository_id) + return self._repository_id.value + + @property + def rerun_url(self) -> str: + self._completeIfNotSet(self._rerun_url) + return self._rerun_url.value + + @property + def run_attempt(self) -> int: + self._completeIfNotSet(self._run_attempt) + return self._run_attempt.value + + @property + def run_number(self) -> int: + self._completeIfNotSet(self._run_number) + return self._run_number.value + + @property + def run_started_at(self) -> datetime: + self._completeIfNotSet(self._run_started_at) + return self._run_started_at.value + + @property + def status(self) -> str: + self._completeIfNotSet(self._status) + return self._status.value + + @property + def triggering_actor(self) -> github.NamedUser.NamedUser: + self._completeIfNotSet(self._triggering_actor) + return self._triggering_actor.value + + @property + def updated_at(self) -> datetime: + self._completeIfNotSet(self._updated_at) + return self._updated_at.value + + @property + def url(self) -> str: + self._completeIfNotSet(self._url) + return self._url.value + + @property + def workflow_id(self) -> int: + self._completeIfNotSet(self._workflow_id) + return self._workflow_id.value + + @property + def workflow_url(self) -> str: + self._completeIfNotSet(self._workflow_url) + return self._workflow_url.value + + def get_artifacts(self) -> PaginatedList[Artifact]: + return PaginatedList( + github.Artifact.Artifact, + self._requester, + self._artifacts_url.value, + None, + list_item="artifacts", + ) + + def cancel(self) -> bool: + """ + :calls: `POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel `_ + """ + status, _, _ = self._requester.requestJson("POST", self.cancel_url) + return status == 202 + + def rerun(self) -> bool: + """ + :calls: `POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun `_ + """ + status, _, _ = self._requester.requestJson("POST", self.rerun_url) + return status == 201 + + def rerun_failed_jobs(self) -> bool: + """ + :calls: `POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs `_ + """ + status, _, _ = self._requester.requestJson("POST", f"{self.url}/rerun-failed-jobs") + return status == 201 + + def timing(self) -> TimingData: + """ + :calls: `GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing `_ + """ + headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/timing") + return TimingData(billable=data["billable"], run_duration_ms=data["run_duration_ms"]) # type: ignore + + def delete(self) -> bool: + """ + :calls: `DELETE /repos/{owner}/{repo}/actions/runs/{run_id} `_ + """ + status, _, _ = self._requester.requestJson("DELETE", self.url) + return status == 204 + + def jobs(self, _filter: Opt[str] = NotSet) -> PaginatedList[WorkflowJob]: + """ + :calls "`GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs `_ + :param _filter: string `latest`, or `all` + """ + assert is_optional(_filter, str), _filter + + url_parameters = NotSet.remove_unset_items({"filter": _filter}) + + return PaginatedList( + github.WorkflowJob.WorkflowJob, + self._requester, + self.jobs_url, + url_parameters, + list_item="jobs", + ) + + def _useAttributes(self, attributes: dict[str, Any]) -> None: + if "actor" in attributes: # pragma no branch + self._actor = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["actor"]) + if "artifacts_url" in attributes: # pragma no branch + self._artifacts_url = self._makeStringAttribute(attributes["artifacts_url"]) + if "cancel_url" in attributes: # pragma no branch + self._cancel_url = self._makeStringAttribute(attributes["cancel_url"]) + if "check_suite_id" in attributes: # pragma no branch + self._check_suite_id = self._makeIntAttribute(attributes["check_suite_id"]) + if "check_suite_node_id" in attributes: # pragma no branch + self._check_suite_node_id = self._makeStringAttribute(attributes["check_suite_node_id"]) + if "check_suite_url" in attributes: # pragma no branch + self._check_suite_url = self._makeStringAttribute(attributes["check_suite_url"]) + if "conclusion" in attributes: # pragma no branch + self._conclusion = self._makeStringAttribute(attributes["conclusion"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "display_title" in attributes: # pragma no branch + self._display_title = self._makeStringAttribute(attributes["display_title"]) + if "event" in attributes: # pragma no branch + self._event = self._makeStringAttribute(attributes["event"]) + if "head_branch" in attributes: # pragma no branch + self._head_branch = self._makeStringAttribute(attributes["head_branch"]) + if "head_commit" in attributes: # pragma no branch + self._head_commit = self._makeClassAttribute(github.GitCommit.GitCommit, attributes["head_commit"]) + if "head_repository" in attributes: # pragma no branch + self._head_repository = self._makeClassAttribute( + github.Repository.Repository, attributes["head_repository"] + ) + if "head_repository_id" in attributes: # pragma no branch + self._head_repository_id = self._makeIntAttribute(attributes["head_repository_id"]) + if "head_sha" in attributes: # pragma no branch + self._head_sha = self._makeStringAttribute(attributes["head_sha"]) + if "html_url" in attributes: # pragma no branch + self._html_url = self._makeStringAttribute(attributes["html_url"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "jobs_url" in attributes: # pragma no branch + self._jobs_url = self._makeStringAttribute(attributes["jobs_url"]) + if "logs_url" in attributes: # pragma no branch + self._logs_url = self._makeStringAttribute(attributes["logs_url"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "path" in attributes: # pragma no branch + self._path = self._makeStringAttribute(attributes["path"]) + if "previous_attempt_url" in attributes: # pragma no branch + self._previous_attempt_url = self._makeStringAttribute(attributes["previous_attempt_url"]) + if "pull_requests" in attributes: # pragma no branch + self._pull_requests = self._makeListOfClassesAttribute( + github.PullRequest.PullRequest, attributes["pull_requests"] + ) + if "referenced_workflows" in attributes: # pragma no branch + self._referenced_workflows = self._makeListOfDictsAttribute(attributes["referenced_workflows"]) + if "repository" in attributes: # pragma no branch + self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"]) + if "repository_id" in attributes: # pragma no branch + self._repository_id = self._makeIntAttribute(attributes["repository_id"]) + if "rerun_url" in attributes: # pragma no branch + self._rerun_url = self._makeStringAttribute(attributes["rerun_url"]) + if "run_attempt" in attributes: # pragma no branch + self._run_attempt = self._makeIntAttribute(attributes["run_attempt"]) + if "run_number" in attributes: # pragma no branch + self._run_number = self._makeIntAttribute(attributes["run_number"]) + if "run_started_at" in attributes: # pragma no branch + assert attributes["run_started_at"] is None or isinstance(attributes["run_started_at"], str), attributes[ + "run_started_at" + ] + self._run_started_at = self._makeDatetimeAttribute(attributes["run_started_at"]) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) + if "triggering_actor" in attributes: # pragma no branch + self._triggering_actor = self._makeClassAttribute( + github.NamedUser.NamedUser, attributes["triggering_actor"] + ) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) + if "workflow_id" in attributes: # pragma no branch + self._workflow_id = self._makeIntAttribute(attributes["workflow_id"]) + if "workflow_url" in attributes: # pragma no branch + self._workflow_url = self._makeStringAttribute(attributes["workflow_url"]) diff --git a/python_embeded/Lib/site-packages/github/WorkflowStep.py b/python_embeded/Lib/site-packages/github/WorkflowStep.py new file mode 100644 index 0000000000000000000000000000000000000000..7bde2a9684d4bb582a8dbb848e8d5831eea46d22 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/WorkflowStep.py @@ -0,0 +1,109 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 AKFish # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Steve Kowalik # +# Copyright 2020 Victor Zeng # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Jeppe Fihl-Pearson # +# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from datetime import datetime +from typing import Any, Dict + +from github.GithubObject import Attribute, CompletableGithubObject, NotSet + + +class WorkflowStep(CompletableGithubObject): + """ + This class represents steps in a Workflow Job. + + The reference can be found here + https://docs.github.com/en/rest/reference/actions#workflow-jobs + + """ + + def _initAttributes(self) -> None: + self._completed_at: Attribute[datetime] = NotSet + self._conclusion: Attribute[str] = NotSet + self._name: Attribute[str] = NotSet + self._number: Attribute[int] = NotSet + self._started_at: Attribute[datetime] = NotSet + self._status: Attribute[str] = NotSet + + def __repr__(self) -> str: + return self.get__repr__({"number": self._number.value, "name": self._name.value}) + + @property + def completed_at(self) -> datetime: + self._completeIfNotSet(self._completed_at) + return self._completed_at.value + + @property + def conclusion(self) -> str: + self._completeIfNotSet(self._conclusion) + return self._conclusion.value + + @property + def name(self) -> str: + self._completeIfNotSet(self._name) + return self._name.value + + @property + def number(self) -> int: + self._completeIfNotSet(self._number) + return self._number.value + + @property + def started_at(self) -> datetime: + self._completeIfNotSet(self._started_at) + return self._started_at.value + + @property + def status(self) -> str: + self._completeIfNotSet(self._status) + return self._status.value + + def _useAttributes(self, attributes: Dict[str, Any]) -> None: + if "completed_at" in attributes: # pragma no branch + self._completed_at = self._makeDatetimeAttribute(attributes["completed_at"]) + if "conclusion" in attributes: # pragma no branch + self._conclusion = self._makeStringAttribute(attributes["conclusion"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "number" in attributes: # pragma no branch + self._number = self._makeIntAttribute(attributes["number"]) + if "started_at" in attributes: # pragma no branch + self._started_at = self._makeDatetimeAttribute(attributes["started_at"]) + if "status" in attributes: # pragma no branch + self._status = self._makeStringAttribute(attributes["status"]) diff --git a/python_embeded/Lib/site-packages/github/__init__.py b/python_embeded/Lib/site-packages/github/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d05c18c4a9d982b86111dd2931cc0b4860dc93 --- /dev/null +++ b/python_embeded/Lib/site-packages/github/__init__.py @@ -0,0 +1,112 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2012 Vincent Jacques # +# Copyright 2012 Zearin # +# Copyright 2013 Vincent Jacques # +# Copyright 2014 Vincent Jacques # +# Copyright 2016 Jannis Gebauer # +# Copyright 2016 Peter Buckley # +# Copyright 2017 sharkykh # +# Copyright 2018 Wan Liuyang # +# Copyright 2018 sfdye # +# Copyright 2019 Adam Baratz # +# Copyright 2019 Steve Kowalik # +# Copyright 2019 Wan Liuyang # +# Copyright 2020 Alice GIRARD # +# Copyright 2020 Emily # +# Copyright 2020 Liuyang Wan # +# Copyright 2020 Steve Kowalik # +# Copyright 2023 Denis Blanchette # +# Copyright 2023 Enrico Minack # +# Copyright 2023 Trim21 # +# Copyright 2024 Enrico Minack # +# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> # +# Copyright 2025 Enrico Minack # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ +""" +The primary class you will instantiate is :class:`github.MainClass.Github`. From its ``get_``, ``create_`` methods, you +will obtain instances of all Github objects like :class:`github.NamedUser.NamedUser` or +:class:`github.Repository.Repository`. + +All classes inherit from :class:`github.GithubObject.GithubObject`. + +""" + +import logging + +from . import Auth +from .AppAuthentication import AppAuthentication +from .GithubException import ( + BadAttributeException, + BadCredentialsException, + BadUserAgentException, + GithubException, + IncompletableObject, + RateLimitExceededException, + TwoFactorException, + UnknownObjectException, +) +from .GithubIntegration import GithubIntegration +from .GithubRetry import GithubRetry +from .InputFileContent import InputFileContent +from .InputGitAuthor import InputGitAuthor +from .InputGitTreeElement import InputGitTreeElement +from .MainClass import Github + +# set log level to INFO for github +logger = logging.getLogger("github") +logger.setLevel(logging.INFO) +logger.addHandler(logging.StreamHandler()) + + +def set_log_level(level: int) -> None: + """ + Set the log level of the github logger, e.g. set_log_level(logging.WARNING) :param level: log level. + """ + logger.setLevel(level) + + +def enable_console_debug_logging() -> None: # pragma no cover (Function useful only outside test environment) + """ + This function sets up a very simple logging configuration (log everything on standard output) that is useful for + troubleshooting. + """ + set_log_level(logging.DEBUG) + + +__all__ = [ + "Auth", + "AppAuthentication", + "BadAttributeException", + "BadCredentialsException", + "BadUserAgentException", + "enable_console_debug_logging", + "Github", + "GithubException", + "GithubIntegration", + "GithubRetry", + "IncompletableObject", + "InputFileContent", + "InputGitAuthor", + "InputGitTreeElement", + "RateLimitExceededException", + "TwoFactorException", + "UnknownObjectException", +] diff --git a/python_embeded/Lib/site-packages/github/py.typed b/python_embeded/Lib/site-packages/github/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/INSTALLER b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/LICENSE b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/METADATA b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..7c781f1cc5b49fc6801e46c259ae2ed0122703b5 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/METADATA @@ -0,0 +1,139 @@ +Metadata-Version: 2.1 +Name: google-ai-generativelanguage +Version: 0.6.15 +Summary: Google Ai Generativelanguage API client library +Home-page: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage +Author: Google LLC +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Platform: Posix; MacOS X; Windows +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet +Requires-Python: >=3.7 +License-File: LICENSE +Requires-Dist: google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0dev,>=1.34.1 +Requires-Dist: google-auth!=2.24.0,!=2.25.0,<3.0.0dev,>=2.14.1 +Requires-Dist: proto-plus<2.0.0dev,>=1.22.3 +Requires-Dist: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<6.0.0dev,>=3.20.2 +Requires-Dist: proto-plus<2.0.0dev,>=1.25.0; python_version >= "3.13" + +Python Client for Generative Language API +========================================= + +|preview| |pypi| |versions| + +`Generative Language API`_: The Gemini API allows developers to build generative AI applications using Gemini models. Gemini is our most capable model, built from the ground up to be multimodal. It can generalize and seamlessly understand, operate across, and combine different types of information including language, images, audio, video, and code. You can use the Gemini API for use cases like reasoning across text and images, content generation, dialogue agents, summarization and classification systems, and more. + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-ai-generativelanguage.svg + :target: https://pypi.org/project/google-ai-generativelanguage/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-ai-generativelanguage.svg + :target: https://pypi.org/project/google-ai-generativelanguage/ +.. _Generative Language API: https://ai.google.dev/docs +.. _Client Library Documentation: https://googleapis.dev/python/generativelanguage/latest +.. _Product Documentation: https://ai.google.dev/docs + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Generative Language API.`_ +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Generative Language API.: https://ai.google.dev/docs +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-ai-generativelanguage/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install google-ai-generativelanguage + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install google-ai-generativelanguage + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Generative Language API + to see other available methods on the client. +- Read the `Generative Language API Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Generative Language API Product documentation: https://ai.google.dev/docs +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/RECORD b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..fb8424165e8ef3c72e52051fba2d4178093ae04c --- /dev/null +++ b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/RECORD @@ -0,0 +1,689 @@ +google/ai/generativelanguage/__init__.py,sha256=BuPh2aQkzW73Njv7hNGuG6ts-NzOwUj5uXwL3Z2I3qI,11838 +google/ai/generativelanguage/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage/__pycache__/gapic_version.cpython-312.pyc,, +google/ai/generativelanguage/gapic_version.py,sha256=fW_Qd_01eJgNZqYHYqEr7_qs9RoCC6BLcI27EhqRscA,653 +google/ai/generativelanguage/py.typed,sha256=HcupzCIj7v3Z4_cqbaAdvF4JVO9LpsSGq46cfaF6HF4,89 +google/ai/generativelanguage_v1/__init__.py,sha256=fUXydUnpFsGWj2SAqgzbnlLZr3OACcC24mUk_6Z5BB4,2529 +google/ai/generativelanguage_v1/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1/__pycache__/gapic_version.cpython-312.pyc,, +google/ai/generativelanguage_v1/gapic_metadata.json,sha256=hdBHUatW6oNbpdVlP1SvADkPlQXa7bNxNO5-3kk-Nfw,3669 +google/ai/generativelanguage_v1/gapic_version.py,sha256=fW_Qd_01eJgNZqYHYqEr7_qs9RoCC6BLcI27EhqRscA,653 +google/ai/generativelanguage_v1/py.typed,sha256=HcupzCIj7v3Z4_cqbaAdvF4JVO9LpsSGq46cfaF6HF4,89 +google/ai/generativelanguage_v1/services/__init__.py,sha256=o-GCU1hbG5VXrOW7hUl_JSImemJCYPrMpZ9mIWck4h4,600 +google/ai/generativelanguage_v1/services/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/__init__.py,sha256=D6qhoNZtllR4Djqpaod4xflCuIheC6SuMJqaLug6QK0,781 +google/ai/generativelanguage_v1/services/generative_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/async_client.py,sha256=tjuut8sToTVnonNmTpG5Azrok77BFLSl52Sr-Q7_f_E,49358 +google/ai/generativelanguage_v1/services/generative_service/client.py,sha256=ho9UszKj0iyxEZXWZ2YPZXzhw70w2EAptqw4KsOJcxY,64263 +google/ai/generativelanguage_v1/services/generative_service/transports/__init__.py,sha256=E1QrkH5RHJcDSs0hDm6O7i2pM1NEidRh9-NCCo7s-2o,1442 +google/ai/generativelanguage_v1/services/generative_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/generative_service/transports/base.py,sha256=fxLINynTaQ-JT7lHeic2Qqcg71WgDtk4CeW3nryGptc,11449 +google/ai/generativelanguage_v1/services/generative_service/transports/grpc.py,sha256=xca7iwB5c_VSyZJryP8FfjhCXKVVTgihVFiuEaAI_-E,24588 +google/ai/generativelanguage_v1/services/generative_service/transports/grpc_asyncio.py,sha256=MKdxxV1R-7-lyh6TAFBMyGkptit89i-cMlRD4QoAOao,28840 +google/ai/generativelanguage_v1/services/generative_service/transports/rest.py,sha256=RZks4GLPdb5Kf8I731WkUcA_wt4GRK-DpjZTSmJ4b0Q,66084 +google/ai/generativelanguage_v1/services/generative_service/transports/rest_base.py,sha256=Rs9euNUea4LjgffSuzjIovG1kC0TKEFGFt-vBQghho8,17287 +google/ai/generativelanguage_v1/services/model_service/__init__.py,sha256=oY53bpew0sqaAPYqhoOV0CD3AQbo7OLP04aNoEFaNGc,761 +google/ai/generativelanguage_v1/services/model_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/async_client.py,sha256=Pl76A7IB7YpNgWq54spb-gHz5tMBj06Ig7nG2LmjWss,30142 +google/ai/generativelanguage_v1/services/model_service/client.py,sha256=w_njC1FlTe24XKUItItiYJ4nxw1gz41XCVRFEDf0R2A,45255 +google/ai/generativelanguage_v1/services/model_service/pagers.py,sha256=qp9EccOZn5Ak3DajwWON-yMDFa5a0HeIiTnah7LxJfM,7695 +google/ai/generativelanguage_v1/services/model_service/transports/__init__.py,sha256=2wzh7QZZoUpcSLQ0d7q_LeOmCeWZyZwP2sd-ir9Xl_I,1372 +google/ai/generativelanguage_v1/services/model_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1/services/model_service/transports/base.py,sha256=3pF0ngOUHjzQXbPVm072ZKJ8iCInnPEN0Br8KkVppGo,7990 +google/ai/generativelanguage_v1/services/model_service/transports/grpc.py,sha256=0FFWUKe7r1QfV4lDwKF8s9q5KoHFcFPua3BuTIVctXQ,19932 +google/ai/generativelanguage_v1/services/model_service/transports/grpc_asyncio.py,sha256=4JHVYOlvioDWoZWsOFpcv5ebCKY83uRDNRJkAZzbEZ8,21801 +google/ai/generativelanguage_v1/services/model_service/transports/rest.py,sha256=F00BNj2EKlvczeX_Wf_ph_dcSVWbKHxcovLwgPm7gm4,40348 +google/ai/generativelanguage_v1/services/model_service/transports/rest_base.py,sha256=efFXtNG1fMQRvgieDAiyvriTrstkhRfhy2wzxfUC7T0,9847 +google/ai/generativelanguage_v1/types/__init__.py,sha256=F6yclqg6BVXinorCH-eDAKVmE6v4NVH7NeK4q2XMmOE,2059 +google/ai/generativelanguage_v1/types/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1/types/__pycache__/citation.cpython-312.pyc,, +google/ai/generativelanguage_v1/types/__pycache__/content.cpython-312.pyc,, +google/ai/generativelanguage_v1/types/__pycache__/generative_service.cpython-312.pyc,, +google/ai/generativelanguage_v1/types/__pycache__/model.cpython-312.pyc,, +google/ai/generativelanguage_v1/types/__pycache__/model_service.cpython-312.pyc,, +google/ai/generativelanguage_v1/types/__pycache__/safety.cpython-312.pyc,, +google/ai/generativelanguage_v1/types/citation.py,sha256=0DdbpeIMmeIw9rkRwSaZE4uv9VyYQ6xQhRfmp3-3edc,2895 +google/ai/generativelanguage_v1/types/content.py,sha256=v0aGyzB_MPsQv2uzW7oTwZZL5-7FYbhQOrYWwIkwn8w,3922 +google/ai/generativelanguage_v1/types/generative_service.py,sha256=jux-9HVkUoUb3SnBhGNB5shqn9B_6bOVdOZjiRbiluA,39332 +google/ai/generativelanguage_v1/types/model.py,sha256=pGg2Z_FONAntSjHaEJ06hLPG8wAEiczTyZYPYW9A3wc,5376 +google/ai/generativelanguage_v1/types/model_service.py,sha256=c2rZ5Z9h2c2uKGrnBMr-qQ9r6uCtPqEp5DKFsB1fq5U,3086 +google/ai/generativelanguage_v1/types/safety.py,sha256=vJWvSx9v1vGeDWT7sFuDMp7wkFAymJfzMthvYoEIAqE,6508 +google/ai/generativelanguage_v1alpha/__init__.py,sha256=WuXa-8ECRbMqZilEBFGvDTiV6SCclS7yvyhsJrRvxtA,10834 +google/ai/generativelanguage_v1alpha/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/__pycache__/gapic_version.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/gapic_metadata.json,sha256=FRAGGdYfzniRUNteZngjTwsdmKqUIFnrc8q8xzGCSVo,24648 +google/ai/generativelanguage_v1alpha/gapic_version.py,sha256=fW_Qd_01eJgNZqYHYqEr7_qs9RoCC6BLcI27EhqRscA,653 +google/ai/generativelanguage_v1alpha/py.typed,sha256=HcupzCIj7v3Z4_cqbaAdvF4JVO9LpsSGq46cfaF6HF4,89 +google/ai/generativelanguage_v1alpha/services/__init__.py,sha256=o-GCU1hbG5VXrOW7hUl_JSImemJCYPrMpZ9mIWck4h4,600 +google/ai/generativelanguage_v1alpha/services/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/__init__.py,sha256=H5m8u77y8Pqx2jLhJXXTNWFcJGkqTAaYON5l5-xXu2s,761 +google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/async_client.py,sha256=uvx-UZKflcACsWBoXKCQLfFsd0S3OI5uhUzxglQNO3E,40596 +google/ai/generativelanguage_v1alpha/services/cache_service/client.py,sha256=hbHZo0vloa7T-qAbZzMzPeGffriXXRwfH_4Zvtxy9gA,55760 +google/ai/generativelanguage_v1alpha/services/cache_service/pagers.py,sha256=pP4970cTeshWD3MlSohQZeGjcbvmElZ2iKFdcvbahrY,8031 +google/ai/generativelanguage_v1alpha/services/cache_service/transports/__init__.py,sha256=K8mqEPq-LoNTzde1G34_QLKwttab3jSPBWOXsSBEQfU,1372 +google/ai/generativelanguage_v1alpha/services/cache_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/cache_service/transports/base.py,sha256=thArk0X1qQYoe7lkdICyLitFrjzlm-EU2geuUtArTUE,9453 +google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc.py,sha256=bxWoR3eUtcFF_Jmppglq8eS-D-3YQ6GYbe09_lR7oC8,23003 +google/ai/generativelanguage_v1alpha/services/cache_service/transports/grpc_asyncio.py,sha256=Rsovi95O-cM4x4EbOH75AgS3B7VqZgedwRxNxGvR4fI,25381 +google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest.py,sha256=LTc5giN2kRjuJxdGJmAXtdtKEyeQW1iYhVtbJu9fScM,57535 +google/ai/generativelanguage_v1alpha/services/cache_service/transports/rest_base.py,sha256=_H_k8_m_0QzzlWiP52ljj4bm39MOiw7dmrzHwK_IiGI,14464 +google/ai/generativelanguage_v1alpha/services/discuss_service/__init__.py,sha256=bHfunJdqzuw4aJIGR4Enuzw0TaD-9pAdZ0KRKKN0-lg,769 +google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/async_client.py,sha256=cN1G8q5pbtpNsG1FPqtdBvmCApZQ9FCQ_BbVVPqWV54,31141 +google/ai/generativelanguage_v1alpha/services/discuss_service/client.py,sha256=f4laCI8fE398hvZ4G2OZblFDp4ogWB39T7kSk4nfG3U,46347 +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__init__.py,sha256=PQWhSfmHneuxrGSr6ZTTUEltxvYMtiM9ZT06fx0EtH8,1400 +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/base.py,sha256=H8sKmiNc2WjdMJt-wLWiHAVjquk8MpB8mJmpxJzOQk0,7833 +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/grpc.py,sha256=N-BQY67m_Cf8AUQwDzYps-MTEduXVlL-VSSTtLzJNcU,19248 +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/grpc_asyncio.py,sha256=l0i-fpyHV8YWX5H9ypSzo4kS6jVmjaeymK27GSVTisk,20935 +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/rest.py,sha256=93k9vHxBdYdXJOgFZzyK1jRPUTWaNu0agQADzSa9VuQ,36632 +google/ai/generativelanguage_v1alpha/services/discuss_service/transports/rest_base.py,sha256=hXQ7FlwRs1mq9BzdjVW-mvCnuWwAjUiFAgLBdHeXgEE,9865 +google/ai/generativelanguage_v1alpha/services/file_service/__init__.py,sha256=0_yUEpYFfHmTaikAa8MHtCpyDPYvEdBlOnjNQjY9jDg,757 +google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/async_client.py,sha256=qPL6P4UypSogTxmU8wEJVMQbND2wpefL_y64fghOm0Q,32608 +google/ai/generativelanguage_v1alpha/services/file_service/client.py,sha256=R_7GRRqZi_ow2-Rai06kEMn40gGZyaOwCVWdJsIPdPs,47583 +google/ai/generativelanguage_v1alpha/services/file_service/pagers.py,sha256=rBMkdzoHz8c8oYxC-NM3_WJF6fD_D_AFAL3glupNETg,7694 +google/ai/generativelanguage_v1alpha/services/file_service/transports/__init__.py,sha256=lRbStijLPXnAlZMS9QkGBzI8uMD4KmHBEMTWlkaPkqU,1358 +google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/file_service/transports/base.py,sha256=LFeb0udwSMZniR6qdDeuABqyDWIKkRqC5Tp9wHw9-eQ,8519 +google/ai/generativelanguage_v1alpha/services/file_service/transports/grpc.py,sha256=4QEOd6rZynx-6eXDJWgM0nPKsnV53WmyEyOL_vw3SYE,20876 +google/ai/generativelanguage_v1alpha/services/file_service/transports/grpc_asyncio.py,sha256=D97D_3xfvdjxFit617Q8GuIvp2POOxMlOuPJBVwtCOs,22950 +google/ai/generativelanguage_v1alpha/services/file_service/transports/rest.py,sha256=rmT1rjDZeXPDHtNyGZ9fB5m9uvgu-bF9lVD2c0qvqic,47360 +google/ai/generativelanguage_v1alpha/services/file_service/transports/rest_base.py,sha256=zNMCTd3p5N2_tJVnt9_kkiCqtyIrOkewI7_xOZgA7L4,11666 +google/ai/generativelanguage_v1alpha/services/generative_service/__init__.py,sha256=D6qhoNZtllR4Djqpaod4xflCuIheC6SuMJqaLug6QK0,781 +google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/async_client.py,sha256=85JPEq9M-soWY0TjXfzGvpO-u1eQeTLK2wkwH6O-UM4,59462 +google/ai/generativelanguage_v1alpha/services/generative_service/client.py,sha256=u6-j8naBOzSq-xsHRcvoV0LCgRtPRvjIF7_zukHvHPs,74480 +google/ai/generativelanguage_v1alpha/services/generative_service/transports/__init__.py,sha256=E1QrkH5RHJcDSs0hDm6O7i2pM1NEidRh9-NCCo7s-2o,1442 +google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/generative_service/transports/base.py,sha256=nViN493KA-Up8AR090Fyz9Pbu0FS2z8dQBcb-u0fq-0,10459 +google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc.py,sha256=s1ZpxkA4WXDubD1Km5T0MplN23L49N7yslDWGVl47Jg,26511 +google/ai/generativelanguage_v1alpha/services/generative_service/transports/grpc_asyncio.py,sha256=9KfxAzHeP-xZgs_JIcdMAuxOkG1YtPctzn1JaG_qzJM,29263 +google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest.py,sha256=5qZ3NS1lB_1JOwsOOjwLXvsMHRwTIPLYhFzcdVeMiM8,69695 +google/ai/generativelanguage_v1alpha/services/generative_service/transports/rest_base.py,sha256=O0BjqQ4QeJ54NOO_mwfzC3KzOv9xC7YZ0WDgnIr0NlY,18206 +google/ai/generativelanguage_v1alpha/services/model_service/__init__.py,sha256=oY53bpew0sqaAPYqhoOV0CD3AQbo7OLP04aNoEFaNGc,761 +google/ai/generativelanguage_v1alpha/services/model_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/async_client.py,sha256=G95EwdW394xm16ha9XqVB3sHhMQppj-SAabT6mGOJjY,53765 +google/ai/generativelanguage_v1alpha/services/model_service/client.py,sha256=Ks0haaBcaVQIxStF3UjRw7Cn6kb6oZib96yHVzJEgHI,68751 +google/ai/generativelanguage_v1alpha/services/model_service/pagers.py,sha256=DwKjTw5bXJ0JVgkqhbsbewjWugcPQESJv573aaT4010,14317 +google/ai/generativelanguage_v1alpha/services/model_service/transports/__init__.py,sha256=2wzh7QZZoUpcSLQ0d7q_LeOmCeWZyZwP2sd-ir9Xl_I,1372 +google/ai/generativelanguage_v1alpha/services/model_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/model_service/transports/base.py,sha256=qH8IkQbWx0fSLyMWMie4Q_A4gfuDIXJJTvU1jTsSV1U,10290 +google/ai/generativelanguage_v1alpha/services/model_service/transports/grpc.py,sha256=oXMQUwPpslP8wZsgycDM9RmpJBgumH5Lkwl2XFp-GDY,25954 +google/ai/generativelanguage_v1alpha/services/model_service/transports/grpc_asyncio.py,sha256=VlzGc7BnTWM9iT74FSVSRfzbUOuen1rud3zsdxm4Ix8,28759 +google/ai/generativelanguage_v1alpha/services/model_service/transports/rest.py,sha256=gaDakNfKGTMfl-cYA2A0DF41Obwr-hMEqQyFclv2xTg,72809 +google/ai/generativelanguage_v1alpha/services/model_service/transports/rest_base.py,sha256=dAhL5FYak7ZjywvgotWiA_tl13XB9xJIHpklOjGPeHQ,17063 +google/ai/generativelanguage_v1alpha/services/permission_service/__init__.py,sha256=behL4ZUeo3vAUjDn1OyooSR9hWxeI1DuO7ENp5yhkPM,781 +google/ai/generativelanguage_v1alpha/services/permission_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/async_client.py,sha256=OOoESs4xa3Dwgkq17rPHTpgu0uBYVdOvg8q83uj8zLo,48853 +google/ai/generativelanguage_v1alpha/services/permission_service/client.py,sha256=6Kqb_1gtb4s2oTJaPXedn2xST31Vs_M4-xQyXxCSqQA,63877 +google/ai/generativelanguage_v1alpha/services/permission_service/pagers.py,sha256=YZBkwpitQhZOBnqIVILifqjIFm2BXviTxLkfe2lxDio,7970 +google/ai/generativelanguage_v1alpha/services/permission_service/transports/__init__.py,sha256=qPGt9EDhhh05gzAGSssRTyMhYeGzFOWphmHNXvHN7Ck,1442 +google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/permission_service/transports/base.py,sha256=JyImjOSqZPp21aaZrG_ZZzPVIvjDNAHfTCKVc4tWKEs,9822 +google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc.py,sha256=UcZobEkoMPwbH79aIUuMKkUZqh_XS_MeQRXGrQfjdjY,24014 +google/ai/generativelanguage_v1alpha/services/permission_service/transports/grpc_asyncio.py,sha256=nNDfIgFFymVpYiMh2_Jhf2klk3AvBx4VXhaQNI2AnKU,26584 +google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest.py,sha256=TWaflhxyHMcj7naRoYU0LcJQ20r05SwBEwVYAXvQI8k,67716 +google/ai/generativelanguage_v1alpha/services/permission_service/transports/rest_base.py,sha256=k875g1ftHJjerAFlv6w2-0K5fLR7blbqH7J-agvILEA,17870 +google/ai/generativelanguage_v1alpha/services/prediction_service/__init__.py,sha256=LZbL-fR6IaTuqkkW9_48PnmUelMndDxEcQZccHmQN14,781 +google/ai/generativelanguage_v1alpha/services/prediction_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/async_client.py,sha256=Qq-KrFqN0MN60jXxp8ULFX8YGdG_6u62NPsSzgS71FU,22704 +google/ai/generativelanguage_v1alpha/services/prediction_service/client.py,sha256=ZC0NnnuAPXjI_XkaRLeTmJfGubRYxyydJpnrTg4cSpE,38056 +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/__init__.py,sha256=KSNsz6RJc_qcW706TMwBGah-_BrHAXEz4NT43hgs-nM,1442 +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/base.py,sha256=Nz0NQdSgavZfHT8vcnohZwwpOwK3cT_EUecjIpO62tU,7275 +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/grpc.py,sha256=6xozfS3yT6JL7xCvkiy9rqPf7NQvPf29qbtXsBZm3zQ,17705 +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/grpc_asyncio.py,sha256=y3PKAb7u24FXR82GupwkwWcrOP3MfjlwHzdaN2DtJ2A,19169 +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/rest.py,sha256=ANC7t32SjT1GtOipraJ7SWC8GZCLugS19L5elfeTnw8,28191 +google/ai/generativelanguage_v1alpha/services/prediction_service/transports/rest_base.py,sha256=o2x9amVif0FQzuCAS05OH-8cQu1xJ4r5XjCRpPm4B3Q,7903 +google/ai/generativelanguage_v1alpha/services/retriever_service/__init__.py,sha256=YCGNT6veyUuOsWmqEYgrUeKwKDUgHvoQZMpAk62NnBM,777 +google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/async_client.py,sha256=ETxRaT_wzOsFI2z3sp8mcViMBnZWxaOou0IraWHSTOM,106467 +google/ai/generativelanguage_v1alpha/services/retriever_service/client.py,sha256=J96gMNYLSMfOkFK2gjVtPXOjHiD5ua_yDEXAeGl9YiY,120919 +google/ai/generativelanguage_v1alpha/services/retriever_service/pagers.py,sha256=0Qqs4AACD1Tdm4oG6eZtB4IOKFda4KVZIEo_u3f5C-M,20788 +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__init__.py,sha256=sX5X5kBM56pf25AiCDyA8-UrMTYPnjsDqOKf9Ivrif0,1428 +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/base.py,sha256=kxyrldQXEx1B8e7SWTh2NLlcCckelMVUEf1EnxKBe8E,15799 +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc.py,sha256=E3xsh4bOogByKHwUKOUwGGunvn2dKP-LG87przBgu5M,39136 +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/grpc_asyncio.py,sha256=m-6GKp5MkYqoiLi1LslmntEUbfy6xaWHEL3nhakOGwU,44578 +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest.py,sha256=U_3qBRzrrF7jXF6c8rMQcRnTDenJaTe8LXbH0J2wKe0,164167 +google/ai/generativelanguage_v1alpha/services/retriever_service/transports/rest_base.py,sha256=XKH-E8e076W8OvImWqPfBjLC9Gh7y8p9-LnCwG47788,41654 +google/ai/generativelanguage_v1alpha/services/text_service/__init__.py,sha256=vyOi-X8K2gCPrmlXaXqxMKUxjmg_7js-kYLt8pRibX4,757 +google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/async_client.py,sha256=4XFUW0uYdNQhnPVI7Eyf6beBDM--8bbACKzbEnBdwSw,42359 +google/ai/generativelanguage_v1alpha/services/text_service/client.py,sha256=fhGqR29Q-sZR8zJ5iAAzcMzpOKlNdCBvO2tcZufxosA,57344 +google/ai/generativelanguage_v1alpha/services/text_service/transports/__init__.py,sha256=MNfRZuaAwV2XGCPox94Y4c16viRBF76vwacyPiOQeZ0,1358 +google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/services/text_service/transports/base.py,sha256=goN3sC0Epp3fWHyYe2ryVck6CmS9rASS9KRR4anmzZo,8711 +google/ai/generativelanguage_v1alpha/services/text_service/transports/grpc.py,sha256=7ltdL16FiWFVeWjYRLRa__LWcT3KB4TUz8GoH5PeRvI,21435 +google/ai/generativelanguage_v1alpha/services/text_service/transports/grpc_asyncio.py,sha256=Oc2N5llYoSqEO0EK3ULUEMSrMKmaE74pJP1OTpbCF7U,23545 +google/ai/generativelanguage_v1alpha/services/text_service/transports/rest.py,sha256=PRsOFQB68HNvypU-FWTtaaeD-tayG_GKViuKE8neuXo,51329 +google/ai/generativelanguage_v1alpha/services/text_service/transports/rest_base.py,sha256=3AFuj9cEP5CV5fCIPIzS1KeDrNDDfHmwuT160Ndmz_Y,13837 +google/ai/generativelanguage_v1alpha/types/__init__.py,sha256=f8yHeobSIoOur1kwNUmh6xSHmAjHHDVuqu2qESy7c1E,9219 +google/ai/generativelanguage_v1alpha/types/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/cache_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/cached_content.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/citation.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/content.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/discuss_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/file.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/file_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/generative_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/model.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/model_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/permission.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/permission_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/prediction_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/retriever.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/retriever_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/safety.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/text_service.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/__pycache__/tuned_model.cpython-312.pyc,, +google/ai/generativelanguage_v1alpha/types/cache_service.py,sha256=DfPZo3ePSNjO-jEsoMRoHlrmPRChv4gohdIfYL_4zNk,4790 +google/ai/generativelanguage_v1alpha/types/cached_content.py,sha256=bGH6eWJwQ1ArsAWoDY3dM-IdLg3DoFMvpZXllXDw9XE,6177 +google/ai/generativelanguage_v1alpha/types/citation.py,sha256=darCP6V52VTZT79hQMOYOdVIeeLmT5M1_v05jr74GCE,2905 +google/ai/generativelanguage_v1alpha/types/content.py,sha256=nOolc497p8OaqlthR1G8gdhJO6fBdxI_TTNoVA-Va1o,25928 +google/ai/generativelanguage_v1alpha/types/discuss_service.py,sha256=e6cQgKmShZ9vYnVX_02tLk8y6DAhYkt4UDUdszZRjGc,11613 +google/ai/generativelanguage_v1alpha/types/file.py,sha256=Kz3VDubxws7Ym7oz28N7qbo8-NMv2T_a-W7LZdIOq50,5442 +google/ai/generativelanguage_v1alpha/types/file_service.py,sha256=d55gFJcPFaq_J0_37x7rGDSmnrJc0RpsSgE0tjs_E-o,3560 +google/ai/generativelanguage_v1alpha/types/generative_service.py,sha256=JCShTSRInUaCcp1MzZPKxq4R1rWk_bwRPVZIx7Sv2MM,77627 +google/ai/generativelanguage_v1alpha/types/model.py,sha256=3sNGuNo4mXkL4QSZBkEw2a5wTqVhDseSpCdP9-Mj350,5381 +google/ai/generativelanguage_v1alpha/types/model_service.py,sha256=pLFwTVh9XoQZsX8sim2c-cj_9Dax2Nr8wlbYuUC9KIg,9628 +google/ai/generativelanguage_v1alpha/types/permission.py,sha256=NNRKfgaMNUeYWEwpiGrguYBlj3p-YR4FOlgXdOGh43Q,4533 +google/ai/generativelanguage_v1alpha/types/permission_service.py,sha256=_ZyFtv4jFm7I1cbm0kQj5RroqkPcI-HfQ5DnbYbBPWo,6367 +google/ai/generativelanguage_v1alpha/types/prediction_service.py,sha256=IZj6AcprpOlDcL5jc7fy7_YowX0c6P7GP13dZIeJS3w,2353 +google/ai/generativelanguage_v1alpha/types/retriever.py,sha256=1uTso7OO06CV1wPX6cPFMVA81-Hbq5b1Lz8gNgrlCfI,13711 +google/ai/generativelanguage_v1alpha/types/retriever_service.py,sha256=bpQjWY9nEdu5viZ4PQEiIj3akLNZ2zE8j950BnXpVXs,24490 +google/ai/generativelanguage_v1alpha/types/safety.py,sha256=1NkveSupNE9vCBXlRzI7DiLhnM5sVRfMqiF4GwpKK2A,8949 +google/ai/generativelanguage_v1alpha/types/text_service.py,sha256=90gKzSSnQIbX7RM5gIy7GwUlLSnxW_6zjmDsJX3xcMQ,14391 +google/ai/generativelanguage_v1alpha/types/tuned_model.py,sha256=b637NnX6zhjSBeIPHOCkKi_2ix3JSmr4oU3QOSg5s0s,17319 +google/ai/generativelanguage_v1beta/__init__.py,sha256=fwB6WLrNr1Mscfb_uVrmOUis09_E96q2YzNkyCOFNqA,9935 +google/ai/generativelanguage_v1beta/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/__pycache__/gapic_version.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/gapic_metadata.json,sha256=TnNHJwMO2rRzy9CoGnSrzV3JJMxvC_WUr3muY7DxnMg,24241 +google/ai/generativelanguage_v1beta/gapic_version.py,sha256=fW_Qd_01eJgNZqYHYqEr7_qs9RoCC6BLcI27EhqRscA,653 +google/ai/generativelanguage_v1beta/py.typed,sha256=HcupzCIj7v3Z4_cqbaAdvF4JVO9LpsSGq46cfaF6HF4,89 +google/ai/generativelanguage_v1beta/services/__init__.py,sha256=o-GCU1hbG5VXrOW7hUl_JSImemJCYPrMpZ9mIWck4h4,600 +google/ai/generativelanguage_v1beta/services/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/__init__.py,sha256=H5m8u77y8Pqx2jLhJXXTNWFcJGkqTAaYON5l5-xXu2s,761 +google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/async_client.py,sha256=kfmRgl3sTqIGxahSBDwuGNvJhKz3zxs5m9hQ_gsCJAM,40561 +google/ai/generativelanguage_v1beta/services/cache_service/client.py,sha256=ZZTI5YBwDGWugz36vmXL0_tKuaP7F029EH6tFeL2nrY,55725 +google/ai/generativelanguage_v1beta/services/cache_service/pagers.py,sha256=xqD-t7GiQvTvjLg_D_y0zsBrZU3KiAjSPRv3TKG9bwU,8022 +google/ai/generativelanguage_v1beta/services/cache_service/transports/__init__.py,sha256=K8mqEPq-LoNTzde1G34_QLKwttab3jSPBWOXsSBEQfU,1372 +google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/cache_service/transports/base.py,sha256=HOPSVanNsV9a1vbzDWWOU8ccelgn3JqSvd1X2BiPoI4,9449 +google/ai/generativelanguage_v1beta/services/cache_service/transports/grpc.py,sha256=WAlkivSFz5hh2uGgCP12DMvMH81-Has5B4T3yPkYX8M,22993 +google/ai/generativelanguage_v1beta/services/cache_service/transports/grpc_asyncio.py,sha256=i98laHEagcyzVRNp1F9fB4NiBGgSKa2u3WU2xo5s88A,25371 +google/ai/generativelanguage_v1beta/services/cache_service/transports/rest.py,sha256=hJa1vtcrH-T2y3rJJI_WT-vBGyYlYbz2A-cekgn1faQ,57506 +google/ai/generativelanguage_v1beta/services/cache_service/transports/rest_base.py,sha256=hvm33hixZh4FQBiT0dcNsLwYGnXtafLKV9W_TGQk3WM,14451 +google/ai/generativelanguage_v1beta/services/discuss_service/__init__.py,sha256=bHfunJdqzuw4aJIGR4Enuzw0TaD-9pAdZ0KRKKN0-lg,769 +google/ai/generativelanguage_v1beta/services/discuss_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/async_client.py,sha256=hpIMs35-1egI8I9ZC2385We9FFwfERI-muYIS8WE7MI,31122 +google/ai/generativelanguage_v1beta/services/discuss_service/client.py,sha256=YxJ9Psk3LuNdtcCpTg3B69W90w54F2_pNQm9yIobfOs,46328 +google/ai/generativelanguage_v1beta/services/discuss_service/transports/__init__.py,sha256=PQWhSfmHneuxrGSr6ZTTUEltxvYMtiM9ZT06fx0EtH8,1400 +google/ai/generativelanguage_v1beta/services/discuss_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/discuss_service/transports/base.py,sha256=XSP07C8p1VkouPaa6OOD9S4PiD_p9PRZGBfdWe2W9As,8515 +google/ai/generativelanguage_v1beta/services/discuss_service/transports/grpc.py,sha256=EFaUZjjJK2dqH3bNqxH8aSEHVDMribCJiUE5YKvGjxw,19243 +google/ai/generativelanguage_v1beta/services/discuss_service/transports/grpc_asyncio.py,sha256=L5n10HJKlp8_PuH3lztrX9f9RrbXtVPbBy3ncUnubU0,21624 +google/ai/generativelanguage_v1beta/services/discuss_service/transports/rest.py,sha256=nqMqR_qA9qM_pksLmPa2P-LAXMxcwO_2s0CeA_SmsAk,36615 +google/ai/generativelanguage_v1beta/services/discuss_service/transports/rest_base.py,sha256=rb7EhBzdoW2IZHNjHHfSe3USMxMjWl-Ti0RRU8jIIl8,9857 +google/ai/generativelanguage_v1beta/services/file_service/__init__.py,sha256=0_yUEpYFfHmTaikAa8MHtCpyDPYvEdBlOnjNQjY9jDg,757 +google/ai/generativelanguage_v1beta/services/file_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/async_client.py,sha256=WJL0017xP4K99OmmXicAt84Srzvbd4ngrx0L0L_Cjvk,32583 +google/ai/generativelanguage_v1beta/services/file_service/client.py,sha256=tXwM5YxgE-Ff-r7xAFbQR0_p9jOeVzu3zq9_F7GjtjI,47558 +google/ai/generativelanguage_v1beta/services/file_service/pagers.py,sha256=cTBXiF2eUVgI2TfDdS3my40KUyj6ky2maY5EQxfDjos,7685 +google/ai/generativelanguage_v1beta/services/file_service/transports/__init__.py,sha256=lRbStijLPXnAlZMS9QkGBzI8uMD4KmHBEMTWlkaPkqU,1358 +google/ai/generativelanguage_v1beta/services/file_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/file_service/transports/base.py,sha256=471Bu9dbvqLZwmblrIe1iqIv6qEkTJ4c_KMK39y2KN4,8517 +google/ai/generativelanguage_v1beta/services/file_service/transports/grpc.py,sha256=ZFuFjdhcqTSdA1fudxWvDznPnR-EUCwxkpDFzPxclS4,20869 +google/ai/generativelanguage_v1beta/services/file_service/transports/grpc_asyncio.py,sha256=U_oKh8yTq9O8ndVpiYBtTv4IhCjF9ihxSLQ1uWBdkzE,22943 +google/ai/generativelanguage_v1beta/services/file_service/transports/rest.py,sha256=ZaXd9YZiWDMyGwzilTGmGhrqQ9BHyyLMXuCi1w5YUXA,47337 +google/ai/generativelanguage_v1beta/services/file_service/transports/rest_base.py,sha256=SSRVgR9UKXD97L-2EbXAUP10zOcline5YpAc_wSIuwg,11656 +google/ai/generativelanguage_v1beta/services/generative_service/__init__.py,sha256=D6qhoNZtllR4Djqpaod4xflCuIheC6SuMJqaLug6QK0,781 +google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/async_client.py,sha256=WegxTtRmUp9CtWerg7BSL8SlyGwHbcw5F0cz9XFxHi8,55482 +google/ai/generativelanguage_v1beta/services/generative_service/client.py,sha256=14aUxJRNsKFIlQrNwmGvKzL79a6TqiHIXKuDbrENkDE,70623 +google/ai/generativelanguage_v1beta/services/generative_service/transports/__init__.py,sha256=E1QrkH5RHJcDSs0hDm6O7i2pM1NEidRh9-NCCo7s-2o,1442 +google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/generative_service/transports/base.py,sha256=jFlroT-rh5jmQikDJDjDKPWV8gosbbHGDMe8S1koesg,11954 +google/ai/generativelanguage_v1beta/services/generative_service/transports/grpc.py,sha256=9ovmiLre8DVHligxFRV7nQd7f_4bJXriT2gLq96nG9Y,25075 +google/ai/generativelanguage_v1beta/services/generative_service/transports/grpc_asyncio.py,sha256=YIrY5iorKwFkSFk0cjQ4bGFvCasOC82brY9a5_aSt-k,29694 +google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py,sha256=3R1DEhsfKOpNlHSbLulQYlHv5zJ9Vl5Qdmcm85Sg8v8,68459 +google/ai/generativelanguage_v1beta/services/generative_service/transports/rest_base.py,sha256=PEtW1h9_STU-G1uCZ_iC-8bs5DX9fdGBlK0p8QJI0g0,18035 +google/ai/generativelanguage_v1beta/services/model_service/__init__.py,sha256=oY53bpew0sqaAPYqhoOV0CD3AQbo7OLP04aNoEFaNGc,761 +google/ai/generativelanguage_v1beta/services/model_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/async_client.py,sha256=nIbz7JxzXhegKrvOJxA-dKJYb7SdqEZZXtZuvMAIq6Y,53721 +google/ai/generativelanguage_v1beta/services/model_service/client.py,sha256=tjFOu6sxE5tMgkhIFoRfhsbmq7_L8joHdSCVoX6flhw,68707 +google/ai/generativelanguage_v1beta/services/model_service/pagers.py,sha256=v5y7ONbtrOj-otxmXMv7MNJbRZ4nhbekqnevWx7ZVqM,14300 +google/ai/generativelanguage_v1beta/services/model_service/transports/__init__.py,sha256=2wzh7QZZoUpcSLQ0d7q_LeOmCeWZyZwP2sd-ir9Xl_I,1372 +google/ai/generativelanguage_v1beta/services/model_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/model_service/transports/base.py,sha256=dr9jDGvdiYvz0HLL_SjUXogQCzrCzBkNK6nSXmapMEA,12680 +google/ai/generativelanguage_v1beta/services/model_service/transports/grpc.py,sha256=CQSGdDkHLMQ5slpYWgoBus_gvgTV64X7jLFo79C4XKY,25942 +google/ai/generativelanguage_v1beta/services/model_service/transports/grpc_asyncio.py,sha256=XIdGEFv62nC0NKe0Y-Uffw0kxjBjHMPr71FBlSw-f4g,31176 +google/ai/generativelanguage_v1beta/services/model_service/transports/rest.py,sha256=z480jZR13LgSf9W0Ltv2uUE89EjQaVn7uVTuGjXTW1M,72766 +google/ai/generativelanguage_v1beta/services/model_service/transports/rest_base.py,sha256=74ZfNhdT9YPg0hpu11xxvESGrsraa3O7Vjp4tuBpWQo,17048 +google/ai/generativelanguage_v1beta/services/permission_service/__init__.py,sha256=behL4ZUeo3vAUjDn1OyooSR9hWxeI1DuO7ENp5yhkPM,781 +google/ai/generativelanguage_v1beta/services/permission_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/async_client.py,sha256=VYODR_pXgrDV_9IMPnW9iEsRUMJzSA1XNFQqcLwUBOY,48814 +google/ai/generativelanguage_v1beta/services/permission_service/client.py,sha256=qb9uxlt_nWP1-0NmoPr--3zmy38sMqX_fAFoU8PyJc4,63838 +google/ai/generativelanguage_v1beta/services/permission_service/pagers.py,sha256=zeYHVE3I7qfu59qcTyvQ5sHSZGsv8hN74wheChMd1pE,7961 +google/ai/generativelanguage_v1beta/services/permission_service/transports/__init__.py,sha256=qPGt9EDhhh05gzAGSssRTyMhYeGzFOWphmHNXvHN7Ck,1442 +google/ai/generativelanguage_v1beta/services/permission_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/permission_service/transports/base.py,sha256=0FMB0ZHzhk5p9Dn1lQceWYjNbzUnaF6Q-71C7G0qnqM,11528 +google/ai/generativelanguage_v1beta/services/permission_service/transports/grpc.py,sha256=FgfKhdeL_g3m14YrKy0Nkhx7VfeWmy49cVGj4QjtV2U,24003 +google/ai/generativelanguage_v1beta/services/permission_service/transports/grpc_asyncio.py,sha256=6XlxnecWFskWQn2XevSIQMgnBrt353aGPcnPOzBYvUo,28308 +google/ai/generativelanguage_v1beta/services/permission_service/transports/rest.py,sha256=4Wpg6jnLF2eEKsXRjKnkon--s4EUR0EfZh8RCAiO0z0,67683 +google/ai/generativelanguage_v1beta/services/permission_service/transports/rest_base.py,sha256=iOxlIaKI_sRPcmgX76amtK0I63JD2SqOpodfKMS7B3o,17851 +google/ai/generativelanguage_v1beta/services/prediction_service/__init__.py,sha256=LZbL-fR6IaTuqkkW9_48PnmUelMndDxEcQZccHmQN14,781 +google/ai/generativelanguage_v1beta/services/prediction_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/async_client.py,sha256=OtcrsxwFwBGm5XmY8PUTrPxhA9hrHAqNpppn6EdpYj8,22692 +google/ai/generativelanguage_v1beta/services/prediction_service/client.py,sha256=P0Izyrim5CnvMnc0iqqNalO25IkuuNe5AatBeNddE-0,38044 +google/ai/generativelanguage_v1beta/services/prediction_service/transports/__init__.py,sha256=KSNsz6RJc_qcW706TMwBGah-_BrHAXEz4NT43hgs-nM,1442 +google/ai/generativelanguage_v1beta/services/prediction_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/prediction_service/transports/base.py,sha256=LSRV5m-t54bU1uLTAW2Z-smEWJoOAfM7mrnO44bS1hQ,7273 +google/ai/generativelanguage_v1beta/services/prediction_service/transports/grpc.py,sha256=jKPBxfAChCgEr_jo6tHu8dFPwrbgWMzwmZihG5fBBv0,17701 +google/ai/generativelanguage_v1beta/services/prediction_service/transports/grpc_asyncio.py,sha256=R6OyX02stW_d92nP7dT5VI6DP9p3-MQhwR7bkbwRm9w,19165 +google/ai/generativelanguage_v1beta/services/prediction_service/transports/rest.py,sha256=5pxBEwnnOMhpIpX3cPyzfuxJFopW34EwNULGNkfX8nI,28177 +google/ai/generativelanguage_v1beta/services/prediction_service/transports/rest_base.py,sha256=yn2uGW6Gumwvt3sSRiwT-axmjgBzNoxuIlv_DIaIXhQ,7896 +google/ai/generativelanguage_v1beta/services/retriever_service/__init__.py,sha256=YCGNT6veyUuOsWmqEYgrUeKwKDUgHvoQZMpAk62NnBM,777 +google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/async_client.py,sha256=czCnIskuIXZEpgqwNNkWboVhjQ5_0w9di_HN7gBCF0E,106354 +google/ai/generativelanguage_v1beta/services/retriever_service/client.py,sha256=7BRM58nwVxWypkxKvNwmHw8jY0aknfxUctLWMHnmP_s,120806 +google/ai/generativelanguage_v1beta/services/retriever_service/pagers.py,sha256=Yw5SVSPbvtcAPmYyQEfWekbpf5I0-5geKnYwmPV8Rio,20763 +google/ai/generativelanguage_v1beta/services/retriever_service/transports/__init__.py,sha256=sX5X5kBM56pf25AiCDyA8-UrMTYPnjsDqOKf9Ivrif0,1428 +google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/retriever_service/transports/base.py,sha256=CXTB19VFudtZtNIC_SwGhWvj0hmMo98osZ6QwBq8oX4,21269 +google/ai/generativelanguage_v1beta/services/retriever_service/transports/grpc.py,sha256=OXgq4RaGrwLg8RrXTBMtCp5wCjVp-M-YJzooTbJp1ZI,39113 +google/ai/generativelanguage_v1beta/services/retriever_service/transports/grpc_asyncio.py,sha256=zY9lTIS_F2nE4qdNcWF0Vrs_pnqQbBe14KKVZSETL8M,50107 +google/ai/generativelanguage_v1beta/services/retriever_service/transports/rest.py,sha256=uI74qUl5dNgj8DeV8-PMty4YN8qNdOFf8BhBFf1dChQ,164086 +google/ai/generativelanguage_v1beta/services/retriever_service/transports/rest_base.py,sha256=vG6HHYFmInjKnjSGc6b_j22amoMNspGVsCaVON99Vkw,41628 +google/ai/generativelanguage_v1beta/services/text_service/__init__.py,sha256=vyOi-X8K2gCPrmlXaXqxMKUxjmg_7js-kYLt8pRibX4,757 +google/ai/generativelanguage_v1beta/services/text_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/async_client.py,sha256=whtNiq9Kv-XiX-VuVFAzu7DtOGXu1wmY3CEWd-xu3EY,42330 +google/ai/generativelanguage_v1beta/services/text_service/client.py,sha256=t-cdFB18lpIWYkMS0t4Wx-ielFiBq-0V6E8MmgnaxiA,57315 +google/ai/generativelanguage_v1beta/services/text_service/transports/__init__.py,sha256=MNfRZuaAwV2XGCPox94Y4c16viRBF76vwacyPiOQeZ0,1358 +google/ai/generativelanguage_v1beta/services/text_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/services/text_service/transports/base.py,sha256=4sTNnxp7CGQk3D3levxdNkB8WZk46tSyfRSHuiFFj58,10077 +google/ai/generativelanguage_v1beta/services/text_service/transports/grpc.py,sha256=DoVhxnKkTmNkEbvrBZKgovWucPd5r5yvYLOo_fVtpyo,21428 +google/ai/generativelanguage_v1beta/services/text_service/transports/grpc_asyncio.py,sha256=23JifVKTBz1QrWwrwmF1Cm09aVjJ-Yoybg8YkQqaubE,24926 +google/ai/generativelanguage_v1beta/services/text_service/transports/rest.py,sha256=FQnyK0gXRYrHjQeg6M5UmA1IYBYZhqA5FtV1KwbGI20,51304 +google/ai/generativelanguage_v1beta/services/text_service/transports/rest_base.py,sha256=fvW8ZYY1oqG0qIKz8VC1HHITNNX39jcZo7xAWJf9jAg,13826 +google/ai/generativelanguage_v1beta/types/__init__.py,sha256=3iVOvaSE4D9BSoZtNtzhMETqlhXOwXAk67UxZc4K1ZA,8321 +google/ai/generativelanguage_v1beta/types/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/cache_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/cached_content.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/citation.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/content.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/discuss_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/file.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/file_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/generative_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/model.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/model_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/permission.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/permission_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/prediction_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/retriever.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/retriever_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/safety.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/text_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/__pycache__/tuned_model.cpython-312.pyc,, +google/ai/generativelanguage_v1beta/types/cache_service.py,sha256=lxySa5abv-kUHrIMG5BTappZUD58WelTWJbzWZ5zYIk,4785 +google/ai/generativelanguage_v1beta/types/cached_content.py,sha256=sK5ycelj40KUE8G7ZpCCO6M_TDROmQdcNR9TIeae04U,6170 +google/ai/generativelanguage_v1beta/types/citation.py,sha256=POi74azJlvfb3dL01Ze9qeJ6SXk-V_7hTZTbmj1nvWE,2903 +google/ai/generativelanguage_v1beta/types/content.py,sha256=ITjmtrmaL2Mi09nakqOQLtHpCfQ06xtRk5lkk5lTQ-o,25899 +google/ai/generativelanguage_v1beta/types/discuss_service.py,sha256=C5wkTuD0KbBdkMvnUKGC_7Vz7iDDTihq69Xk3uk3Osc,11601 +google/ai/generativelanguage_v1beta/types/file.py,sha256=MbDAIhhiGH7kbzi2a8SjvdI6Z57tthfwaaj8yxpoEwA,5439 +google/ai/generativelanguage_v1beta/types/file_service.py,sha256=OQ6kUSqGNvhmzossZlexku1oDcNIfcM8ZTkSKjZW5_c,3555 +google/ai/generativelanguage_v1beta/types/generative_service.py,sha256=x8QMrXjiu-sgLeWtbJSERw5a3pNucgMPGqVBZkzVC9A,62951 +google/ai/generativelanguage_v1beta/types/model.py,sha256=KUYIw1bNxNjFild1uR7sKul3M417B9NysuSwQtPHTj8,5380 +google/ai/generativelanguage_v1beta/types/model_service.py,sha256=p9ceM1_GxSRiOntFcMapaq7aISBRK-Otgdpd6XmTQjc,9620 +google/ai/generativelanguage_v1beta/types/permission.py,sha256=qVk9Yu5cPJOgYGQAjiGa5vt2SQvqxZLiWtqkAqqmx0o,4530 +google/ai/generativelanguage_v1beta/types/permission_service.py,sha256=pI0oaopOeylDBj7ckskMWPzNE1JwEnBzzYVB0r-UP-c,6362 +google/ai/generativelanguage_v1beta/types/prediction_service.py,sha256=x7VRjLWQQY-a3tlU1hI-2k62wry1lvs4ilqOJZhCsO4,2351 +google/ai/generativelanguage_v1beta/types/retriever.py,sha256=qx8kL6RrCar5wuvcRztzuiiGxM2KzQERUIYWYpt_A8g,13703 +google/ai/generativelanguage_v1beta/types/retriever_service.py,sha256=BCJORrju6YzTiwqe1kbZ544HYTkaJByrOHcqCcxkDiQ,24469 +google/ai/generativelanguage_v1beta/types/safety.py,sha256=iFrRUgUtYiJBmfF8smdA3m2Q4McJka_782J9hcIyi54,8941 +google/ai/generativelanguage_v1beta/types/text_service.py,sha256=C0YkGGA2CJwDA_2TEAWjdmijuaNdiYaar2VL0RhFe-k,14378 +google/ai/generativelanguage_v1beta/types/tuned_model.py,sha256=zINSSvzBWSfbyA176T09OfKtB_z6267JBFjF92T7vXM,14112 +google/ai/generativelanguage_v1beta2/__init__.py,sha256=isDAArPIRfibbPeZsu28otwKbvGeLckuiRCjGO4NBl4,2426 +google/ai/generativelanguage_v1beta2/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/__pycache__/gapic_version.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/gapic_metadata.json,sha256=fGGrbso66IVegGTZj-_C9HzFl52ZA1QEVMI-PFk2cxA,3627 +google/ai/generativelanguage_v1beta2/gapic_version.py,sha256=fW_Qd_01eJgNZqYHYqEr7_qs9RoCC6BLcI27EhqRscA,653 +google/ai/generativelanguage_v1beta2/py.typed,sha256=HcupzCIj7v3Z4_cqbaAdvF4JVO9LpsSGq46cfaF6HF4,89 +google/ai/generativelanguage_v1beta2/services/__init__.py,sha256=o-GCU1hbG5VXrOW7hUl_JSImemJCYPrMpZ9mIWck4h4,600 +google/ai/generativelanguage_v1beta2/services/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/__init__.py,sha256=bHfunJdqzuw4aJIGR4Enuzw0TaD-9pAdZ0KRKKN0-lg,769 +google/ai/generativelanguage_v1beta2/services/discuss_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/async_client.py,sha256=Yz0jbACTaSGCjCRSxxFGP_3J7e6fjm1iogybXWzWCsM,26503 +google/ai/generativelanguage_v1beta2/services/discuss_service/client.py,sha256=tk8nWEoZBTd-J0CNmJx3MGEumi6KohjQWz9W_vZ0x7c,41785 +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/__init__.py,sha256=PQWhSfmHneuxrGSr6ZTTUEltxvYMtiM9ZT06fx0EtH8,1400 +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/base.py,sha256=pbAQGleAPr0vsrslHy8tzOgCHkcqAIeibnLM5XK1QuI,7528 +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/grpc.py,sha256=28CyuQ2Iy-Ze_bo776oLSACNXwZ5yq6Y_mF0AkgMR2o,17466 +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/grpc_asyncio.py,sha256=Rt5Gwi-dYBdNzoa5H3FKcE32ZvDGo4rzWIvbfeffIHY,19481 +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/rest.py,sha256=vkVRXsEfFpv33CdHTCYwkfKacKeRXqyVn1vctPyQs8E,23215 +google/ai/generativelanguage_v1beta2/services/discuss_service/transports/rest_base.py,sha256=CPRB3gksP0DnuaY2S28rkEGp5qm9J9HoQ_Jr66SYx7E,7529 +google/ai/generativelanguage_v1beta2/services/model_service/__init__.py,sha256=oY53bpew0sqaAPYqhoOV0CD3AQbo7OLP04aNoEFaNGc,761 +google/ai/generativelanguage_v1beta2/services/model_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/async_client.py,sha256=qI-VrXUIqpN5HKQja1IS8FZcxT_pOq37Ugk2INf89CA,22907 +google/ai/generativelanguage_v1beta2/services/model_service/client.py,sha256=G9OLtR_1a-KtNwwWR_s1CSRFEmWbmLhoyh5CLBMikh4,38134 +google/ai/generativelanguage_v1beta2/services/model_service/pagers.py,sha256=M8DPT5x_nKN7bjUpo8x9sxFitqWQxYO27ia_j0Y7jp8,7740 +google/ai/generativelanguage_v1beta2/services/model_service/transports/__init__.py,sha256=2wzh7QZZoUpcSLQ0d7q_LeOmCeWZyZwP2sd-ir9Xl_I,1372 +google/ai/generativelanguage_v1beta2/services/model_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/model_service/transports/base.py,sha256=yWBo2IgQGhpmwczob4nO7wn8KwXYdOL_ZcBDD4IcUjg,7340 +google/ai/generativelanguage_v1beta2/services/model_service/transports/grpc.py,sha256=STuOxD5bnKnAqFzf-pJg_RJseM6dKtMF_io1s5v1Vc8,16954 +google/ai/generativelanguage_v1beta2/services/model_service/transports/grpc_asyncio.py,sha256=H69__I_hepSoJ7skbzaU3kbFLizgTCdaLdx6jG2ZFec,18964 +google/ai/generativelanguage_v1beta2/services/model_service/transports/rest.py,sha256=b0BhRF-e7zJ_TlP9Vxe9YxfWkiAuVIs2GIDPFz5PSAI,21480 +google/ai/generativelanguage_v1beta2/services/model_service/transports/rest_base.py,sha256=h7V-jNjA5mrATJkglB3-i6bKGlNkZOMRTUsoTrWKLBg,6304 +google/ai/generativelanguage_v1beta2/services/text_service/__init__.py,sha256=vyOi-X8K2gCPrmlXaXqxMKUxjmg_7js-kYLt8pRibX4,757 +google/ai/generativelanguage_v1beta2/services/text_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/async_client.py,sha256=L2sopkTPObFU_7W2Ju1zq9vZpSw42-4unZVjgdnxS2A,26806 +google/ai/generativelanguage_v1beta2/services/text_service/client.py,sha256=Wjxc6pLcN4PMJfUmB8Jxl93oGE0A0hRJljtkgzxjd-o,42043 +google/ai/generativelanguage_v1beta2/services/text_service/transports/__init__.py,sha256=MNfRZuaAwV2XGCPox94Y4c16viRBF76vwacyPiOQeZ0,1358 +google/ai/generativelanguage_v1beta2/services/text_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/services/text_service/transports/base.py,sha256=DAeiWtvxpwx3we3z_A1LPLwQtaTR1z1wY_lv5Zz9NeU,7410 +google/ai/generativelanguage_v1beta2/services/text_service/transports/grpc.py,sha256=fpeUvTnwOau-0q-JWqbsA_gCZiPgmh0oaRMifXOP-Gw,17208 +google/ai/generativelanguage_v1beta2/services/text_service/transports/grpc_asyncio.py,sha256=mhykQZzG3fosLT6_pOKwbv13VJn5Jbd0QvyCljAuTv0,19208 +google/ai/generativelanguage_v1beta2/services/text_service/transports/rest.py,sha256=AojNjvXTdadZs06gyuOhh_Weu2wi7OAZtpigH18BeTg,22234 +google/ai/generativelanguage_v1beta2/services/text_service/transports/rest_base.py,sha256=qUS9SygLg-QLNFpgNd_cOG-yIppSiO60URRhCbIvI1M,7451 +google/ai/generativelanguage_v1beta2/types/__init__.py,sha256=vaSdPFIeiTJaxsAER_ql0R_f3xAlEbKBq2i_5TESIUY,1847 +google/ai/generativelanguage_v1beta2/types/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/types/__pycache__/citation.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/types/__pycache__/discuss_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/types/__pycache__/model.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/types/__pycache__/model_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/types/__pycache__/safety.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/types/__pycache__/text_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta2/types/citation.py,sha256=1hUCvtbxvmnODA8VsmBkSJlL7eXb2oOKnOcK1EOt690,2905 +google/ai/generativelanguage_v1beta2/types/discuss_service.py,sha256=-CTH-y_Q4ZrJ9QKo1-GxnhPZWkmEDihaqeAApHkJJOA,11613 +google/ai/generativelanguage_v1beta2/types/model.py,sha256=aMeWTNF8aMQE_22KgT3H995yHGjRH2oBracjhMrssds,4670 +google/ai/generativelanguage_v1beta2/types/model_service.py,sha256=2dMKF7AWMzupe2d3ObHYsPTHXHoikad3ffZ5QuhcSbk,3158 +google/ai/generativelanguage_v1beta2/types/safety.py,sha256=NAs5uLLZIE_SKZRUsMs5Cr635vyBVNFaSvdgMa8gJKM,7878 +google/ai/generativelanguage_v1beta2/types/text_service.py,sha256=1AVNLv5x5hHuVcaKRcYIEG_OTmf6fqYpNNMuJgDOgiw,10981 +google/ai/generativelanguage_v1beta3/__init__.py,sha256=BqLZH0Mg9gubvZVD3f3Ji1mpmQF6VAneYsJyC-8gtLg,4188 +google/ai/generativelanguage_v1beta3/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/__pycache__/gapic_version.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/gapic_metadata.json,sha256=D3NL-fRU10xwbA-O9Z-DOeijMXDRrARaWMgyw-RNI5w,8993 +google/ai/generativelanguage_v1beta3/gapic_version.py,sha256=fW_Qd_01eJgNZqYHYqEr7_qs9RoCC6BLcI27EhqRscA,653 +google/ai/generativelanguage_v1beta3/py.typed,sha256=HcupzCIj7v3Z4_cqbaAdvF4JVO9LpsSGq46cfaF6HF4,89 +google/ai/generativelanguage_v1beta3/services/__init__.py,sha256=o-GCU1hbG5VXrOW7hUl_JSImemJCYPrMpZ9mIWck4h4,600 +google/ai/generativelanguage_v1beta3/services/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/__init__.py,sha256=bHfunJdqzuw4aJIGR4Enuzw0TaD-9pAdZ0KRKKN0-lg,769 +google/ai/generativelanguage_v1beta3/services/discuss_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/async_client.py,sha256=x0pTzU6tv1s2DYhUeYryITJWFD8SaykwBN5_72gbxgc,26566 +google/ai/generativelanguage_v1beta3/services/discuss_service/client.py,sha256=8FZRQpwOGVADx-NV0UNupvsnVElAT-GapwfidwPlvBk,41848 +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/__init__.py,sha256=PQWhSfmHneuxrGSr6ZTTUEltxvYMtiM9ZT06fx0EtH8,1400 +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/base.py,sha256=_5Klhak-XfIcvlmb7EvgW-WahtvuJuDMqBzSl2xk1iI,6906 +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/grpc.py,sha256=NWe5fDtcXTLEXutHz6D08j8oA-bwDv6uRbjxhbcIGKw,17528 +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/grpc_asyncio.py,sha256=u2tKcu6yhPCffYaL-bwoxLKpOIH7xqzi1jInkgaawq8,18849 +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/rest.py,sha256=NhDjZwAe5EAoa5XJvXKLpxAinciMBF37pnzBa2Tq81w,23277 +google/ai/generativelanguage_v1beta3/services/discuss_service/transports/rest_base.py,sha256=SyHh_eROyDghWJlQA-7lxNeKXTavUWwDxoLH3lTF3ww,7591 +google/ai/generativelanguage_v1beta3/services/model_service/__init__.py,sha256=oY53bpew0sqaAPYqhoOV0CD3AQbo7OLP04aNoEFaNGc,761 +google/ai/generativelanguage_v1beta3/services/model_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/async_client.py,sha256=FYvoDSa8zBoAQ4Rot5tK41924zdfKl6AIjmkOGA-RrA,49499 +google/ai/generativelanguage_v1beta3/services/model_service/client.py,sha256=EUKRPgaPiBqHjzkKwydnxOoEawVkLZi1gPPp_n6699o,64561 +google/ai/generativelanguage_v1beta3/services/model_service/pagers.py,sha256=5gKWW_zV97mORUWLmkLW1Wo4db-NOOqlis6XgumLQNI,14317 +google/ai/generativelanguage_v1beta3/services/model_service/transports/__init__.py,sha256=2wzh7QZZoUpcSLQ0d7q_LeOmCeWZyZwP2sd-ir9Xl_I,1372 +google/ai/generativelanguage_v1beta3/services/model_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/model_service/transports/base.py,sha256=R8mEGa4YGEm_gbmETQu8MwttmC8xq8Xz-61V3aBovQA,9363 +google/ai/generativelanguage_v1beta3/services/model_service/transports/grpc.py,sha256=7OZ-JCHvGso7g59ZBWY4R0KjSi06xqnrzxCrLZZGZfM,23851 +google/ai/generativelanguage_v1beta3/services/model_service/transports/grpc_asyncio.py,sha256=6JSi9FgPgIH-x05hmZMDdGbKoJaXkl5oTAt5T4DDoGM,26290 +google/ai/generativelanguage_v1beta3/services/model_service/transports/rest.py,sha256=4dKtDxOdVc6wjiFOdfblDAivmP6hCcxafvfAMH-DfRY,58481 +google/ai/generativelanguage_v1beta3/services/model_service/transports/rest_base.py,sha256=ECBQVbYOOiIgHx953bwRK6LTR0xlCv77mXNaaIQe1-4,14828 +google/ai/generativelanguage_v1beta3/services/permission_service/__init__.py,sha256=behL4ZUeo3vAUjDn1OyooSR9hWxeI1DuO7ENp5yhkPM,781 +google/ai/generativelanguage_v1beta3/services/permission_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/__pycache__/pagers.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/async_client.py,sha256=OO2_txWohqKirzRWiIctlqXd1dY1dz7qJLxRCWfujRg,44219 +google/ai/generativelanguage_v1beta3/services/permission_service/client.py,sha256=mFv5xN_4Yidcu2PXEVCnrgP7gjc6vTuZGCDTO8IFC40,59637 +google/ai/generativelanguage_v1beta3/services/permission_service/pagers.py,sha256=Uu9Ir1Yj5BvyNHBq8MbBARbzCHEYAKvv4Ci2eV9ZZ6o,7970 +google/ai/generativelanguage_v1beta3/services/permission_service/transports/__init__.py,sha256=qPGt9EDhhh05gzAGSssRTyMhYeGzFOWphmHNXvHN7Ck,1442 +google/ai/generativelanguage_v1beta3/services/permission_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/permission_service/transports/base.py,sha256=N0UoX4a1jehpv9LVHAf6HlKoF-OjT3yvLR6rRpLMr-c,8895 +google/ai/generativelanguage_v1beta3/services/permission_service/transports/grpc.py,sha256=Lbp1CUGxTB63zSu8Hs4pgwvh0MSu91GBX_H43Z5rB54,22294 +google/ai/generativelanguage_v1beta3/services/permission_service/transports/grpc_asyncio.py,sha256=COuO2VWN2tgynzFCieNDSddEmBoHWgEI_P7pafK2kzI,24498 +google/ai/generativelanguage_v1beta3/services/permission_service/transports/rest.py,sha256=jiFvQ8xrcCbb7BAolQ75Ke-VMkrHKMEmpkhbAXv02jY,54253 +google/ai/generativelanguage_v1beta3/services/permission_service/transports/rest_base.py,sha256=SGWFaBW9KAnSfZAtLnxK1y84jeeQpz7maK_pdXtRxhw,14775 +google/ai/generativelanguage_v1beta3/services/text_service/__init__.py,sha256=vyOi-X8K2gCPrmlXaXqxMKUxjmg_7js-kYLt8pRibX4,757 +google/ai/generativelanguage_v1beta3/services/text_service/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/__pycache__/async_client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/__pycache__/client.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/async_client.py,sha256=9fhngf2MQ4c-aX5JXxMU0FRKV6-7coRelkNMt1LQ1is,37884 +google/ai/generativelanguage_v1beta3/services/text_service/client.py,sha256=TPVdWRCXE9nEEVf__CZgljcTXMbASUeZEywEoQRKuqE,52945 +google/ai/generativelanguage_v1beta3/services/text_service/transports/__init__.py,sha256=MNfRZuaAwV2XGCPox94Y4c16viRBF76vwacyPiOQeZ0,1358 +google/ai/generativelanguage_v1beta3/services/text_service/transports/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/transports/__pycache__/base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/transports/__pycache__/grpc.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/transports/__pycache__/grpc_asyncio.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/transports/__pycache__/rest.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/transports/__pycache__/rest_base.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/services/text_service/transports/base.py,sha256=BEytqx1k7uqlsoyStE2kkyTJmltmpOZjCD5G4Q85sHs,7784 +google/ai/generativelanguage_v1beta3/services/text_service/transports/grpc.py,sha256=Ahhtz83qJHfR6OGpmtb-s_GvikSecKUgQQ0xJaiMxVo,19715 +google/ai/generativelanguage_v1beta3/services/text_service/transports/grpc_asyncio.py,sha256=cfM9_GwATu5yINjx5ArqHBuunD1iTSnmsprmQANoCyI,21459 +google/ai/generativelanguage_v1beta3/services/text_service/transports/rest.py,sha256=Dz3H_GIWE3fZPBIeoXWVc9_iz5jIiQW_ickjktJq8ZY,37972 +google/ai/generativelanguage_v1beta3/services/text_service/transports/rest_base.py,sha256=_wCXhN9Vqjj1gz9m4Njkd8ZsqxnRdtWTqVmnzNZi_KE,11563 +google/ai/generativelanguage_v1beta3/types/__init__.py,sha256=JWlef1IYhCP3t3sQeIQc6w2JdLYJxFrRC4L-G9qQhZw,3416 +google/ai/generativelanguage_v1beta3/types/__pycache__/__init__.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/citation.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/discuss_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/model.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/model_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/permission.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/permission_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/safety.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/text_service.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/__pycache__/tuned_model.cpython-312.pyc,, +google/ai/generativelanguage_v1beta3/types/citation.py,sha256=UT56CpPBxmaTICugalNWQBo0oKNqs9AiXNtC8zcWOWk,2905 +google/ai/generativelanguage_v1beta3/types/discuss_service.py,sha256=Cselj-xp-AnIHw4x2Kgk_wjROKXcWpM9Mf_Gisi_voQ,11613 +google/ai/generativelanguage_v1beta3/types/model.py,sha256=nsaz0c2XeYgnbnEF9LIBQIUFAVLtzC-ZgmLw8KdQ_3A,4670 +google/ai/generativelanguage_v1beta3/types/model_service.py,sha256=bF-lD1tgHvSyrltEJjkbUbkfVQGqBO200MjAQ3diIk4,8924 +google/ai/generativelanguage_v1beta3/types/permission.py,sha256=p6M0p92QlgFoV6R2ziJc9vOo39XuSgBN0Tw31He73EM,4460 +google/ai/generativelanguage_v1beta3/types/permission_service.py,sha256=Gg_cRqDYm7GPk9n7Qmnx1AD2f6sACT53tdohbuxEyek,6197 +google/ai/generativelanguage_v1beta3/types/safety.py,sha256=m_iYUVCCZeooS8Nks38Rkj88tb5HXgZwapho2o3JkAc,7974 +google/ai/generativelanguage_v1beta3/types/text_service.py,sha256=Pa-vSY0TzVmS7IQh6Mtb9SFlZoOT_P2GTXc41ny3Ql0,13777 +google/ai/generativelanguage_v1beta3/types/tuned_model.py,sha256=bJynWOgbYgb-ye_qhbKsczDbaw5Arr0KNRZrRvAjIHk,12841 +google_ai_generativelanguage-0.6.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_ai_generativelanguage-0.6.15.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_ai_generativelanguage-0.6.15.dist-info/METADATA,sha256=etmbb7T5lFfbyoV_t61O9b5gDX-EjpOLBkD9s6YSBtw,5708 +google_ai_generativelanguage-0.6.15.dist-info/RECORD,, +google_ai_generativelanguage-0.6.15.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91 +google_ai_generativelanguage-0.6.15.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/WHEEL b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9b78c44519d450e4036a1ea44361a2ac7b1ee300 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.3.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/top_level.txt b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/python_embeded/Lib/site-packages/google_ai_generativelanguage-0.6.15.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/METADATA b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..11b025408db184aa76fbf2c73b7ac52c6a48de8d --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/METADATA @@ -0,0 +1,75 @@ +Metadata-Version: 2.4 +Name: google-api-core +Version: 2.25.1 +Summary: Google API client core library +Author-email: Google LLC +License: Apache 2.0 +Project-URL: Documentation, https://googleapis.dev/python/google-api-core/latest/ +Project-URL: Repository, https://github.com/googleapis/python-api-core +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: googleapis-common-protos<2.0.0,>=1.56.2 +Requires-Dist: protobuf!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<7.0.0,>=3.19.5 +Requires-Dist: proto-plus<2.0.0,>=1.22.3 +Requires-Dist: proto-plus<2.0.0,>=1.25.0; python_version >= "3.13" +Requires-Dist: google-auth<3.0.0,>=2.14.1 +Requires-Dist: requests<3.0.0,>=2.18.0 +Provides-Extra: async-rest +Requires-Dist: google-auth[aiohttp]<3.0.0,>=2.35.0; extra == "async-rest" +Provides-Extra: grpc +Requires-Dist: grpcio<2.0.0,>=1.33.2; extra == "grpc" +Requires-Dist: grpcio<2.0.0,>=1.49.1; python_version >= "3.11" and extra == "grpc" +Requires-Dist: grpcio-status<2.0.0,>=1.33.2; extra == "grpc" +Requires-Dist: grpcio-status<2.0.0,>=1.49.1; python_version >= "3.11" and extra == "grpc" +Provides-Extra: grpcgcp +Requires-Dist: grpcio-gcp<1.0.0,>=0.2.2; extra == "grpcgcp" +Provides-Extra: grpcio-gcp +Requires-Dist: grpcio-gcp<1.0.0,>=0.2.2; extra == "grpcio-gcp" +Dynamic: license-file + +Core Library for Google Client Libraries +======================================== + +|pypi| |versions| + +This library is not meant to stand-alone. Instead it defines +common helpers used by all Google API clients. For more information, see the +`documentation`_. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-api_core.svg + :target: https://pypi.org/project/google-api_core/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-api_core.svg + :target: https://pypi.org/project/google-api_core/ +.. _documentation: https://googleapis.dev/python/google-api-core/latest + + +Supported Python Versions +------------------------- +Python >= 3.7 + + +Unsupported Python Versions +--------------------------- + +Python == 2.7, Python == 3.5, Python == 3.6. + +The last version of this library compatible with Python 2.7 and 3.5 is +`google-api-core==1.31.1`. + +The last version of this library compatible with Python 3.6 is +`google-api-core==2.8.2`. diff --git a/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/RECORD b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b5864b4456024e0bc9ebf74cf3695139bceb5989 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/RECORD @@ -0,0 +1,125 @@ +google/api_core/__init__.py,sha256=bCgLRZtOkaVlSxTPG_o1x4V0w5FJAWREIlnq3kCfqeY,782 +google/api_core/__pycache__/__init__.cpython-312.pyc,, +google/api_core/__pycache__/_rest_streaming_base.cpython-312.pyc,, +google/api_core/__pycache__/bidi.cpython-312.pyc,, +google/api_core/__pycache__/client_info.cpython-312.pyc,, +google/api_core/__pycache__/client_logging.cpython-312.pyc,, +google/api_core/__pycache__/client_options.cpython-312.pyc,, +google/api_core/__pycache__/datetime_helpers.cpython-312.pyc,, +google/api_core/__pycache__/exceptions.cpython-312.pyc,, +google/api_core/__pycache__/extended_operation.cpython-312.pyc,, +google/api_core/__pycache__/general_helpers.cpython-312.pyc,, +google/api_core/__pycache__/grpc_helpers.cpython-312.pyc,, +google/api_core/__pycache__/grpc_helpers_async.cpython-312.pyc,, +google/api_core/__pycache__/iam.cpython-312.pyc,, +google/api_core/__pycache__/operation.cpython-312.pyc,, +google/api_core/__pycache__/operation_async.cpython-312.pyc,, +google/api_core/__pycache__/page_iterator.cpython-312.pyc,, +google/api_core/__pycache__/page_iterator_async.cpython-312.pyc,, +google/api_core/__pycache__/path_template.cpython-312.pyc,, +google/api_core/__pycache__/protobuf_helpers.cpython-312.pyc,, +google/api_core/__pycache__/rest_helpers.cpython-312.pyc,, +google/api_core/__pycache__/rest_streaming.cpython-312.pyc,, +google/api_core/__pycache__/rest_streaming_async.cpython-312.pyc,, +google/api_core/__pycache__/retry_async.cpython-312.pyc,, +google/api_core/__pycache__/timeout.cpython-312.pyc,, +google/api_core/__pycache__/universe.cpython-312.pyc,, +google/api_core/__pycache__/version.cpython-312.pyc,, +google/api_core/__pycache__/version_header.cpython-312.pyc,, +google/api_core/_rest_streaming_base.py,sha256=AlkPe71v0kRUeWP5yn6N1KbxCxKhr-vfQOCgoF6x8ZE,4351 +google/api_core/bidi.py,sha256=uF3Zmgy76WhUtnesEJAKnVlsIOaGMM6Iihoivg9K8Ls,28685 +google/api_core/client_info.py,sha256=A1yzixILdp55Rk8Hu1m7QGlnOh6CGMWhKLNi9TUotRU,4092 +google/api_core/client_logging.py,sha256=o7VrcpJ5yqIfdpBDGKTIIVaqIfl5Ppr_AxiOfyKIGTk,5023 +google/api_core/client_options.py,sha256=3wXyTuP91oqIopt-ZuMqrGO5mP2nZKB-PcxXIHAfOjs,6566 +google/api_core/datetime_helpers.py,sha256=5gFi7n0r-xVImQdj6rQKNwk58m2LcMF9WliXGHbBsDA,9034 +google/api_core/exceptions.py,sha256=5VXhbkcGCrfjo6tzP4hCVh6vakqGM7kZSewVj6pCS8M,21150 +google/api_core/extended_operation.py,sha256=r9xSOblNF35lwn2hrrjUQ-f3JDoo0a4Z8xwOy_VkvL0,8632 +google/api_core/future/__init__.py,sha256=7sToxNNu9c_xqcpmO8dbrcSLOOxplnYOOSXjOX9QIXw,702 +google/api_core/future/__pycache__/__init__.cpython-312.pyc,, +google/api_core/future/__pycache__/_helpers.cpython-312.pyc,, +google/api_core/future/__pycache__/async_future.cpython-312.pyc,, +google/api_core/future/__pycache__/base.cpython-312.pyc,, +google/api_core/future/__pycache__/polling.cpython-312.pyc,, +google/api_core/future/_helpers.py,sha256=jA6m2L1aqlOJA-9NdC1BDosPksZQ7FmLLYWDOrsQOPc,1248 +google/api_core/future/async_future.py,sha256=7rOK0tzud8MCoUwO9AjF-3OQDtELwhtp2ONltSB3GEI,5355 +google/api_core/future/base.py,sha256=SHyudamSWR7EyUsYaQ-XrGGkLeYClSfXfsHIHSqDIYI,1763 +google/api_core/future/polling.py,sha256=0HUw1bp7ZLgEqMtwsvxIXNMHQbHgsP6TpmpVrMbjJ2I,14349 +google/api_core/gapic_v1/__init__.py,sha256=r6kCwKznSXPTYRdz4C384fscefaw_rXP2bzJdnzEVnw,988 +google/api_core/gapic_v1/__pycache__/__init__.cpython-312.pyc,, +google/api_core/gapic_v1/__pycache__/client_info.cpython-312.pyc,, +google/api_core/gapic_v1/__pycache__/config.cpython-312.pyc,, +google/api_core/gapic_v1/__pycache__/config_async.cpython-312.pyc,, +google/api_core/gapic_v1/__pycache__/method.cpython-312.pyc,, +google/api_core/gapic_v1/__pycache__/method_async.cpython-312.pyc,, +google/api_core/gapic_v1/__pycache__/routing_header.cpython-312.pyc,, +google/api_core/gapic_v1/client_info.py,sha256=FhmeHuSgFIxCCXaFPb4QdpoBzR4FVTy2997fkXorXbM,2421 +google/api_core/gapic_v1/config.py,sha256=5isOOYPSZCXpDcJDJiwmTxGTUo0RjxJJvW2yjqBR4BI,6300 +google/api_core/gapic_v1/config_async.py,sha256=_jrB5Yv6rxxSU6KwzOxWQ-G_x5mXilpSFAgnQ_6ktrU,1728 +google/api_core/gapic_v1/method.py,sha256=SnMqRoKKCRph9xpnQvQ29SGjCd9WVpHEPK60X-uPyWM,9494 +google/api_core/gapic_v1/method_async.py,sha256=L8BHV3SkvKTDqVSonDuUY1OIRMPEqfsOsTitYRQ_UwQ,2090 +google/api_core/gapic_v1/routing_header.py,sha256=kJKOYpNS2mgSZa4Qt8Ib2Q5ONfNwpJwbNloVJ8e2wMs,3093 +google/api_core/general_helpers.py,sha256=ZrYwDg7VTgtaQlFk_fCeFTKYZD62JMQdZRhbQhbQL_c,681 +google/api_core/grpc_helpers.py,sha256=3TPU35tMy43rZ9pvo7OmwQkZFqVPRQ2ViqolzE6-W88,24787 +google/api_core/grpc_helpers_async.py,sha256=LZvldkW8d0Lz-N1xITFpsE8TO0ej0jilUu7R4U2cf3Q,12966 +google/api_core/iam.py,sha256=BGz63HtOP5_5oH9Zs93RP0Y6Qshty2eOhFEYj_CoE64,13213 +google/api_core/operation.py,sha256=mHWay2vrNbEliv5YWFzyXBywbQdy_VPW98BALh514PA,13198 +google/api_core/operation_async.py,sha256=XdunwVY6aKA-K0OK-5_dYbqjbvF1DLTYUUL4IOztld4,8046 +google/api_core/operations_v1/__init__.py,sha256=ncvxAGOrunbMNRoQ9n1Io1p1nRN_LV5DutV52UidV8k,1638 +google/api_core/operations_v1/__pycache__/__init__.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/abstract_operations_base_client.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/abstract_operations_client.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/operations_async_client.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/operations_client.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/operations_client_config.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/operations_rest_client_async.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/pagers.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/pagers_async.cpython-312.pyc,, +google/api_core/operations_v1/__pycache__/pagers_base.cpython-312.pyc,, +google/api_core/operations_v1/abstract_operations_base_client.py,sha256=JoAlWWxuj_TpbAv9GCBt6_BMhflvIoR-rg9TPSOJ3is,14861 +google/api_core/operations_v1/abstract_operations_client.py,sha256=j_ulCLJpyqGh1SY8z5kss9iYBfOwE_XXCTqwQAKpyeI,16073 +google/api_core/operations_v1/operations_async_client.py,sha256=1BENex2y2ovlCHlXR4v5Cfiqk2o36DBWEzPyCCCudbU,14794 +google/api_core/operations_v1/operations_client.py,sha256=-fmbRv_2L_5cJv70WfybRw9EUyLlHB-wTbC-n0Iq4Fg,15274 +google/api_core/operations_v1/operations_client_config.py,sha256=v7B0FiVc5p9HhnpPY1_3FIomFdA-J-4lilomeoC9SkQ,2285 +google/api_core/operations_v1/operations_rest_client_async.py,sha256=qMYVo08Y0jfSU53dmHSDvO7_UL3x8DzJgpvnwAaTyyE,14616 +google/api_core/operations_v1/pagers.py,sha256=WYXqIGNIMbQX-2OUbiqz3ZXScvI_iOxKjxkN6bTP1YQ,2463 +google/api_core/operations_v1/pagers_async.py,sha256=SdFB-eXtOjZCHWICgViao6txHJqgs7vhsso6HT_npOo,2624 +google/api_core/operations_v1/pagers_base.py,sha256=qlizIpOdU-JVeQIMaPRIBmkcsghDX2FQYz5VH3-l9s0,2652 +google/api_core/operations_v1/transports/__init__.py,sha256=Ng5VDMks97QNfbkhFSRKmvNwUv3_IQmLUszCGTeJYvE,1457 +google/api_core/operations_v1/transports/__pycache__/__init__.cpython-312.pyc,, +google/api_core/operations_v1/transports/__pycache__/base.cpython-312.pyc,, +google/api_core/operations_v1/transports/__pycache__/rest.cpython-312.pyc,, +google/api_core/operations_v1/transports/__pycache__/rest_asyncio.cpython-312.pyc,, +google/api_core/operations_v1/transports/base.py,sha256=ygeocDSNgUA-DN-0Orx5ii4c6jUqmFZ17KmXlbsAFrM,11419 +google/api_core/operations_v1/transports/rest.py,sha256=qywh6vNSLPqP7Ieov5EJkN-THleZZt8qK0y5iCC91NQ,20599 +google/api_core/operations_v1/transports/rest_asyncio.py,sha256=t6ub6RgxKqPfRYO5ahy4l6vVqY2EvIKYuJSiT7TYPNw,24822 +google/api_core/page_iterator.py,sha256=FXMfqbhlVYAEVjpojytYAiUluVNYAVSC41MdfAhHAX4,20330 +google/api_core/page_iterator_async.py,sha256=TbuXorRhP1wcQTD3raBJhWgSJP1JwJO_nCKJphCbVdw,10294 +google/api_core/path_template.py,sha256=Lyqqw8OECuw5O7y9x1BJvfNbYEbmx4lnTGqc6opSyHk,11685 +google/api_core/protobuf_helpers.py,sha256=ct_P2z6iYNvum0FZ5Uj-96qf83Q_99TP1qcGwvlO_9c,12448 +google/api_core/py.typed,sha256=q8dgH9l1moUXiufHBVjqI0MuJy4Be9a3rNH8Zl_sICA,78 +google/api_core/rest_helpers.py,sha256=2DsInZiHv0sLd9dfLIbEL2vDJQIybWgxlkxnNFahPnI,3529 +google/api_core/rest_streaming.py,sha256=AwduJ7tYa0_iBhFEqCY696NVmNGWWCm6g4wnTqoVjS4,2209 +google/api_core/rest_streaming_async.py,sha256=5GuzrfYFHfR22d9guOtXvZ1E-VHCCusJyWKVRxOcFuE,3340 +google/api_core/retry/__init__.py,sha256=WhgtLBQO2oK-AehH_AHbGbfWo1IdG5ahUGrs3aFGw0o,2088 +google/api_core/retry/__pycache__/__init__.cpython-312.pyc,, +google/api_core/retry/__pycache__/retry_base.cpython-312.pyc,, +google/api_core/retry/__pycache__/retry_streaming.cpython-312.pyc,, +google/api_core/retry/__pycache__/retry_streaming_async.cpython-312.pyc,, +google/api_core/retry/__pycache__/retry_unary.cpython-312.pyc,, +google/api_core/retry/__pycache__/retry_unary_async.cpython-312.pyc,, +google/api_core/retry/retry_base.py,sha256=e1Asrsjp8Joj__GS9n0tiMeseYN5HWocHK2cbThyPHU,12890 +google/api_core/retry/retry_streaming.py,sha256=sw6Bx7w9G1lK8KCAYn2pw0hZ12sPQAD9h4otC2BXIuQ,11032 +google/api_core/retry/retry_streaming_async.py,sha256=gYs5KWzQ9RHb05ciPuoptOm5VWCOS7fliNG006Ndveg,14517 +google/api_core/retry/retry_unary.py,sha256=X8wIBzhKMpf3PlOmMgotIgg21Hvv16hUb3f8d20hnDc,13517 +google/api_core/retry/retry_unary_async.py,sha256=7PANk3jx6dBKKUZKd3yb2TFPBYO9l7uXg4QmBxmwhQQ,9594 +google/api_core/retry_async.py,sha256=_r0ROYeQqdATtRMx-q_6o4bPmqFzPyjr_oV3lfloDSM,1514 +google/api_core/timeout.py,sha256=heil0E6scuyFkMvymbR2bA33ZmJSavH_SmRNK9kpqcM,10279 +google/api_core/universe.py,sha256=k_K5J0I3kKQiM2yEHvxeqAWxXEQZKJ2SfDlMAH-rQ08,2952 +google/api_core/version.py,sha256=zk-6uopTPf5QfJCWtvMpBtM20LATfAG9g3zNecJwnew,598 +google/api_core/version_header.py,sha256=uEFXosCp8UH7XhznG5GQseTYtWNoJHXRPA557DWsUxA,1046 +google_api_core-2.25.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_api_core-2.25.1.dist-info/METADATA,sha256=WMMMUaM35tO_wBQMWaXs4L9ztzoXlF9avR39jYYtNOQ,3009 +google_api_core-2.25.1.dist-info/RECORD,, +google_api_core-2.25.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +google_api_core-2.25.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_api_core-2.25.1.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/top_level.txt b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_core-2.25.1.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/METADATA b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4ec0fdf8f8735419a75f68e273ac6dcb0df6d421 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/METADATA @@ -0,0 +1,163 @@ +Metadata-Version: 2.4 +Name: google-api-python-client +Version: 2.174.0 +Summary: Google API Client Library for Python +Home-page: https://github.com/googleapis/google-api-python-client/ +Author: Google LLC +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google api client +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: httplib2<1.0.0,>=0.19.0 +Requires-Dist: google-auth!=2.24.0,!=2.25.0,<3.0.0,>=1.32.0 +Requires-Dist: google-auth-httplib2<1.0.0,>=0.2.0 +Requires-Dist: google-api-core!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0,<3.0.0,>=1.31.5 +Requires-Dist: uritemplate<5,>=3.0.1 +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# Google API Client + +[![PyPI version](https://badge.fury.io/py/google-api-python-client.svg)](https://badge.fury.io/py/google-api-python-client) + +This is the [Google API Python client library](https://cloud.google.com/apis/docs/client-libraries-explained#google_api_client_libraries) +for Google's discovery based APIs. To get started, please see the +[docs folder](https://github.com/googleapis/google-api-python-client/blob/main/docs/README.md). + +This library is considered complete and is in maintenance mode. This means +that we will address critical bugs and security issues but will not add any +new features. + +This library is officially supported by Google. However, the maintainers of +this repository recommend using [Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python), +where possible, for new code development. For more information, please visit +[Client Libraries Explained](https://cloud.google.com/apis/docs/client-libraries-explained). + +## Version 2.0 Release +The 2.0 release of `google-api-python-client` includes a substantial reliability +improvement, compared with 1.x, as discovery documents are now cached in the library +rather than fetched dynamically. It is highly recommended to upgrade from v1.x to v2.x. + +Only python 3.7 and newer is supported. If you are not able to upgrade python, then +please continue to use version 1.x as we will continue supporting python 2.7+ in +[v1](https://github.com/googleapis/google-api-python-client/tree/v1). + +Discovery documents will no longer be retrieved dynamically when +you call `discovery.build()`. The discovery documents will instead be retrieved +from the client library directly. New versions of this library are released weekly. +As a result of caching the discovery documents, the size of this package is at least +50 MB larger compared to the previous version. + +Please see the [Migration Guide](https://github.com/googleapis/google-api-python-client/blob/main/UPGRADING.md) +for more information. + +## Documentation + +See the [docs folder](https://github.com/googleapis/google-api-python-client/blob/main/docs/README.md) for more detailed instructions and additional documentation. + +## Other Google API libraries + +The maintainers of this repository recommend using +[Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python), +where possible, for new code development due to the following reasons: + +With [Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python): +- There is a separate client library for each API, so you can choose +which client libraries to download. Whereas, `google-api-python-client` is a +single client library for all APIs. As a result, the total package size for +`google-api-python-client` exceeds 50MB. +- There are stricter controls for breaking changes to the underlying APIs +as each client library is focused on a specific API. +- There are more features in these Cloud Client Libraries as each library is +focused on a specific API, and in some cases, the libraries are owned by team +who specialized in that API. +- Developers will benefit from intellisense. + +For more information, please visit +[Client Libraries Explained](https://cloud.google.com/apis/docs/client-libraries-explained). + +Although there are many benefits to moving to +[Cloud Client Libraries for Python](https://github.com/googleapis/google-cloud-python), +the maintainers want to emphasize that `google-api-python-client` will continue +to be supported. + +For Google Ads API, we recommend using [Google Ads API Client Library for Python](https://github.com/googleads/google-ads-python/). + +For Google Firebase Admin API, we recommend using [Firebase Admin Python SDK](https://github.com/firebase/firebase-admin-python). + +## Installation + +Install this library in a [virtualenv](https://virtualenv.pypa.io/en/latest/) using pip. virtualenv is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With virtualenv, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +### Mac/Linux + +```bash +pip3 install virtualenv +virtualenv +source /bin/activate +/bin/pip install google-api-python-client +``` + +### Windows + +```batch +pip install virtualenv +virtualenv +\Scripts\activate +\Scripts\pip.exe install google-api-python-client +``` + +## Supported Python Versions + +Python 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and 3.13 are fully supported and tested. This library may work on later versions of 3, but we do not currently run tests against those versions. + +## Unsupported Python Versions + +Python < 3.7 + +## Third Party Libraries and Dependencies + +The following libraries will be installed when you install the client library: +* [httplib2](https://github.com/httplib2/httplib2) +* [uritemplate](https://github.com/sigmavirus24/uritemplate) + +For development you will also need the following libraries: +* [WebTest](https://pypi.org/project/WebTest/) +* [pyopenssl](https://pypi.python.org/pypi/pyOpenSSL) + +## Contributing + +Please see our [Contribution Guide](https://github.com/googleapis/google-api-python-client/blob/main/CONTRIBUTING.rst). +In particular, we love pull requests - but please make sure to sign +the contributor license agreement. diff --git a/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/RECORD b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c795044ddfd8cb29bc37073916c6a8a08602d9ce --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/RECORD @@ -0,0 +1,586 @@ +apiclient/__init__.py,sha256=U1SOZ1GeeF3uCr0fzO5Od-rpe17R12-Ppyq25NTSbow,746 +apiclient/__pycache__/__init__.cpython-312.pyc,, +google_api_python_client-2.174.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_api_python_client-2.174.0.dist-info/METADATA,sha256=T-TXCaTVvM84TrDffeRc9eanoGE-NPaxQRbCVOCHSlc,6952 +google_api_python_client-2.174.0.dist-info/RECORD,, +google_api_python_client-2.174.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +google_api_python_client-2.174.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +google_api_python_client-2.174.0.dist-info/top_level.txt,sha256=lbWgdDwQ3oww0ub0pmZ3fmIYAOTHf18Two4U9CxRlnw,58 +googleapiclient/__init__.py,sha256=kFWxKShJalbnrCuV0klL7mjZaiXfPpjlqmyKyI8yfTU,904 +googleapiclient/__pycache__/__init__.cpython-312.pyc,, +googleapiclient/__pycache__/_auth.cpython-312.pyc,, +googleapiclient/__pycache__/_helpers.cpython-312.pyc,, +googleapiclient/__pycache__/channel.cpython-312.pyc,, +googleapiclient/__pycache__/discovery.cpython-312.pyc,, +googleapiclient/__pycache__/errors.cpython-312.pyc,, +googleapiclient/__pycache__/http.cpython-312.pyc,, +googleapiclient/__pycache__/mimeparse.cpython-312.pyc,, +googleapiclient/__pycache__/model.cpython-312.pyc,, +googleapiclient/__pycache__/sample_tools.cpython-312.pyc,, +googleapiclient/__pycache__/schema.cpython-312.pyc,, +googleapiclient/__pycache__/version.cpython-312.pyc,, +googleapiclient/_auth.py,sha256=QttUwhmp7BmhW5CReaAOVGH6kEtITYmEHhVCVmsnDPs,5736 +googleapiclient/_helpers.py,sha256=iNxILG6iNNFukr7lhaYfVqX4oFM5SERvcsU3JxeOo6I,6723 +googleapiclient/channel.py,sha256=Fc4nxu-RxGkjY_STp9bwJfZaLan6VdX-DNniH-ANSuE,11054 +googleapiclient/discovery.py,sha256=9TKz9stsr8Q9TPTjKG1I6yHoPH1ISRvh58q_NoX3mOM,66341 +googleapiclient/discovery_cache/__init__.py,sha256=ww_vl0vhVLuHSEdRTv3-gq6EDG--Ff7rILYHHFifnzc,2315 +googleapiclient/discovery_cache/__pycache__/__init__.cpython-312.pyc,, +googleapiclient/discovery_cache/__pycache__/appengine_memcache.cpython-312.pyc,, +googleapiclient/discovery_cache/__pycache__/base.cpython-312.pyc,, +googleapiclient/discovery_cache/__pycache__/file_cache.cpython-312.pyc,, +googleapiclient/discovery_cache/appengine_memcache.py,sha256=6T1pQj-toAhDwfgLuiggFGhxKNGw5y-NnLUzLIF_M4s,1657 +googleapiclient/discovery_cache/base.py,sha256=yCDPtxnbNN-p5_9fzBacC6P3wcUPlaCQIy5v_dXTons,1389 +googleapiclient/discovery_cache/documents/abusiveexperiencereport.v1.json,sha256=S71sOgX6Jaa_CVbAYzdQANp6oxb8poocJieP6Q0KW0E,5671 +googleapiclient/discovery_cache/documents/acceleratedmobilepageurl.v1.json,sha256=pyMbFLPRkHJ-j_vpoXoTgLeJmB_Ff8aGoY94qtSIjC4,6729 +googleapiclient/discovery_cache/documents/accessapproval.v1.json,sha256=6iGAnShDZTJu-sDFOBqjRRTAhJFXPQXgYjxZO-Nxxjo,51837 +googleapiclient/discovery_cache/documents/accesscontextmanager.v1.json,sha256=0iOVchqifv1pr44NkJlazD4UVPXs2lcylXrfAPsYZ_8,117746 +googleapiclient/discovery_cache/documents/accesscontextmanager.v1beta.json,sha256=Vsv_nz7ubkkbGwNgxirN2AWgUuYH0mADUx9LFaqKu_c,51062 +googleapiclient/discovery_cache/documents/acmedns.v1.json,sha256=l4yO_s08Dowy9AdSBd857ZVqw6Ea4PWt1KE1OqOb9mE,6858 +googleapiclient/discovery_cache/documents/addressvalidation.v1.json,sha256=JQV7-cW61aZFFdW9MFu86CVTCg6XiBvSa8EGIt7Vks4,50336 +googleapiclient/discovery_cache/documents/adexchangebuyer.v1.2.json,sha256=0-XVzUa3kcqFiCZYk_W0au5mIV5-w3AgBtQJsSnWL9w,20475 +googleapiclient/discovery_cache/documents/adexchangebuyer.v1.3.json,sha256=6lFs8ULCDsQuo8s48oBpFdDCVbwICk6MNaCvDVrhP9Q,59967 +googleapiclient/discovery_cache/documents/adexchangebuyer.v1.4.json,sha256=pgYvRj3gK2vBxH7Dh4YoCqd7TXTzTDPQqVqOlVRxITk,136987 +googleapiclient/discovery_cache/documents/adexchangebuyer2.v2beta1.json,sha256=DsPe2AUTiMhcL_RQl_DIP6jVj_C_6BwM9knbgdt6auY,231740 +googleapiclient/discovery_cache/documents/adexperiencereport.v1.json,sha256=ZcB2Sna6t35lyCS6gJZ-FBePqKfGK9y1m2K8zVNDkN0,6644 +googleapiclient/discovery_cache/documents/admin.datatransfer_v1.json,sha256=hlCQx7RWQvTPF2JqI_Q19y4J7P8FgrHDR31YEIQseq4,12027 +googleapiclient/discovery_cache/documents/admin.datatransferv1.json,sha256=hlCQx7RWQvTPF2JqI_Q19y4J7P8FgrHDR31YEIQseq4,12027 +googleapiclient/discovery_cache/documents/admin.directory_v1.json,sha256=Qe6xHlfXdMHAvI5JUQABqnf4yNPXuCDMwj3M8zhofD0,276380 +googleapiclient/discovery_cache/documents/admin.directoryv1.json,sha256=Qe6xHlfXdMHAvI5JUQABqnf4yNPXuCDMwj3M8zhofD0,276380 +googleapiclient/discovery_cache/documents/admin.reports_v1.json,sha256=nrzgns5Jb5BmIHPnAFe4E6ygxE5NeCrlmJAuOf6ppEg,59897 +googleapiclient/discovery_cache/documents/admin.reportsv1.json,sha256=nrzgns5Jb5BmIHPnAFe4E6ygxE5NeCrlmJAuOf6ppEg,59897 +googleapiclient/discovery_cache/documents/admob.v1.json,sha256=KqHlEbdrL6m9INFAwhX9wFuqvR5Kjk_rdfu6mtc4XY4,52164 +googleapiclient/discovery_cache/documents/admob.v1beta.json,sha256=gcGNiedgQiUsitwzTPPv-yTsWzcR7iCV3_A9VO5G2f8,91957 +googleapiclient/discovery_cache/documents/adsense.v2.json,sha256=QAlUmTcLbXdnOr30Wtns5mFN6UwlNNVDi2fJsUzraS8,105238 +googleapiclient/discovery_cache/documents/adsensehost.v4.1.json,sha256=kKGnNG3aFbYwLFOLJkIGph3m7vC2heaob68rlmV4J28,37965 +googleapiclient/discovery_cache/documents/adsenseplatform.v1.json,sha256=sxqJvzMQS0OW7i_spxKrvmpI2BTZ-fPguABRUzEeKWs,20170 +googleapiclient/discovery_cache/documents/adsenseplatform.v1alpha.json,sha256=vIkJNUvHBAdnlTrSECYVMjqwc1bl3zwdm18p1UZDULo,33973 +googleapiclient/discovery_cache/documents/advisorynotifications.v1.json,sha256=LjKYP_4Fy_is5k-nccRqXa9usXF5_rBxhE_qdN9FkqE,20673 +googleapiclient/discovery_cache/documents/aiplatform.v1.json,sha256=XCevxby57NEczvwoXKTBh3z9Br6zsR4jQpwTqYG5ljI,1850845 +googleapiclient/discovery_cache/documents/aiplatform.v1beta1.json,sha256=sCiMrQOcbb1Zxcoh3F13CHk-7sqnLdsLVMN9auPkGgA,2221038 +googleapiclient/discovery_cache/documents/airquality.v1.json,sha256=Jid1ijxffWKiYwOdpwu_toVra3fOeowW8QuMkz2wpao,40963 +googleapiclient/discovery_cache/documents/alertcenter.v1beta1.json,sha256=mGQhl9nyAkBKYbJvHtem2LVzKnzHi2wkkSAIlim07lk,69312 +googleapiclient/discovery_cache/documents/alloydb.v1.json,sha256=EvK6E3Bf6PS7KnyWxB-Kt0rnSReKFGWrMILOe_eVteI,217330 +googleapiclient/discovery_cache/documents/alloydb.v1alpha.json,sha256=IU6c0dCCoSnhwwC3JtLVA6-6eraHlivgRf7FJGb5QKM,225236 +googleapiclient/discovery_cache/documents/alloydb.v1beta.json,sha256=cH5vQs3mr_KAMLDogIA1rVaqjeT8WBkPr_dweZZomhc,224598 +googleapiclient/discovery_cache/documents/analytics.v3.json,sha256=pq5nLmdNvFR-k8Sre800U3mI2tU6hVZGdQCNX_VJNiE,195428 +googleapiclient/discovery_cache/documents/analyticsadmin.v1alpha.json,sha256=EWoTo02ihWGs36oVfn_lknvTBsMZNgoK-FcaCLWuTc8,341243 +googleapiclient/discovery_cache/documents/analyticsadmin.v1beta.json,sha256=cPjvjzFbBQkY6C3g5ITM3E9NTNgCwui7XALSx_Rh-Ek,124871 +googleapiclient/discovery_cache/documents/analyticsdata.v1alpha.json,sha256=3rdVFqqDjQQ7-0qi_UkAYpRthvRKjoXJ8SJzulNHBn0,80445 +googleapiclient/discovery_cache/documents/analyticsdata.v1beta.json,sha256=-ptvrqUp-0rNGlell3IyH12yzL7LQbz9nBKOukMThkE,97076 +googleapiclient/discovery_cache/documents/analyticshub.v1.json,sha256=SbAl65dpRFXM_23OgWaUDzEUoxzam3FWFjWKEhx47QM,101922 +googleapiclient/discovery_cache/documents/analyticshub.v1beta1.json,sha256=fEXIoeH9DyR-OYgO2xMVQ9qOcFHjZl3LoWhbB14lAlg,58305 +googleapiclient/discovery_cache/documents/analyticsreporting.v4.json,sha256=8S4FyrAstnlesJ3ss4fYM7V18YvJgMh9S9jIo-vAOY8,61333 +googleapiclient/discovery_cache/documents/androiddeviceprovisioning.v1.json,sha256=VMdXCj6OCgTEktYH3Q_o4SHxg8niniZP9CHbJzVEb2o,61064 +googleapiclient/discovery_cache/documents/androidenterprise.v1.json,sha256=uyJbiGM2aLZ2La2NjJki0RYDH9Sq45nVQ9dMzi3WoCs,159424 +googleapiclient/discovery_cache/documents/androidmanagement.v1.json,sha256=7va4TnwXs5nR0oFnPnc6UiaUbEKIK3VLQpUbrBQJTKE,321649 +googleapiclient/discovery_cache/documents/androidpublisher.v3.json,sha256=iLfmeiopJQfwxeDea_k8Qw27typXGN2PuQx5mDaWSeI,329486 +googleapiclient/discovery_cache/documents/apigateway.v1.json,sha256=iT3Nbapbon_vlL96E0zn5QB0x62Le0nby17mm9euAl8,67624 +googleapiclient/discovery_cache/documents/apigateway.v1beta.json,sha256=AlaLyzdwk_VDpObVjgEseM6do0Uv17o7OR68K5dVu3A,69337 +googleapiclient/discovery_cache/documents/apigee.v1.json,sha256=Rq-7ZzHVNNKTJYumY2CpIjv_8qfovkSr1_g4bpd-SLI,715071 +googleapiclient/discovery_cache/documents/apigeeregistry.v1.json,sha256=hCu1irwJNFHGEQgiTM5HJtqvF1JUeqpBVA8SGUn9syQ,156027 +googleapiclient/discovery_cache/documents/apihub.v1.json,sha256=Rf9jSLiyChzWOLNhSJ7s-IVz2910Kvn1Nuw1ab6RGj8,238617 +googleapiclient/discovery_cache/documents/apikeys.v2.json,sha256=FZBL7LZgNkiOp8cChbkg38Xd0oRqDyn9MQRFouSiqRg,22352 +googleapiclient/discovery_cache/documents/apim.v1alpha.json,sha256=vEIuLE-GKaFKbEsNNTZFsDXHe1o1_oytjiHXHPT3h_M,48406 +googleapiclient/discovery_cache/documents/appengine.v1.json,sha256=65gMax89RoLfrrhxg-qhq9DkN1U-llaMAemPNlfNm-I,173074 +googleapiclient/discovery_cache/documents/appengine.v1alpha.json,sha256=7uAqJvDKcKnXelZ9QwU1FTfuSHJlVucIw7bdSStl71g,73992 +googleapiclient/discovery_cache/documents/appengine.v1beta.json,sha256=s7grm0Xa3d6JZvdurHWDIOs4mFNoV2XYstzjS8LcUP4,180798 +googleapiclient/discovery_cache/documents/appengine.v1beta4.json,sha256=yELseCdExWSunuF7afIqEw_94UU7PvKCXDmWkyAbYWg,110912 +googleapiclient/discovery_cache/documents/appengine.v1beta5.json,sha256=OHCPs6izs9jPAEuG8s9dr76KCn3f5lKdfWE5NaQBhZo,110227 +googleapiclient/discovery_cache/documents/apphub.v1.json,sha256=z7tKJ70C9tJbDFcMHqjJAMKR0Q0GzRW4FuVOpKhZ38s,92728 +googleapiclient/discovery_cache/documents/apphub.v1alpha.json,sha256=RTPNMiT4UxeG5taVJAMQ1uM4Kc_b4u1TIBTDj3yJCeU,99005 +googleapiclient/discovery_cache/documents/area120tables.v1alpha1.json,sha256=W3nRxsh01aYTWrEV05o-14Ubu4UvIqDelbu01_s9Ve0,26671 +googleapiclient/discovery_cache/documents/areainsights.v1.json,sha256=XGuwadbyFl9e84T5-AsiOktVw80eZzY5YnZYVnBQdH8,13908 +googleapiclient/discovery_cache/documents/artifactregistry.v1.json,sha256=OfEV2ONLdkEMpCk3oyOqVtTSi65Gz9yQYVDc1-GY-ZY,156305 +googleapiclient/discovery_cache/documents/artifactregistry.v1beta1.json,sha256=HouVCHF0eAZGxpexfi22ppR1hnImL8uAvjaKfLHlt5k,63804 +googleapiclient/discovery_cache/documents/artifactregistry.v1beta2.json,sha256=lE5MexBXKkBBVEcFZokZsWFeJ7IhvYT3UaM5pJN71A8,82401 +googleapiclient/discovery_cache/documents/assuredworkloads.v1.json,sha256=4y_fU84lwAydy9kbOI8KioTPDsFvq1bkIQGa4UidJhw,73905 +googleapiclient/discovery_cache/documents/assuredworkloads.v1beta1.json,sha256=v25crZ8H4Dwkrb1UD1RonXrLY2uOgTYFosIN7aBD47I,76086 +googleapiclient/discovery_cache/documents/authorizedbuyersmarketplace.v1.json,sha256=ReuPo9gijkSYfjf2POLjKSLgZsR33LGYYhLWCM991lY,111045 +googleapiclient/discovery_cache/documents/authorizedbuyersmarketplace.v1alpha.json,sha256=0qa-LitkQzNWYpgvcRf4TcNofuW8mBqHILnljTvwBO4,119894 +googleapiclient/discovery_cache/documents/authorizedbuyersmarketplace.v1beta.json,sha256=dC_ReHXZVQWAPLwr08SjvbsdrDS1bBUzwvBTPJGcre0,12485 +googleapiclient/discovery_cache/documents/backupdr.v1.json,sha256=dWJ7455zub8yDiNyrQhL6o_ykVDYKdQFN0apTTeHiCc,205697 +googleapiclient/discovery_cache/documents/baremetalsolution.v1.json,sha256=DgpA2txkVyJ3FJmckMnRzB1LGtD8K6qo8F2eYT6Bi3c,13574 +googleapiclient/discovery_cache/documents/baremetalsolution.v1alpha1.json,sha256=LWBZqVLJQlt0qgc4yoRJWQfwH0oPL8aS4wHGF8LRfzk,19186 +googleapiclient/discovery_cache/documents/baremetalsolution.v2.json,sha256=WWaMmuGvau4vIHHkwYZTQmABw8ZVSsTK7v352CtG3q0,105820 +googleapiclient/discovery_cache/documents/batch.v1.json,sha256=8eu5buil88VCrdhateW_Pmvs6nBidDDlfpdPSwYvtmc,88997 +googleapiclient/discovery_cache/documents/beyondcorp.v1.json,sha256=RXYgEE-e4I6GcW95vRbJszj6tj6WNMwkZv6s3a_eb-I,148929 +googleapiclient/discovery_cache/documents/beyondcorp.v1alpha.json,sha256=MtmHOvNfzriwZnzz1YCcA4OAigAf7NbHgdD1Oo4Pd5c,246123 +googleapiclient/discovery_cache/documents/biglake.v1.json,sha256=JiAvdp7lTnDjHSpeG0RZ_mZFOtNCW5lXWrok81NGECs,26554 +googleapiclient/discovery_cache/documents/bigquery.v2.json,sha256=Q9O8_Vlf0uLPP9CNG79xS-9ldKOTbu5R72VvfzNO2MM,409876 +googleapiclient/discovery_cache/documents/bigqueryconnection.v1.json,sha256=uogtso7Bp7eexOLF2Syb3hapjEHyOU1Wx62pnBGwefI,43660 +googleapiclient/discovery_cache/documents/bigqueryconnection.v1beta1.json,sha256=d45MeNg37AdYm_s8hO7ZqLd8hDw3qbpif9ecV1OMYIA,32721 +googleapiclient/discovery_cache/documents/bigquerydatapolicy.v1.json,sha256=Nnzx-_JwLwMWOPvbonPg1bLR14ROCPuCiEQWGRjxK7U,35034 +googleapiclient/discovery_cache/documents/bigquerydatatransfer.v1.json,sha256=m6hUZ3p28aOzbpYgz-1Pukx-jLc3Zcj0e6QaRJv6y1U,91300 +googleapiclient/discovery_cache/documents/bigqueryreservation.v1.json,sha256=Ni6Kmj8Xi9pjGyTUWBSpOJxfF48Ser_zLTYdPtec35Y,90224 +googleapiclient/discovery_cache/documents/bigqueryreservation.v1alpha2.json,sha256=u1WvY6zx7CYg_q9OhtqB5I8Su4b1kEA7p3VwegecO8U,44509 +googleapiclient/discovery_cache/documents/bigqueryreservation.v1beta1.json,sha256=zVtHmOXJTgtYX3JK9YoFUW8uNNHwi-ZPHs4gQN-Y0cY,60957 +googleapiclient/discovery_cache/documents/bigtableadmin.v1.json,sha256=udwAbAWXjShMSJcvAaxRNI-V5QFFQdE6InVOhHT-y7Q,32684 +googleapiclient/discovery_cache/documents/bigtableadmin.v2.json,sha256=ygk-z_J5NX9o61YIcLy2VGw5Vq_0Y1Do47mfbtp6h9o,218082 +googleapiclient/discovery_cache/documents/billingbudgets.v1.json,sha256=v3YOJsAFLFb0dBL3DDh40t5RYi_K8YZUszEi-IY0XQM,27319 +googleapiclient/discovery_cache/documents/billingbudgets.v1beta1.json,sha256=W1XxaGkQBjVGfxUdSJFFi2WIfppU-rP-rkFpSuTKvqk,26850 +googleapiclient/discovery_cache/documents/binaryauthorization.v1.json,sha256=VbVagXrsIjQFnLWQNo7wffILvWF_rvPatEnLx1T_i70,85436 +googleapiclient/discovery_cache/documents/binaryauthorization.v1beta1.json,sha256=9zlVIEnahifUYLArioJ_ycDpVZpet2mkIrclt_WkKQ4,50127 +googleapiclient/discovery_cache/documents/blockchainnodeengine.v1.json,sha256=a1Ofj3cZkV0TgdbkUN88FKmGBeDYWg59orqr0eLjIDY,33214 +googleapiclient/discovery_cache/documents/blogger.v2.json,sha256=_Mn53e4gp6cs6YtNt7826ROf1ne6mpuRjKVWUCBa4D0,21624 +googleapiclient/discovery_cache/documents/blogger.v3.json,sha256=6fBSJsQdIaX4ijJr1hsje92WC8n0jVn0zseJkxnqqpE,44163 +googleapiclient/discovery_cache/documents/books.v1.json,sha256=dWEew3bc3mDWbAhR-f26d9JqXKqiPtpXQ7We2VBfQVs,110062 +googleapiclient/discovery_cache/documents/businessprofileperformance.v1.json,sha256=2FQwtRgx3ObOq_qdL-a_M9evFaluSAUCpPAXZ15JpmM,24459 +googleapiclient/discovery_cache/documents/calendar.v3.json,sha256=PnI_dBpYlyBLYPrRLNdcgUhNC2b-PxX4PY2JEd2jdOU,124158 +googleapiclient/discovery_cache/documents/certificatemanager.v1.json,sha256=YUfN_Zv8VCyn8tbnlJZNcueFEhK7k9VWV3uvmdq-bOQ,73726 +googleapiclient/discovery_cache/documents/chat.v1.json,sha256=KsYmzO7VNXdvdZ2td8ac9uREji2BFZiqR9nox2dm3Yg,292692 +googleapiclient/discovery_cache/documents/checks.v1alpha.json,sha256=_Ko7Qb9yYJxCarWZa3mlQg08Y5azaxIAj7smjiqmviA,91808 +googleapiclient/discovery_cache/documents/chromemanagement.v1.json,sha256=JG-Vikhr6-4ZwAH6zRtNnYgRvAqjp_xDmicoFJhr3yU,191503 +googleapiclient/discovery_cache/documents/chromepolicy.v1.json,sha256=F_laa2i3Vpu-MZs3oG2WYhfaCDCA6wnF-qGVURohieI,62781 +googleapiclient/discovery_cache/documents/chromeuxreport.v1.json,sha256=B_gPbscveC48075QTg7o8DVwhrw62NnpNdwJlg13Zgk,22609 +googleapiclient/discovery_cache/documents/civicinfo.v2.json,sha256=l_UnR9XfxV6SPGLLA53OZN_r0sffeUlIMoaNZaIKoUE,30776 +googleapiclient/discovery_cache/documents/classroom.v1.json,sha256=jVcsmge-7bqe9eW67nppAraD6dhIECFXV9GbxgQaIQg,245513 +googleapiclient/discovery_cache/documents/cloudasset.v1.json,sha256=C63xFBWTTfiJ_mv6KMomiO0MdtZF3wZDej3_-kmmQTo,259468 +googleapiclient/discovery_cache/documents/cloudasset.v1beta1.json,sha256=5_lUxBFrf6WekxeYqMLL5AXBJzk4f0lz3IE85aRjqkY,95594 +googleapiclient/discovery_cache/documents/cloudasset.v1p1beta1.json,sha256=r3Jdq7Re-xz6GOxJ0-Weo5O1wW8V0iadoUhGwtvsRV4,83762 +googleapiclient/discovery_cache/documents/cloudasset.v1p4beta1.json,sha256=RT5pGxMQhQ_T9JKt97G6G94znnnweuqgSwEnby7Vkck,110574 +googleapiclient/discovery_cache/documents/cloudasset.v1p5beta1.json,sha256=R0MmgDRSV1UbtpnsbTSG98ZLWrJoMLNZIfBnhcO40q4,82419 +googleapiclient/discovery_cache/documents/cloudasset.v1p7beta1.json,sha256=dxOwFjGlIt_yD-eYZF3l5S5bYV2_NVC6TJa4zYQ8MQ0,88076 +googleapiclient/discovery_cache/documents/cloudbilling.v1.json,sha256=jg1-B4LYm5Dp-V9jUomBsLVOd9H4uPlgCTjME9AHUrs,61261 +googleapiclient/discovery_cache/documents/cloudbilling.v1beta.json,sha256=SqLdm243EPaHYt08Zw_rblcz4XeXzo3jdFxO-A_ehno,98576 +googleapiclient/discovery_cache/documents/cloudbuild.v1.json,sha256=cPi6CyaV2nCxp44FFzhJZlwQD_QoJsXLcKJOJoWhAV8,197189 +googleapiclient/discovery_cache/documents/cloudbuild.v1alpha1.json,sha256=tN8lxatpJZdx4mhuKWjgzYeBfbN3ZFgZOhdDI8HdMTc,103536 +googleapiclient/discovery_cache/documents/cloudbuild.v1alpha2.json,sha256=FqGePJRUozQZ3MgYXXDeeBwhKb38oRdL3RDyfn5LKOA,102139 +googleapiclient/discovery_cache/documents/cloudbuild.v1beta1.json,sha256=Z9D0XmsAbFI1Ug2BBm8i4hocf4dzGW0MP_3rprbHH2I,105268 +googleapiclient/discovery_cache/documents/cloudbuild.v2.json,sha256=zBN4vl72VyumDaRF4pKIvLPAy7qhqSZ_sYQZa22qx_A,113912 +googleapiclient/discovery_cache/documents/cloudchannel.v1.json,sha256=8ftPzRu5DWWy7bCMQe_ks_2RVTcFS-ichTIGbIEKcHA,249757 +googleapiclient/discovery_cache/documents/cloudcommerceprocurement.v1.json,sha256=NtXgLDh60lxmnNf3YKeRYfUr2suT9B1KvXUyXvfeXuU,40056 +googleapiclient/discovery_cache/documents/cloudcontrolspartner.v1.json,sha256=rMIB1jLBv1Hx5BP1XHy1P6SjL5dzpxtgQ0C2JrWdkE8,39795 +googleapiclient/discovery_cache/documents/cloudcontrolspartner.v1beta.json,sha256=WMIVTmWBALeWRidAdfvDf5UMnsjHgJ0m8LZxez5XPQc,39907 +googleapiclient/discovery_cache/documents/clouddebugger.v2.json,sha256=2IO6Cc_uKUbDzdXhyc02Xr2Y7vd8TIRq_2iWDhwGYPE,53446 +googleapiclient/discovery_cache/documents/clouddeploy.v1.json,sha256=Oj50CXluTUqRV6ayyMekTi0vAbcRYnAzrAEpOhPb9kA,259765 +googleapiclient/discovery_cache/documents/clouderrorreporting.v1beta1.json,sha256=LT3OJ_dSdWCJnai8IcrGZ5Gxr4xti3uIknpzRPbNzN8,46460 +googleapiclient/discovery_cache/documents/cloudfunctions.v1.json,sha256=LyCgf0RL_0C2u84WMl91yE7Jgy27OBFxt4UKYw4mEtU,65107 +googleapiclient/discovery_cache/documents/cloudfunctions.v2.json,sha256=uxJghvcBGyUlh39gFzs6SD6RkJ7eEGtqUGhxw_0C9D8,86776 +googleapiclient/discovery_cache/documents/cloudfunctions.v2alpha.json,sha256=sSttj4gAWPpRPQOKHNDx51mefZJ1JIcOHQAepx4iqk0,87041 +googleapiclient/discovery_cache/documents/cloudfunctions.v2beta.json,sha256=9P6-d-vHPklQeJ6hZSvec5SnestkWKQ1PlnQAgj5IG4,86988 +googleapiclient/discovery_cache/documents/cloudidentity.v1.json,sha256=D_Z3Zq2fgCwiyn0Jv8M3pLEP0NzRd9NjR9DCBziftGA,165314 +googleapiclient/discovery_cache/documents/cloudidentity.v1beta1.json,sha256=EcwRYr2YaAEg7bDt9tXbpnzr69vyBeimkfhuN5LBRuM,194853 +googleapiclient/discovery_cache/documents/cloudiot.v1.json,sha256=BLM9X9po2P0rn8osda4MgRc990yAYWFVbRMnoCTjN6w,94703 +googleapiclient/discovery_cache/documents/cloudkms.v1.json,sha256=GE3SPnyU-em3AJdW4YbpZ2BagUGeaXDPNh_0B3KcFB0,211499 +googleapiclient/discovery_cache/documents/cloudprofiler.v2.json,sha256=DKiyeC2Z010ehm-WHvDJBGMnfVFow8daU56CAP1hlkE,14920 +googleapiclient/discovery_cache/documents/cloudresourcemanager.v1.json,sha256=Ze84AMCb0NrobGUsOppZf84ZMGkyVg3q2qCG76BWM3Y,101735 +googleapiclient/discovery_cache/documents/cloudresourcemanager.v1beta1.json,sha256=pDTAX1oOSWZiGw825NDYsl7cIYz__1ctAege_ysSdSU,58765 +googleapiclient/discovery_cache/documents/cloudresourcemanager.v2.json,sha256=FKliR52dUB8gdJTRYxiAxO5GE8fChL4bbhJj36_VE30,52486 +googleapiclient/discovery_cache/documents/cloudresourcemanager.v2beta1.json,sha256=HYYwrbxp5uvt1c_Oq3AWqfgDPLOjp_i0iJf44X1jA48,52496 +googleapiclient/discovery_cache/documents/cloudresourcemanager.v3.json,sha256=v5y53JMOXgtw6E8KHiqx_M-jf2PYz-89IeA9A1chT80,134613 +googleapiclient/discovery_cache/documents/cloudscheduler.v1.json,sha256=9_pki0w7ePlHy82k2z2CEfkAqNlnpB6bUy9Sfpr0zlo,47107 +googleapiclient/discovery_cache/documents/cloudscheduler.v1beta1.json,sha256=WuGy9dX2WqnKnqSFSVBDAIdvYg1Xmi-GJ2z_gCfJ7os,43317 +googleapiclient/discovery_cache/documents/cloudsearch.v1.json,sha256=zioYxBar0l7onDdnYAfGKjcguMEdRkybFuuQlawHHDE,247310 +googleapiclient/discovery_cache/documents/cloudshell.v1.json,sha256=pRDGK9lNQ9_ADOmlBcTUVzBX422WFWCijv2LK--rzUA,22895 +googleapiclient/discovery_cache/documents/cloudshell.v1alpha1.json,sha256=XoIskUrEjFBy7Saxe7cApOT6ShmcKZlwzRDAiIoxgSI,25615 +googleapiclient/discovery_cache/documents/cloudsupport.v2.json,sha256=bgzxdZLCW_ECHALWO18hIRvYsmo34G6gCD-lSpAn214,51905 +googleapiclient/discovery_cache/documents/cloudsupport.v2beta.json,sha256=rIT5tiNtlXf3I4SPsCWx9nv44Eg-s4VotYzG2qGQhNk,57895 +googleapiclient/discovery_cache/documents/cloudtasks.v2.json,sha256=0sGe-mnA2IeFAiHPThdaUrucNRy3gIENpwYDPB1Gp9s,96758 +googleapiclient/discovery_cache/documents/cloudtasks.v2beta2.json,sha256=3INmN9jyGLRTOU_qNQjeAagECPrA4hu7GLeBlBY3Ojw,113423 +googleapiclient/discovery_cache/documents/cloudtasks.v2beta3.json,sha256=K8KT6FH4hZfX-8cdkXioqZpdnM9F3qIOVi4s4WX-wpk,103749 +googleapiclient/discovery_cache/documents/cloudtrace.v1.json,sha256=Po2AzlboBENj1bTgIVRd7PP7ux9lZ3HrwO1glYEJlkg,12084 +googleapiclient/discovery_cache/documents/cloudtrace.v2.json,sha256=YqE6jcB7F-7Wc-xuHMgXcxO4rxS-QBbjuCDOWaonJ8E,21232 +googleapiclient/discovery_cache/documents/cloudtrace.v2beta1.json,sha256=C-rFqBUcGEdGeys6I18EtbUb-LV2oI5FL8D7EGbrLNk,11533 +googleapiclient/discovery_cache/documents/composer.v1.json,sha256=UQ99RsKx2-K5_MLhokpy6pA-IbAp7AHQgiaYPqAYyx0,105714 +googleapiclient/discovery_cache/documents/composer.v1beta1.json,sha256=_Y0HsjrPUcq_HhuFC-ZBaA3HN-BI3mIOiTeDewQnnK0,108640 +googleapiclient/discovery_cache/documents/compute.alpha.json,sha256=fQSPX2LuOWajuJBdeYz2v_-uSjsehL4ZT0pWZNuOJqA,5017762 +googleapiclient/discovery_cache/documents/compute.beta.json,sha256=IjVJ8IQ8A-TonXMKz0b1v3c4IGDFArQWLfoZM11abKQ,4473659 +googleapiclient/discovery_cache/documents/compute.v1.json,sha256=S2FAgOThWEIZbmGtXWV0zNkQFMCn7h_nmaAaMneO-Zc,4035453 +googleapiclient/discovery_cache/documents/config.v1.json,sha256=s0GWOZOlfF82W7ae_sQsM4E1UuMJshn5PFO8g11UTmw,113507 +googleapiclient/discovery_cache/documents/connectors.v1.json,sha256=ghd8W65HO9qLaCf0gjSBId4kp4EV5DXEDPwnmdsz67A,261367 +googleapiclient/discovery_cache/documents/connectors.v2.json,sha256=2bFLJEEKBxwIA1-1_SBlPln4lCwf56uBOPGvJsslnzI,71814 +googleapiclient/discovery_cache/documents/contactcenteraiplatform.v1alpha1.json,sha256=_ophg0tfM2c9itoT7Ph9xiTbEt2ZRJRshOrTH6rVKiw,44191 +googleapiclient/discovery_cache/documents/contactcenterinsights.v1.json,sha256=2xKD3Syb-pEhmDqTAme8L3gjPW44XXDZoHAgg8F82i8,446657 +googleapiclient/discovery_cache/documents/container.v1.json,sha256=O-pt6KoxPVZyD_2EJA2AB2UrmOs9ItikrDLF5Y21ZMw,341858 +googleapiclient/discovery_cache/documents/container.v1beta1.json,sha256=BPZnWgCwaQfSAV__r7wErvTZf5YuoBwpvoJrJ7cO74U,365916 +googleapiclient/discovery_cache/documents/containeranalysis.v1.json,sha256=jAUd2LR9ogQJhLMnvO-sgadDDPqnQOyqoS_WflaSsJw,236766 +googleapiclient/discovery_cache/documents/containeranalysis.v1alpha1.json,sha256=vkddmhEINvHnapLWeqEcdNRjS0a8XTmIy7RsmjDj-kU,258315 +googleapiclient/discovery_cache/documents/containeranalysis.v1beta1.json,sha256=68rT-0qkoPLFfY9tOL7nX8QL5pAcuzFVllccOBw77XE,248368 +googleapiclient/discovery_cache/documents/content.v2.1.json,sha256=DYP75OF3647H4Wsgnk63okcPh5wwYcKBBX11xa7O-Ak,467608 +googleapiclient/discovery_cache/documents/content.v2.json,sha256=PuV1X8AOtI9T1gaQphOf14GgA06gplme2e31cRNVSlU,389993 +googleapiclient/discovery_cache/documents/contentwarehouse.v1.json,sha256=mvMFtg4zcLO64JQheZ2qUKQCg3I69Wm9TE3TMKuVn6U,226184 +googleapiclient/discovery_cache/documents/css.v1.json,sha256=oDmW6d1Gpr1FORwtwlIscKiMovcuxFilKtBvAnj85Hs,44472 +googleapiclient/discovery_cache/documents/customsearch.v1.json,sha256=gkOUqUMB14JgNUySDvnSooKihyAmZWmbBYJ6Jpz0wHs,63076 +googleapiclient/discovery_cache/documents/datacatalog.v1.json,sha256=Pu3JjeFx6vj9KFT_Fpbdk3SStTI4bstMrE98pet0nZI,194068 +googleapiclient/discovery_cache/documents/datacatalog.v1beta1.json,sha256=56ECzij7A64lKIEzGFThCmPfjF_JOFo_PombFxA36mg,182855 +googleapiclient/discovery_cache/documents/dataflow.v1b3.json,sha256=DbaFbCAGY_Nprx7N8xa3IdiDDZZGzk8iflRbNcbB9qU,272960 +googleapiclient/discovery_cache/documents/dataform.v1beta1.json,sha256=nwIS_wa3q7wJOa72uki7BPG37ihrF-F49LQovoXZ-Dw,149400 +googleapiclient/discovery_cache/documents/datafusion.v1.json,sha256=sGSoT575n-amUztEjHEPtYFd8QoF6dSNTQZ_th79jUs,67691 +googleapiclient/discovery_cache/documents/datafusion.v1beta1.json,sha256=053Oj0b65FVbbP5xNo1lOTL-t1emNJTymEd1UognsWM,76628 +googleapiclient/discovery_cache/documents/datalabeling.v1beta1.json,sha256=5AdOFMYk2uvTezbB0CLjZkRnBRzrasRNJaEdZC4TCJc,202109 +googleapiclient/discovery_cache/documents/datalineage.v1.json,sha256=1kX0kj-dKAs_FL0iVWvCOsenD-1IYk5wkk25RhAnaJg,52426 +googleapiclient/discovery_cache/documents/datamigration.v1.json,sha256=bdUe65YAR9d-K_R4z6Q1VnIrop75QBPVracCaTsP1IM,240433 +googleapiclient/discovery_cache/documents/datamigration.v1beta1.json,sha256=DHWhpOaH5DusAJflQUl7hpeMi8tCrBQZ6gJFJ3aVYOw,84129 +googleapiclient/discovery_cache/documents/datapipelines.v1.json,sha256=vocmGOA8i7K12Yy3kAeZ1IsUfm3fza3QWFE6taPqP6Y,38301 +googleapiclient/discovery_cache/documents/dataplex.v1.json,sha256=kUD3jjGGgAeSM3LWbo8qQdQbLbdtbIZTwZoiWXdbaSY,505747 +googleapiclient/discovery_cache/documents/dataportability.v1.json,sha256=HpZkBUfyNaCvA6Y8fCHUC_bJHuO1htY3-KHv8u-fZOs,50978 +googleapiclient/discovery_cache/documents/dataportability.v1beta.json,sha256=rx-IxyKqDN7xqTx7tdjQzybZsujIPJjI5_kU2c7VeM4,51034 +googleapiclient/discovery_cache/documents/dataproc.v1.json,sha256=SXO_K4GiPgY5eA05DXr_oQtccYRtOp-MxdGlWjP0LW8,426722 +googleapiclient/discovery_cache/documents/dataproc.v1beta2.json,sha256=jfuxbI0IJ3EFmdqwKxUp_DvxU6gLnDToTAicOhZM0qo,256974 +googleapiclient/discovery_cache/documents/datastore.v1.json,sha256=rLgPJcB4W-7TvccUrWyZ7OOWcmQJtBa05kwNvr_k9eM,100229 +googleapiclient/discovery_cache/documents/datastore.v1beta1.json,sha256=Yid7Qf4pqbNmwl1tWayQ_cYyNn7liUImn1YS-bbeijo,28932 +googleapiclient/discovery_cache/documents/datastore.v1beta3.json,sha256=7PvsBf-qzpwJ4jndS7gh34AfWU6OLjnpSn0JzM-YTlI,77221 +googleapiclient/discovery_cache/documents/datastream.v1.json,sha256=FxJuesqCLk2Vh9UgXP-ssuNunieSegH5YF8xAzswQqM,119199 +googleapiclient/discovery_cache/documents/datastream.v1alpha1.json,sha256=Z39NqlEop9vBYHYwozndO42Dn7ITrQrf0sChxdaUTew,78971 +googleapiclient/discovery_cache/documents/deploymentmanager.alpha.json,sha256=41TotKSko5LlRXLiPWdj--WrDR5JQxtm9azbm5PFFEc,157016 +googleapiclient/discovery_cache/documents/deploymentmanager.v2.json,sha256=nNECN8yB7JQsazZOTeasWlBXmsSI5Uxgqtp-V1XsXrE,110758 +googleapiclient/discovery_cache/documents/deploymentmanager.v2beta.json,sha256=v8aSTs6IQFilQgKYWabMUR6_tS4pcwQNVo6XrCThW10,153106 +googleapiclient/discovery_cache/documents/developerconnect.v1.json,sha256=7IvV_TG8H-g3sBJHHd6UCw7NhMQXqrWe1BDp4_m2uNo,100878 +googleapiclient/discovery_cache/documents/dfareporting.v3.3.json,sha256=AaucsfQ-9Hx6evOCWHX3E6n6llRjAlvVFEqLD2bpYXE,721039 +googleapiclient/discovery_cache/documents/dfareporting.v3.4.json,sha256=0KvRG3-gvfK5CunHotnX5uTGYwl8W_af_vg0LX0q_NU,748283 +googleapiclient/discovery_cache/documents/dfareporting.v3.5.json,sha256=E0e7bs-i0WQg8X-rLjIOn5DpeCDtiE9yDB_-J4VuCAw,17300 +googleapiclient/discovery_cache/documents/dfareporting.v4.json,sha256=O4KKtW0HfsDPEHYskqU3ossXiVasE5_-bJV06AT3PUY,562732 +googleapiclient/discovery_cache/documents/dialogflow.v2.json,sha256=pGW3Ug1LsnsuOclKz4aBYYyMZa6VopQpCh5ESoGMjT0,939044 +googleapiclient/discovery_cache/documents/dialogflow.v2beta1.json,sha256=psIlM_HevNCU4Ox0_7a6PlPY6F_rBszzLGKL4USXJDY,962161 +googleapiclient/discovery_cache/documents/dialogflow.v3.json,sha256=MJIYuVShZ6A_tIB1SY89SYHlenexerGDtbw1-YJlrl4,808069 +googleapiclient/discovery_cache/documents/dialogflow.v3beta1.json,sha256=sBQvUQa93SGk0mC1l0U1pLd2_GaepKyCHUqqozo-guM,857192 +googleapiclient/discovery_cache/documents/digitalassetlinks.v1.json,sha256=3CICeK-vxTL7U-PF6KQfUjQxPO39tHKmLa32-6kwqsw,29872 +googleapiclient/discovery_cache/documents/discovery.v1.json,sha256=OQvmfp6aUxzASZk9m__FvI0wuRXNWI_41RykyxtDkzU,18215 +googleapiclient/discovery_cache/documents/discoveryengine.v1.json,sha256=I5avqf79iU0wHg-pdftFug_L2PyauyWysfoh8NmoVx8,1007174 +googleapiclient/discovery_cache/documents/discoveryengine.v1alpha.json,sha256=Z2Vl9KNtQOXSj4FCkQKihh6fRxdVZ_RNQw8qNmlIGig,1167830 +googleapiclient/discovery_cache/documents/discoveryengine.v1beta.json,sha256=nTbeFiJlTGJYAknNnclqosrclLYzPpRLeftLPBPS2fs,1071834 +googleapiclient/discovery_cache/documents/displayvideo.v1.json,sha256=RRZQfVKtGzhfs9Kx6Rp2mrBcfaRJ9p5B9I76uIcVf4c,737810 +googleapiclient/discovery_cache/documents/displayvideo.v2.json,sha256=4RdH-bBQ4LdeUODe1QEp5ocoGNq04CxanNG4ut2SBKk,785231 +googleapiclient/discovery_cache/documents/displayvideo.v3.json,sha256=Nba6Qrz7dCrFKa2Bi36AHcVc702Ga3p2W0uH5F9RL48,913147 +googleapiclient/discovery_cache/documents/displayvideo.v4.json,sha256=iZ0bUMhB8kQrk79LhnplWOsYSrzVzS-b0inwHvcBU7k,848278 +googleapiclient/discovery_cache/documents/dlp.v2.json,sha256=RxJECVQKiVk3pgsL2VnNe5KqLBtMsZisplaB82RJGM8,524784 +googleapiclient/discovery_cache/documents/dns.v1.json,sha256=yLqVURduJwi3t7Jg_43UBOTPnG74K4kkrT53XpGHEro,121299 +googleapiclient/discovery_cache/documents/dns.v1beta2.json,sha256=p5ymbYYTMHIZyjOm5TxHg0t4Wolzko5gaFjwHi16tm4,121683 +googleapiclient/discovery_cache/documents/dns.v2.json,sha256=uMSPBTHSlq6gMc-OC9ap_C9WuE34lwbub8U8wOlwoTY,136579 +googleapiclient/discovery_cache/documents/docs.v1.json,sha256=TygbvHb6iYjxvWRXXgWYnCvbPNtkAdXipHTI4QH6aro,179902 +googleapiclient/discovery_cache/documents/documentai.v1.json,sha256=uMCpwy1qxc3KC57j0fuVwkFZ2X3aDvbx_je1Ulydox4,217751 +googleapiclient/discovery_cache/documents/documentai.v1beta2.json,sha256=gOemdhcv2MjxnsArox4YiE7zXia3wVKtMsD6eqBauYw,213046 +googleapiclient/discovery_cache/documents/documentai.v1beta3.json,sha256=_Is3pf1orovUfM9W0gXdiFS0kTDvIhUygNb-cUAJCu4,248860 +googleapiclient/discovery_cache/documents/domains.v1.json,sha256=3Eui21VVZWEtdjp_EEQV6R_VBTpi0BZaHKrezY29q-8,121515 +googleapiclient/discovery_cache/documents/domains.v1alpha2.json,sha256=72bRYKwL6d7FELZsbiHgqM_HbEiuviL9ATseeZXiRio,122168 +googleapiclient/discovery_cache/documents/domains.v1beta1.json,sha256=KHOaPQoDkM0KpOYPet7whUbpdBp5jMc9yIxGb-OyAJU,121805 +googleapiclient/discovery_cache/documents/domainsrdap.v1.json,sha256=0kMvTxrY_-Slq8YjmDxT3Q1LZsiE4EkltzeZvzj7R3s,11381 +googleapiclient/discovery_cache/documents/doubleclickbidmanager.v1.1.json,sha256=jHYIGcAx7c3WN_5Mvr6LpEFpkB-VYgyz-rpoi41Fl-8,117347 +googleapiclient/discovery_cache/documents/doubleclickbidmanager.v1.json,sha256=c-oeCNUdKAdNJa3Bm3sqAgb6LpgiCn-s6NUUp4rsUt8,3347 +googleapiclient/discovery_cache/documents/doubleclickbidmanager.v2.json,sha256=y_jmaALx58H7CcutbeZdjITVzjYpeA-Y6aUFAmnvP_E,21518 +googleapiclient/discovery_cache/documents/doubleclicksearch.v2.json,sha256=hKxva7ErQGWge70V83F4EHAk9YSSGEmBjlt-CG1Gbeg,34911 +googleapiclient/discovery_cache/documents/drive.v2.json,sha256=i1UdnwC7H098dPUZ7HW6OdlYhMEQ5uqBj0uPA1KjXPA,204601 +googleapiclient/discovery_cache/documents/drive.v3.json,sha256=PsJ2mGX_cjIl-jCjDoPCu7swbsmL3-zJTG7tv5nC5O0,175590 +googleapiclient/discovery_cache/documents/driveactivity.v2.json,sha256=SexajzanodYVuVUGQG6TXbAZo9tQXZwnaiqiTRFbUIk,37015 +googleapiclient/discovery_cache/documents/drivelabels.v2.json,sha256=XEniMP6MnFB_cAlTfWQKVZj-hOUy6-ML3KCaq3mMMSo,108498 +googleapiclient/discovery_cache/documents/drivelabels.v2beta.json,sha256=P3QqTd8FIfrED20ud5cHs6lue-40sBZ6tz37PNzwTq4,109974 +googleapiclient/discovery_cache/documents/essentialcontacts.v1.json,sha256=HL3qRBgEecmFCMjYEZJwnoykj5EQ5szQQwXDHLd1Nek,34502 +googleapiclient/discovery_cache/documents/eventarc.v1.json,sha256=NPHXFVIpjRI5DRJh5YG5gDoF6wXMa9lYPSh2sZq6NU4,167448 +googleapiclient/discovery_cache/documents/eventarc.v1beta1.json,sha256=mY2ecbNBWJyhuWfnF0fndnDH0Dqr1a38N8c36huuixw,46836 +googleapiclient/discovery_cache/documents/factchecktools.v1alpha1.json,sha256=W4CxWFn3fyxidiE6iML3nT2EJg8FsBTVPgOOGjXKy6I,22449 +googleapiclient/discovery_cache/documents/fcm.v1.json,sha256=r0WiNLM2iQTVVKZY5j8i72CC0xIqeTxkFVs-qmK3HEE,31737 +googleapiclient/discovery_cache/documents/fcmdata.v1beta1.json,sha256=MyF9jSa11RwspABXDPfTYu7GVCMRxKoOOAeb6FkJiIY,15964 +googleapiclient/discovery_cache/documents/file.v1.json,sha256=Ng9rZLXs9MJSPFiwC5h0RLkcP7heThuN1BxNCwP7ZL8,84557 +googleapiclient/discovery_cache/documents/file.v1beta1.json,sha256=zt8aM6uRdrrzmAu64K3uzfQKCferMAUkqHnp-TjNF9U,97534 +googleapiclient/discovery_cache/documents/firebase.v1beta1.json,sha256=zY_XPnBN8IKgUNmxXwRSw0xvfhwA1TjCyjmoVx-8zFw,116623 +googleapiclient/discovery_cache/documents/firebaseappcheck.v1.json,sha256=4sJ6aL6BDdt90T5PJa-4W5DbSIrHL0SvxCL4Dp5Xyxw,101098 +googleapiclient/discovery_cache/documents/firebaseappcheck.v1beta.json,sha256=ZgX4sBB3YsiZzB1iKf47-uyZKWS4hKs9F9UriqctAcI,119685 +googleapiclient/discovery_cache/documents/firebaseappdistribution.v1.json,sha256=mU5U6Iw-dcVvFKKcCWGDW9yf_gCJH3CxgYobhvNNqpU,65376 +googleapiclient/discovery_cache/documents/firebaseappdistribution.v1alpha.json,sha256=iTomZPSP4zvcinoHBkk8ZAwAhfeMp-n11NxGL15u5ho,58208 +googleapiclient/discovery_cache/documents/firebaseapphosting.v1.json,sha256=QgTbX7a0yIgK6BiY0OABIZ433mQNTwYeBvLcUqa6Fy0,97764 +googleapiclient/discovery_cache/documents/firebaseapphosting.v1beta.json,sha256=Kjb0Yxa1JBdGovyzrYjR8XvJ8IDQE-WsuU_BkeYTE1o,100361 +googleapiclient/discovery_cache/documents/firebasedatabase.v1beta.json,sha256=CDrBLeHyVymSxQdwRs4RMA7M-WBCs5Jg79lnLExxtuE,15647 +googleapiclient/discovery_cache/documents/firebasedataconnect.v1.json,sha256=aIB5rQYaRvalleFNR8zAxTbes5EuZ9SqJ25Za5wN0_s,72292 +googleapiclient/discovery_cache/documents/firebasedataconnect.v1beta.json,sha256=nhzwCO8Tla8xyPdiO1e-188c80rRWmxsJbY7IIbvC3M,72500 +googleapiclient/discovery_cache/documents/firebasedynamiclinks.v1.json,sha256=rncuTrigAtLNh7coo5yBLG10g9E7qNRzMl7D9Lrs6Uo,33276 +googleapiclient/discovery_cache/documents/firebasehosting.v1.json,sha256=iUmcrmwQcS2COWiCL1POQJOfbbFVMfnpo9eqWWUiyN0,26742 +googleapiclient/discovery_cache/documents/firebasehosting.v1beta1.json,sha256=35WM0roy6_pJoCwTgml7DPn-xXi3QU5jaZZDMfESBfc,133655 +googleapiclient/discovery_cache/documents/firebaseml.v1.json,sha256=fshZd5QIjB4RNnuMlW2r_7Sa50JKTyE-UHjmIEwDPik,10356 +googleapiclient/discovery_cache/documents/firebaseml.v1beta2.json,sha256=1Ajl7yL81dyXtz5SQPKdh6GpKMR6W3dw-tdYjI1Sky4,16713 +googleapiclient/discovery_cache/documents/firebaseml.v2beta.json,sha256=KZFmXSjW1cZpr7tfd5mHy36rdiDsZ6jjDHcD4ZMPkRI,88470 +googleapiclient/discovery_cache/documents/firebaserules.v1.json,sha256=ZJDkeRQTv28Vjex0ru4YEllbvnZbXMHPNxknLMZrUE4,34267 +googleapiclient/discovery_cache/documents/firebasestorage.v1beta.json,sha256=zOjCJ_8yjwYhvWe_8RQmeFP5aACyZe0DpTFgS5YNyS4,11253 +googleapiclient/discovery_cache/documents/firestore.v1.json,sha256=mafqepM5QcMeSOyl0_NtmIHd_sJF6ZAf9u_hzRQirUs,187413 +googleapiclient/discovery_cache/documents/firestore.v1beta1.json,sha256=tYrA25ymz6hQl0o82eKVRCZrcf6IEN6zuhmza1F2lpY,115178 +googleapiclient/discovery_cache/documents/firestore.v1beta2.json,sha256=JZ0NPEIf_QLVibDrdVQcj3EEKweoUqwcZR8Tqn4fa9M,42024 +googleapiclient/discovery_cache/documents/fitness.v1.json,sha256=1MKnVrlqoJrCbnSw2dXGgsnVrTpsoUvAoPtF2bObQTE,62402 +googleapiclient/discovery_cache/documents/forms.v1.json,sha256=hnOruUSkg9PsT1ei2K9k5tvM5LsTbFtQCVd1NHtvzEc,53219 +googleapiclient/discovery_cache/documents/games.v1.json,sha256=7kUSswXqMS8ajF2QNAafJFSXmfgmAACPwVeqgzDTQqY,102349 +googleapiclient/discovery_cache/documents/gamesConfiguration.v1configuration.json,sha256=CavvLLS58hm3p1cUvCznVE4CqBqUjR6qED8wQObr-Jg,19280 +googleapiclient/discovery_cache/documents/gamesManagement.v1management.json,sha256=EZFK6Rxlm2Hy0hv2F3sBto6UMvjJsykQ_fcmUYXq1LQ,23171 +googleapiclient/discovery_cache/documents/gameservices.v1.json,sha256=E5MFFlyECvsMxSIdo45glqQhAagCDHzeRSo13RPcJ-o,54733 +googleapiclient/discovery_cache/documents/gameservices.v1beta.json,sha256=amIruWItU7wwP_wTWMXY_g2eoY-2FW24EWyPxwQtMvs,54813 +googleapiclient/discovery_cache/documents/genomics.v1.json,sha256=r75lm6eDRH0cxivOOnIQnsm-KkrMY0C8Kp1H6WirqHY,44128 +googleapiclient/discovery_cache/documents/genomics.v1alpha2.json,sha256=OBijBJvThGSucv3G0IILtC8RNGFmdxYrZeLTDFMncsM,66239 +googleapiclient/discovery_cache/documents/genomics.v2alpha1.json,sha256=80yCmc2cqlgSJfPYAxqPMCKFxDWRksFMZzsEkgcsQmI,63816 +googleapiclient/discovery_cache/documents/gkebackup.v1.json,sha256=1f0D9ccdUM5aWXaTGotWRGxe4K_AEIFv9kSCCdwSCMg,191182 +googleapiclient/discovery_cache/documents/gkehub.v1.json,sha256=oZshUMxf2uDKZKoQmwVo3dw-c8nWFKBJXCfNlcMt3DY,232901 +googleapiclient/discovery_cache/documents/gkehub.v1alpha.json,sha256=X2UaQPCzlbJITSj0VV8ORCpiA50O0c9GScv3lrQoSjQ,265960 +googleapiclient/discovery_cache/documents/gkehub.v1alpha2.json,sha256=jIsXo_cDmHYf0RJNlhYTrM1ELjde46sbGHhrfbOGDc4,65373 +googleapiclient/discovery_cache/documents/gkehub.v1beta.json,sha256=R0flqaQVKs62EO89X3QCJf--IeHuZ7atPKD-0guzuYQ,236572 +googleapiclient/discovery_cache/documents/gkehub.v1beta1.json,sha256=_pI0ZcaheGrL251l6W0NHsVXLiKFahAdTjKRNWY8Lhs,71143 +googleapiclient/discovery_cache/documents/gkehub.v2.json,sha256=MafPn9XUCdG0f-Sfg5FWjUZYjQu2c_eohLZx9gYxnBY,109716 +googleapiclient/discovery_cache/documents/gkehub.v2alpha.json,sha256=P5LDNDhBE93oGeF9YZH6uosHn3Q2tVV3nYXuqn_35GQ,109826 +googleapiclient/discovery_cache/documents/gkehub.v2beta.json,sha256=HEVI4WN-glO_Y83bQ8Ofle_WK-0LjjdPdjmVDc8W_VQ,109804 +googleapiclient/discovery_cache/documents/gkeonprem.v1.json,sha256=P-CtgUh1Og6JaL6XMtFPbjfUeLJExkKff8P6mgWXjwE,253321 +googleapiclient/discovery_cache/documents/gmail.v1.json,sha256=b33GjsCnaBTA-_8hSLBe2mKVoq5viriLPlwgrdGqz9c,138855 +googleapiclient/discovery_cache/documents/gmailpostmastertools.v1.json,sha256=hn1pbcIEUbxWLI43jDndfvBw67dJ2MrnPi5cR93SBNQ,19156 +googleapiclient/discovery_cache/documents/gmailpostmastertools.v1beta1.json,sha256=fDU0TzGeaILZGZMr20TN2heEXDYK-Akmz5cIT8hIicE,19543 +googleapiclient/discovery_cache/documents/groupsmigration.v1.json,sha256=D1av9Pn3hJa_u2CCR0QiAOJzO4dnWVlxKPtcNpZzEa0,3947 +googleapiclient/discovery_cache/documents/groupssettings.v1.json,sha256=PwxhV_pC71kBNg0BHpRw9Ten-Qbst58PfAXVY6Ua5j0,24702 +googleapiclient/discovery_cache/documents/healthcare.v1.json,sha256=d-kQFHFM6dvaAFirYo6QAeJyXmwXh6EEVnXwMQDWI4k,438971 +googleapiclient/discovery_cache/documents/healthcare.v1beta1.json,sha256=541SQ8-yNLe8B_Eqlb22kGO5_mGZhGIKFgdqzucSmLU,498538 +googleapiclient/discovery_cache/documents/homegraph.v1.json,sha256=AA2WMT2GMNbzjn_AvW-J9O6KSkSDen_uC83-v18DvKs,19440 +googleapiclient/discovery_cache/documents/iam.v1.json,sha256=zopGsrFz7THF5Glzq-J5ieDL6iMFBfCJ26brpiizINk,260474 +googleapiclient/discovery_cache/documents/iam.v2.json,sha256=-PoSx-TxbrU8aYuDvtXphQeeKPYs6AV7aeuGUguEt3k,36073 +googleapiclient/discovery_cache/documents/iam.v2beta.json,sha256=b-lfD2P1OmmzpJVGCY23ZTBpsFs1bLBbn80HKbKP_LE,36197 +googleapiclient/discovery_cache/documents/iamcredentials.v1.json,sha256=dwj2vcEGYn55-h-svUulc9yXMaBZo3wDQmzsE0lV9NY,19185 +googleapiclient/discovery_cache/documents/iap.v1.json,sha256=2EVgmOPXIAilBgxhESRdRPVfebytDD32E8qXHLfhWOM,60719 +googleapiclient/discovery_cache/documents/iap.v1beta1.json,sha256=E-FmRVtEg5CcmV2MtJcrhp_5yYwbUnm1y0sYagRdwUQ,20190 +googleapiclient/discovery_cache/documents/ideahub.v1alpha.json,sha256=PfWK6J_Vqz1f_-mYWGBlCxLWSc8iwHrn9QRu0fl3GBY,21042 +googleapiclient/discovery_cache/documents/ideahub.v1beta.json,sha256=9N4Jk-jHWcWC-Cd5Hb_ARxh7nB6h2HVqrDNPRtei-GY,18785 +googleapiclient/discovery_cache/documents/identitytoolkit.v1.json,sha256=QchNLhHkm8ODfNrFmpHesc2I7l64CXJ96w6IbI9_mNo,143803 +googleapiclient/discovery_cache/documents/identitytoolkit.v2.json,sha256=5gGGHt5hfjUTobVCK_XKlrQTfu-U4sLkO7ggUWGeW5Q,136457 +googleapiclient/discovery_cache/documents/identitytoolkit.v3.json,sha256=jg5fCSI6F9Ubd6pdyjUdL3KZboo1DwLrwX_fo1SQfIY,54662 +googleapiclient/discovery_cache/documents/ids.v1.json,sha256=Q2QF6Xb_8qM769F5dVZqncRpuQ0CkvrRN177T5Kbf54,25967 +googleapiclient/discovery_cache/documents/index.json,sha256=aToo8a5LH-shdyLDo4-_QRwB6s1vFYEsF2w-gmO3-eg,213200 +googleapiclient/discovery_cache/documents/indexing.v3.json,sha256=VniFOPVeV6ho_SPcRiHzZD1WuhDlrmib49WzGG6EUoU,5776 +googleapiclient/discovery_cache/documents/integrations.v1.json,sha256=fdp3yTSJPg1JC6KyT-DLAo-iROjmfEnklGY0JbDwNAc,480074 +googleapiclient/discovery_cache/documents/integrations.v1alpha.json,sha256=-bp1QUgLeateldClVafXg6Z8lbasIk1B9x0Vc5UwSKk,376245 +googleapiclient/discovery_cache/documents/jobs.v2.json,sha256=L-aDKIJ86eq-tEmOrHZfKD2MmQkCP_uTwCCTQHSJcoQ,227088 +googleapiclient/discovery_cache/documents/jobs.v3.json,sha256=OCDFs1rw8-vh_vIchswkmKEqRosIhpaNOumknFxVE3s,121113 +googleapiclient/discovery_cache/documents/jobs.v3p1beta1.json,sha256=ycJYA6hdxv4Asou1NfqBkeKZbHFMdQbP4kqG5USORww,135102 +googleapiclient/discovery_cache/documents/jobs.v4.json,sha256=zJT9KRD5R56uuhwxPmUrV7f4VI5w8rLNxR7f4rBeikc,135236 +googleapiclient/discovery_cache/documents/keep.v1.json,sha256=4L9rSisFKCYF9sazu5Goh0j1_L77pYhAfwEgTq7ptAQ,16998 +googleapiclient/discovery_cache/documents/kgsearch.v1.json,sha256=ZwTdiUrvYERjzOanj4JdPhI2Z9Y_A43vI79EmFRr6io,4886 +googleapiclient/discovery_cache/documents/kmsinventory.v1.json,sha256=yIk3tmTbB577w4q4ciyljg4ZJXL0TTFgRfoxvl4hqQM,38172 +googleapiclient/discovery_cache/documents/language.v1.json,sha256=mE0uY0frqt4Wz_nBOocEv9mRhGEfW_4CTaC4sh7CWHM,151542 +googleapiclient/discovery_cache/documents/language.v1beta1.json,sha256=-Nwsr0Ls6nKWMZSQ3ZzkW1Zdvu2gEqb6yt4r65Z1xOU,38558 +googleapiclient/discovery_cache/documents/language.v1beta2.json,sha256=qLKTCEpVWCLgP8uT8FagfKPpDwir-PD0H4prgZWAXck,152340 +googleapiclient/discovery_cache/documents/language.v2.json,sha256=mbdj_eAp61zYoNMoP0ZSLNEEN_Qov2nZgaL6fbNJs5g,138008 +googleapiclient/discovery_cache/documents/libraryagent.v1.json,sha256=DoFPi9frga11E11_DL9e8wQ6cZQfLrr1TqUJq3oNNBc,9898 +googleapiclient/discovery_cache/documents/licensing.v1.json,sha256=CB4ka9YxsG5xl6ujOQN8JusXErFtL73mqgHHw0u5m74,15827 +googleapiclient/discovery_cache/documents/lifesciences.v2beta.json,sha256=ci2-lfSmer-UPyp34RLAJpE9nZwbQJOlhVVtLsMkwKU,52568 +googleapiclient/discovery_cache/documents/localservices.v1.json,sha256=x6aX43jOnqyA7U-kk3WhT81I9IiVEzWXvlibZ8BjARw,18779 +googleapiclient/discovery_cache/documents/logging.v2.json,sha256=8A3o1FhOYB9a8wB3HR07Pv8lff6tHL2PlQA29CCoWaE,498844 +googleapiclient/discovery_cache/documents/looker.v1.json,sha256=wsy988PeWJjPrO_37MdaI4Ajxg5mC2Jmo68oKaS50pI,45422 +googleapiclient/discovery_cache/documents/managedidentities.v1.json,sha256=Q2n75aQO9t_LsmTZqdtYv39CGHdaOtjKCNp7tvYnq-w,118816 +googleapiclient/discovery_cache/documents/managedidentities.v1alpha1.json,sha256=fAkJW-6Y6LsqyxtxgOHtJ0-aIssxdRIfZuKcCFEOOHM,118842 +googleapiclient/discovery_cache/documents/managedidentities.v1beta1.json,sha256=HxowKK3QiyXdNkLuF7-qlnQZ2Xc-QFA_n4KQbyQyOdg,119795 +googleapiclient/discovery_cache/documents/managedkafka.v1.json,sha256=ZArFFPSshwVxappO-ZDtIBSFDI0KfKsebw2MrRTsnlM,148751 +googleapiclient/discovery_cache/documents/manufacturers.v1.json,sha256=U88bUQKj4jTRJg_6sfwe0z8J_-Il9R9TO5nAIxASzLo,41060 +googleapiclient/discovery_cache/documents/marketingplatformadmin.v1alpha.json,sha256=qTk0pcCjd6-CAIXuWIlogDucnUW-AU8Rde-UEsODlk0,12562 +googleapiclient/discovery_cache/documents/meet.v2.json,sha256=Qesrk9wWj88A3wQzujY2bwTZeD18DY_b_KY6D-cn6yc,43604 +googleapiclient/discovery_cache/documents/memcache.v1.json,sha256=PHK31QEOXRYkeSFkyy7yvwoaHUqveTd7Nm9dlRo_WmY,64890 +googleapiclient/discovery_cache/documents/memcache.v1beta2.json,sha256=FK5nlnEOzAiQwYK8Ngc96ZpRT75K-0rizjWYBIGjeNI,66816 +googleapiclient/discovery_cache/documents/merchantapi.accounts_v1beta.json,sha256=jt1b6zDsrwfU_AzXvDBlTOLsTTEz30nXtn3xl85R_sA,181984 +googleapiclient/discovery_cache/documents/merchantapi.conversions_v1beta.json,sha256=xRrIlKaHMuyiSgGPzgIKY7yqk8pTcv7rU5PHmsQyYhQ,20633 +googleapiclient/discovery_cache/documents/merchantapi.datasources_v1beta.json,sha256=2fplDabsnaCuM_cSUjG9WxTeCpqsdIrTwhujH8890-U,36703 +googleapiclient/discovery_cache/documents/merchantapi.inventories_v1beta.json,sha256=wWhgEKK6ZjCioKbUnQnbd8hbxKb1td8z2SnTrktouUk,24157 +googleapiclient/discovery_cache/documents/merchantapi.issueresolution_v1beta.json,sha256=cf108YGXR70yF7uXdXiBQHUv7Ms8sw0eQMFZ3S2jUnY,50614 +googleapiclient/discovery_cache/documents/merchantapi.lfp_v1beta.json,sha256=JbhVEPdrrXEV7Mew8fiaDVg5kppVYHlsH4ymvsgbp3Y,28956 +googleapiclient/discovery_cache/documents/merchantapi.notifications_v1beta.json,sha256=TLSLS7V69FLKGdN1E9jhr8ziOI68lhfu3seynuyX_-o,15632 +googleapiclient/discovery_cache/documents/merchantapi.ordertracking_v1beta.json,sha256=ceyQX0n8DBH40GR8sre5_ucQFq1FHeWmzVWhCFB8TnA,18886 +googleapiclient/discovery_cache/documents/merchantapi.products_v1beta.json,sha256=GX6EdvcV5AzmsAlz74VjngJRaZLZoHpp9OsJsJx7V2Y,68033 +googleapiclient/discovery_cache/documents/merchantapi.promotions_v1beta.json,sha256=pe97bbCq3graHHzPnOUp1eUgFzaVrBBa018_wczQWWE,39921 +googleapiclient/discovery_cache/documents/merchantapi.quota_v1beta.json,sha256=vHbfGjuKXASRclsAEyUVL4igvxvPhcUiWiyce6t7HCA,11679 +googleapiclient/discovery_cache/documents/merchantapi.reports_v1beta.json,sha256=6vPmPamCWYp-gFg2YR4GOJT0WNaCYmhGQqPmBCsnano,58777 +googleapiclient/discovery_cache/documents/merchantapi.reviews_v1beta.json,sha256=Ys5MolynZi1lzHjBUDHrw9gP6bpS7iqIRGlXNoGKYGE,42797 +googleapiclient/discovery_cache/documents/metastore.v1.json,sha256=OrS8GgqX4SLN9pvmAaoRMrhpTQEYcWzR_1NWcApT_8o,141081 +googleapiclient/discovery_cache/documents/metastore.v1alpha.json,sha256=akhF7cr5gPffMNOObVM_YL-pAkBYtTyPABb5gom6lIA,151197 +googleapiclient/discovery_cache/documents/metastore.v1beta.json,sha256=9r_qaDnOSNXg0eldaJ7S7KPqj7_fP86XFGVEUW0lFQo,151091 +googleapiclient/discovery_cache/documents/metastore.v2.json,sha256=QTDp6iCKRTDdBXjTLuuGBliz6jaTq5bBw2jlA5mN1dQ,66531 +googleapiclient/discovery_cache/documents/metastore.v2alpha.json,sha256=DPqtcLgeHhEGbxZWcU6NnFS9SmH5rxGvoi9y_yGq7mc,87673 +googleapiclient/discovery_cache/documents/metastore.v2beta.json,sha256=MrlztbziAhAib5eqcL4O5rUW_eYrcEzk8sICx_IVwZ8,87517 +googleapiclient/discovery_cache/documents/migrationcenter.v1.json,sha256=KbXLa4cfYbi2P1aHswZTk5nEdLk9eiEaxb-Moi2pZZc,208136 +googleapiclient/discovery_cache/documents/migrationcenter.v1alpha1.json,sha256=smzLeiy_HlMAymu8DoGQW6Dyf5F3qT1hFi4mIJN0mPM,266655 +googleapiclient/discovery_cache/documents/ml.v1.json,sha256=Q-dBFvLCgnV25aG6YILqNCB3wpL6PK7pJ_TX_xXzxJo,175519 +googleapiclient/discovery_cache/documents/monitoring.v1.json,sha256=3i8EOlzpt3fkf3olFi9HaOqCWQCRVvQv8rzkySueimY,115224 +googleapiclient/discovery_cache/documents/monitoring.v3.json,sha256=uc6va0ra0Au9BsihROYClnCz2eCleAlLQC6FT6gWj14,342632 +googleapiclient/discovery_cache/documents/mybusinessaccountmanagement.v1.json,sha256=ue2l9wxhctz1M9pNi4G4fHHUBAzzmu0Sd2_qF7teoG4,31920 +googleapiclient/discovery_cache/documents/mybusinessbusinesscalls.v1.json,sha256=w_OnSvJZU62j-5J8o3Mt3CmA2Rk7_GKu5DuhsIV574Y,16209 +googleapiclient/discovery_cache/documents/mybusinessbusinessinformation.v1.json,sha256=z7wc5yVzEvtm_aWWtSvimqGJQfdrcEeQWn9qE8P3XpQ,66301 +googleapiclient/discovery_cache/documents/mybusinesslodging.v1.json,sha256=3XznJiEG44cWQkgSHQrS0u8P7mX6J6Ck9P9hGN1Sf4Q,222770 +googleapiclient/discovery_cache/documents/mybusinessnotifications.v1.json,sha256=iuA9q6GqeWcDfbXU-FrSAkrjOAXOeRBSPUXbSiIVA1I,8029 +googleapiclient/discovery_cache/documents/mybusinessplaceactions.v1.json,sha256=EnWkiYLZggSlFINF0ujYooNwRMh1qPxdVLR2n-Ikhbk,14578 +googleapiclient/discovery_cache/documents/mybusinessqanda.v1.json,sha256=MBjZalhwZNuin_Y54kxl13lctTp5ODRexqgaUK0BCBM,14263 +googleapiclient/discovery_cache/documents/mybusinessverifications.v1.json,sha256=CVGhi48NjTwKUWM91iYDyFHz1B3sodLEmIcDRJsphDU,25479 +googleapiclient/discovery_cache/documents/netapp.v1.json,sha256=yfaG40BEHfESuxSbImRGU1gsLgB1Dwmk7E8IzgKDjuY,132868 +googleapiclient/discovery_cache/documents/netapp.v1beta1.json,sha256=l2JCwt12V4AlbglZG-p1oghXDjVqHjn1N7b1JGJgLqE,135736 +googleapiclient/discovery_cache/documents/networkconnectivity.v1.json,sha256=vp5QrvGvdhA2TekHHglvkesv0C065WEZCIpVs2rY-hk,233274 +googleapiclient/discovery_cache/documents/networkconnectivity.v1alpha1.json,sha256=BYbqeAQyAjdam-lAz5kv4jGmUU0i6Q3VTZEXYHACzeM,80819 +googleapiclient/discovery_cache/documents/networkmanagement.v1.json,sha256=EB1PuRhLwZn7owOCqIjr7_xiMw4_jto5CK2H9xByJlE,150327 +googleapiclient/discovery_cache/documents/networkmanagement.v1beta1.json,sha256=t0IVfG5M8wTEUvOZJC9ZQ8fnmfes4J-2XeLqw3_oIZw,160202 +googleapiclient/discovery_cache/documents/networksecurity.v1.json,sha256=4DB0hdd5_s6bpm58-K1SWasZ4nfQRlKuBgr6hBrbh_Q,321553 +googleapiclient/discovery_cache/documents/networksecurity.v1beta1.json,sha256=0-TH4W7aoolPMfllFVqPbcwux4aaLqExOby1TjPfdLY,341878 +googleapiclient/discovery_cache/documents/networkservices.v1.json,sha256=YSmv-EUWPhy6kkK9nJ-vxa6z5ap9c3S5jS-BeXEg7Hk,237191 +googleapiclient/discovery_cache/documents/networkservices.v1beta1.json,sha256=nYx4ZW7fXuYM9liHxucionBYH_GZxczO_tTOIQyEKr8,223679 +googleapiclient/discovery_cache/documents/notebooks.v1.json,sha256=ii6adyZhX9r5ekNsPuU4bd8TnpUpnvTZBZEiGUPYqDA,159045 +googleapiclient/discovery_cache/documents/notebooks.v2.json,sha256=OQ8QeMKWBQvckkTD-hKkH3abiYE1Ao8f1nhKXopIam4,77084 +googleapiclient/discovery_cache/documents/oauth2.v2.json,sha256=qbqQUKMu6g1IrIHIAfYwTAZZgIDf8j69Lr6i-rzbzLs,6601 +googleapiclient/discovery_cache/documents/observability.v1.json,sha256=3v1n8q4xGfvYHJiGrKUN4-8n4887eHXDzISOmfLSsRw,18284 +googleapiclient/discovery_cache/documents/ondemandscanning.v1.json,sha256=RlWelWdmPc5dsKJHTt8Igav1IMtKEy7BD4nCNFE9zh0,94143 +googleapiclient/discovery_cache/documents/ondemandscanning.v1beta1.json,sha256=PloJDEtVfLlxDibygVRLP_4LTNSscKiN5yl6FNlX6aY,93994 +googleapiclient/discovery_cache/documents/oracledatabase.v1.json,sha256=O9Y7eB0sTj8nYDaC_IxktcOs8rvOjjnxPuO6ym8dfkU,121769 +googleapiclient/discovery_cache/documents/orgpolicy.v2.json,sha256=kP7gol-Qbrp6o507uYp3UiaEFkCkcuNyibyDT4zn-28,55610 +googleapiclient/discovery_cache/documents/osconfig.v1.json,sha256=GVMjO90q8t_boI__GiFf5Mng4pznwVFw7knhTbzV3QU,141498 +googleapiclient/discovery_cache/documents/osconfig.v1alpha.json,sha256=aip_V60o7wVkvESTNkOfh51lZEuCGLxW-EjglGCi-Sc,106049 +googleapiclient/discovery_cache/documents/osconfig.v1beta.json,sha256=0K9K0Spr4Rt83E58qmvMq5Ht28A6uibpmBvLTS_0KQg,87545 +googleapiclient/discovery_cache/documents/osconfig.v2.json,sha256=qv7ZxoHKtUsbSrnmufwBB1hfHHDQlyaPE-akOKwYu54,88480 +googleapiclient/discovery_cache/documents/osconfig.v2beta.json,sha256=VQxFkLsqgf1UUB6K2AZWFCwGGZHA2cPS9tovx5UNzZk,88860 +googleapiclient/discovery_cache/documents/oslogin.v1.json,sha256=ilwmbOAL-S-KfXTcy4mUKI-dSH2ZV9tP61fSVl5hxzs,13149 +googleapiclient/discovery_cache/documents/oslogin.v1alpha.json,sha256=a43X8cDkL6qZA-knmrYL1Llgs1U-y_OYcoNI4FZNruw,21955 +googleapiclient/discovery_cache/documents/oslogin.v1beta.json,sha256=24Sfz5r1NM--HcaYN8Y7Li_WxYXjQN4DLNsGeqmm10A,21010 +googleapiclient/discovery_cache/documents/pagespeedonline.v5.json,sha256=HLFi19o2CGZYT-nR4oK9F-9tXBWrREeBDm9f3PKKcJY,28503 +googleapiclient/discovery_cache/documents/parallelstore.v1.json,sha256=aZs1oKvPCoOHr0rNNrRyst4-qxpf6ufFfWGL5hh29C4,36618 +googleapiclient/discovery_cache/documents/parallelstore.v1beta.json,sha256=bm2wwH5FIdeCNIJKi2ksy_7t4gVgj6YVW9ElrWl2tPw,36513 +googleapiclient/discovery_cache/documents/paymentsresellersubscription.v1.json,sha256=_J8m3p_DhR23ile5m34U0O2_gn_aAkljiwxGUJp1inU,68608 +googleapiclient/discovery_cache/documents/people.v1.json,sha256=9-aQd4MBUAhJkl5wpEfTccS2ipglZT8uf978tHdcKAU,112570 +googleapiclient/discovery_cache/documents/places.v1.json,sha256=bOnxpoZCWBEjF-qG6gN3HRQiddGhW20mYgK3jVwmUvk,110121 +googleapiclient/discovery_cache/documents/playablelocations.v3.json,sha256=wbkjdTm2IPCudHBKwwIOaAWwsRxfcinsOiKPR_C5G4M,25906 +googleapiclient/discovery_cache/documents/playcustomapp.v1.json,sha256=pG8LwuC9yO1R9lSyNXVskFTrZaBm_MQCl3JPegK2yck,5201 +googleapiclient/discovery_cache/documents/playdeveloperreporting.v1alpha1.json,sha256=ZD3dFjz_B-G6KJ9QLGJiGnmexwKfYQCMmA5cTt-d7JE,148544 +googleapiclient/discovery_cache/documents/playdeveloperreporting.v1beta1.json,sha256=1VGZvgncXNlUAwX4wS_b-dymag1-CmWEE_R8f9YRJ0o,148331 +googleapiclient/discovery_cache/documents/playgrouping.v1alpha1.json,sha256=IiCHjssDE3DyDE09U8j9GumZpi2t6SZfFiy_myuQm-s,6307 +googleapiclient/discovery_cache/documents/playintegrity.v1.json,sha256=2UG5AC_OwwBSTkNsgOlIaDZfeXa0LnLPQIwFVituiGE,22302 +googleapiclient/discovery_cache/documents/policyanalyzer.v1.json,sha256=UbzYQTXuhZcV_f8klEA9ps8syc4RTJ_30TpRYiLa5AE,11965 +googleapiclient/discovery_cache/documents/policyanalyzer.v1beta1.json,sha256=uc6Tw0al4RaKcVAwNyNoA2nEUNP7uzUdPxnZxnz6isQ,10922 +googleapiclient/discovery_cache/documents/policysimulator.v1.json,sha256=cmsFPE3YtJ6oFUxed-BNF9Ci02GiZMluiQ9O2klZdYo,100598 +googleapiclient/discovery_cache/documents/policysimulator.v1alpha.json,sha256=53UzAMBVDIQV4TlyG7JHSH87zCkxYkhGDV0bdQvxPy0,58233 +googleapiclient/discovery_cache/documents/policysimulator.v1beta.json,sha256=2N_wuSwKyT9egEsF_breBOmSVqirQXoyzhqULoiHCuQ,104967 +googleapiclient/discovery_cache/documents/policysimulator.v1beta1.json,sha256=Q1ufGYQSG04J4ufoZ0JH4hgwdeN1QeW1dhREOv-b0Pw,54107 +googleapiclient/discovery_cache/documents/policytroubleshooter.v1.json,sha256=3WWpBNOwDE2E_9qN56IAkB_QoNxbKa656bHHCbmGbB8,31718 +googleapiclient/discovery_cache/documents/policytroubleshooter.v1beta.json,sha256=k5NV64Ld0v4t3sr3ajAP0LfK9-k6OgfaR_AyZxJPQko,30156 +googleapiclient/discovery_cache/documents/pollen.v1.json,sha256=5yHEc8-STvhGa8G0J929bXjT8-YR4aUBN-U0yf4e6NA,21526 +googleapiclient/discovery_cache/documents/poly.v1.json,sha256=MI1zdlmWLLalpCwlx22n33nkszug6pksZb9_1x96K90,27091 +googleapiclient/discovery_cache/documents/privateca.v1.json,sha256=ggTWGfaz1fyeZElh0zB6UbPruvxRA3pb7nQ5oJasJIg,152263 +googleapiclient/discovery_cache/documents/privateca.v1beta1.json,sha256=-IYVzz8Z5iIw2AuWRzhg8A4Sq8H-jn6I9mNTnTiKvG0,44228 +googleapiclient/discovery_cache/documents/prod_tt_sasportal.v1alpha1.json,sha256=96j345PnT94kQzeYPHlixWSiQk6hQ_AGYkSe7190DEs,100005 +googleapiclient/discovery_cache/documents/publicca.v1.json,sha256=msybmT2yjAQKtsnvMrA37fvWwf6i92SS9zU5RiUMne0,4849 +googleapiclient/discovery_cache/documents/publicca.v1alpha1.json,sha256=lZTujGOmJFdOVOrYFlqse4jJOM85qOAYcV_4WhALNcU,4873 +googleapiclient/discovery_cache/documents/publicca.v1beta1.json,sha256=TamTpQDX3VRyn6vt6k89HyKLcMSf9UaI8pebzVqpWSw,4869 +googleapiclient/discovery_cache/documents/pubsub.v1.json,sha256=0sJBrNZk5ELSAAt90GE0UzFT1B17u5AjD8ao23IcYrQ,131361 +googleapiclient/discovery_cache/documents/pubsub.v1beta1a.json,sha256=BANlfJnV40qmdfOkDwirxdhSc11PDRjaeV7lh2QsBuQ,26028 +googleapiclient/discovery_cache/documents/pubsub.v1beta2.json,sha256=3Y211hPblsfNRtfZ1J1PhPJy3sn5y_knPVAaxndVWPU,51138 +googleapiclient/discovery_cache/documents/pubsublite.v1.json,sha256=WMbpgrapU3kLiHERlUxjwYWKRYbm5FRYPQd4j514NI4,53052 +googleapiclient/discovery_cache/documents/rapidmigrationassessment.v1.json,sha256=85IxZPgGgTo9OAsfzdOccKm5eeMTJzXdZo_PbglIOX0,32706 +googleapiclient/discovery_cache/documents/readerrevenuesubscriptionlinking.v1.json,sha256=jg9GE5YxOZEgHpJU99qBqwpDmYfTkb9uWX47p1LR0Qs,9170 +googleapiclient/discovery_cache/documents/realtimebidding.v1.json,sha256=H7rAgUK0WvN0jyw8tyfA7Pcv1M8UodsQAVIW68e01yg,118786 +googleapiclient/discovery_cache/documents/realtimebidding.v1alpha.json,sha256=0aZYwk8L6hmk_xVK_rr4BwT4FPEn56oiZWKVqin92rs,18365 +googleapiclient/discovery_cache/documents/recaptchaenterprise.v1.json,sha256=_VkKIm6eoLVqNhUxl1AhjV7yUhUGy44NBaycmlU-RSE,97461 +googleapiclient/discovery_cache/documents/recommendationengine.v1beta1.json,sha256=k0aW98mk8r7nsXNx8-yE_x0AIfu9uBMvo2XE14KkfeI,87898 +googleapiclient/discovery_cache/documents/recommender.v1.json,sha256=opxLJE3suZOJxlGLWEBWJCNdYVb2WAXiuuo5L42bHyE,98951 +googleapiclient/discovery_cache/documents/recommender.v1beta1.json,sha256=ZhhEVtBinUdLScN74LaAkBC84JCD-4DuJ-1S01qnMAc,111437 +googleapiclient/discovery_cache/documents/redis.v1.json,sha256=X9ke-io3G3VUmrLL0LmjFKLWPSdLth7foSGh8PyabKo,164878 +googleapiclient/discovery_cache/documents/redis.v1beta1.json,sha256=YM-2dpbD7hwPxgQ5mgobFFkcey1x8SDtFO_dHVw9rTY,165748 +googleapiclient/discovery_cache/documents/remotebuildexecution.v1.json,sha256=7GFLt5IiI_-OYe68YsVR99EYWAZbRDdQ7MBSu2yU8n4,117609 +googleapiclient/discovery_cache/documents/remotebuildexecution.v1alpha.json,sha256=hSDoD01FhwXYIVbrOwSe7cLI19DoN1AwZm4ylBQzTgU,124864 +googleapiclient/discovery_cache/documents/remotebuildexecution.v2.json,sha256=EII61EfJ8sqYPcx-Ilk5j-XosxGTIfrN48mLKLkGfnQ,148991 +googleapiclient/discovery_cache/documents/reseller.v1.json,sha256=Yj6bAjZzjoMxi574h73yo407FyuUUr5Xo7G_JlGkxx8,49119 +googleapiclient/discovery_cache/documents/resourcesettings.v1.json,sha256=PBtggh9NeN9JMcNY29fETTCUnggc6vP3cjwFXEEp_jo,22442 +googleapiclient/discovery_cache/documents/retail.v2.json,sha256=ueCcDd62i_LDOM7vRgp7xOCDQ0PZQeug6f8skvvQxg4,376787 +googleapiclient/discovery_cache/documents/retail.v2alpha.json,sha256=-QqW9AKXnEwmnNfvb6-U3AjOuMJBX34K0SCkmWdlOt4,439032 +googleapiclient/discovery_cache/documents/retail.v2beta.json,sha256=JsxkFBi4s4Z61QJsdBHFHyvz-0aLbVz4KUqEZZyfWNs,396068 +googleapiclient/discovery_cache/documents/run.v1.json,sha256=J6hNuYy0W2uok0qTgx06CBFE7cxFnpB8ZpGDzEGRBU4,258648 +googleapiclient/discovery_cache/documents/run.v1alpha1.json,sha256=Z0H_iXudGt7JDmcS4XZx09xCSBXPBv9MCktQqrAiayA,69965 +googleapiclient/discovery_cache/documents/run.v1beta1.json,sha256=huF9CDeN1HdW5tai_neIoAPtXOqg1t_KxstLag14WiE,40411 +googleapiclient/discovery_cache/documents/run.v2.json,sha256=RjZKLqzhahbV3Ysc6mwC4oE9XJA_3RfTHDNfIHhig5g,264953 +googleapiclient/discovery_cache/documents/runtimeconfig.v1.json,sha256=a9eko6S6zJLWmkOlnqRstqEfiRhdFG2KKWgrFmk2NCY,10289 +googleapiclient/discovery_cache/documents/runtimeconfig.v1beta1.json,sha256=U-Eglt6hR7I2J8zmVDlWhGK3R2gs1Iy4SRZ25Z9TmD8,55381 +googleapiclient/discovery_cache/documents/saasservicemgmt.v1beta1.json,sha256=GfTqN9utVvWU5IPOFQjhsBJxE8JBiRERC04Oav0rdBw,123001 +googleapiclient/discovery_cache/documents/safebrowsing.v4.json,sha256=swfVWEKVKLtGSoSNbRdA0LdXy48qohgK8Pnwf6yiIjE,38346 +googleapiclient/discovery_cache/documents/safebrowsing.v5.json,sha256=IaeiQ_bXsQZjBAvCXNAAjnA9tSlhwjN8V_q5rqMyS7s,28399 +googleapiclient/discovery_cache/documents/sasportal.v1alpha1.json,sha256=MYsQcG35bK_r5XtPy_fGHq9fhWGRDCbfyftXSDP9K8c,99260 +googleapiclient/discovery_cache/documents/script.v1.json,sha256=NbawB8y4RGEF3c-4M2xt30DkLSTbjoWOs8A0d8NbD1s,49028 +googleapiclient/discovery_cache/documents/searchads360.v0.json,sha256=OcIQEMnizor28p1BbkXxG053PFTfHTFjlGwv3G5pNRY,332283 +googleapiclient/discovery_cache/documents/searchconsole.v1.json,sha256=w_Zd73I9mDUeGWCMT0-cOKLvuQ05JM-kNBYdxYBB7SY,40740 +googleapiclient/discovery_cache/documents/secretmanager.v1.json,sha256=4_5x9JRZJaOBAjkdUrMsvbN004aXcTamZ-r2Djtlxmo,75801 +googleapiclient/discovery_cache/documents/secretmanager.v1beta1.json,sha256=BeUtii98LamnzfqtOienR5of1d83OtkqmTKKUv9v-ak,47622 +googleapiclient/discovery_cache/documents/secretmanager.v1beta2.json,sha256=HYRTCoQJnj-oZzqalcrFAbxkxfxWuWmBHoYxc2G8C7U,76127 +googleapiclient/discovery_cache/documents/securitycenter.v1.json,sha256=f3BZUPYkWtFJX6m4FK6UoI8SvB3Kfp5RE09UtnyXHxw,607622 +googleapiclient/discovery_cache/documents/securitycenter.v1beta1.json,sha256=HPQOE_qi7JRERkg6_5Iw8FH95HfzisKHl57gRPmjV6g,365723 +googleapiclient/discovery_cache/documents/securitycenter.v1beta2.json,sha256=BeoibV5ogNLC82T9YMxRVJtxT3nC5obxMM94Ph2h9cY,388542 +googleapiclient/discovery_cache/documents/securityposture.v1.json,sha256=G4bi4SQB4brKJWQ-UucQWfXuUixYQogjRWGdppzFneo,71190 +googleapiclient/discovery_cache/documents/serviceconsumermanagement.v1.json,sha256=UbsEDe2cG5eXXoPb8oXwQFE48NJBi4bpKHZZXuIrE2g,165122 +googleapiclient/discovery_cache/documents/serviceconsumermanagement.v1beta1.json,sha256=CPFu85PuDpehmvUjDGK0gjvjeOQckNPgn66GRX6c7WU,172604 +googleapiclient/discovery_cache/documents/servicecontrol.v1.json,sha256=l4vkhVKDwRHzx9mQcaNPYfEfgJTbkYE7JjMzBTLPWrk,98463 +googleapiclient/discovery_cache/documents/servicecontrol.v2.json,sha256=Yz7W2H74UR3n5AMQ672d8kyghGy-sA31Gpb_GdjEf-I,54820 +googleapiclient/discovery_cache/documents/servicedirectory.v1.json,sha256=xPTK7-3JD1nhXCXo8EOJ_9HDBM4iqlmJGlWNM3QGIS4,54438 +googleapiclient/discovery_cache/documents/servicedirectory.v1beta1.json,sha256=G3zhHnCaljMMYa9y4m4yhZ-RDP11aw6joKsg4YA-uqM,58940 +googleapiclient/discovery_cache/documents/servicemanagement.v1.json,sha256=82d_8dLDgapSO9BAFSMSB-XhJdy_EhZAoHDyxbyOZyI,185858 +googleapiclient/discovery_cache/documents/servicenetworking.v1.json,sha256=LHP8dV4pWhimwf3OjPhEljYYGjQKd6VbesgJu9SDiVQ,200704 +googleapiclient/discovery_cache/documents/servicenetworking.v1beta.json,sha256=JSPITljmO4B3uo4NK5ge0BKm5aw8PxRdEXKjHVcii_A,153256 +googleapiclient/discovery_cache/documents/serviceusage.v1.json,sha256=2Y35PcH183J0rAnFZhTmjB3LLOJBINDQU7FeJwspS6s,171217 +googleapiclient/discovery_cache/documents/serviceusage.v1beta1.json,sha256=kQcwF3e1qmgCL6PFyiZQ86hjSi9d7prom8Q4Xv0Rk9Y,208815 +googleapiclient/discovery_cache/documents/sheets.v4.json,sha256=K46s2XtznVSxYshbAG61X-mXtRb3nZdeBr4zeE6yO0E,300187 +googleapiclient/discovery_cache/documents/siteVerification.v1.json,sha256=xvq_xsL575_6zsUckW9eo-jWWdxW6Ng13g8ohB2uGLA,8419 +googleapiclient/discovery_cache/documents/slides.v1.json,sha256=QUf-dtFq3TVqEyUT0Y8_ZagQmmF-BC7hB0UPKlsxBDA,185359 +googleapiclient/discovery_cache/documents/smartdevicemanagement.v1.json,sha256=VRNJs4ILczG5VbEi7-_jw3YjEkzGG78gRfeTwHHkUvM,12914 +googleapiclient/discovery_cache/documents/solar.v1.json,sha256=R0L-_8Rf3317nZZfvOMo9aKCrppE1OgIV3ZlLFlO3Xg,38899 +googleapiclient/discovery_cache/documents/sourcerepo.v1.json,sha256=PpTvPOAbVUYvw7py9gMn6bT_zn01aR939Fj9WvoSoTM,38672 +googleapiclient/discovery_cache/documents/spanner.v1.json,sha256=Xi2KaoKW6c4mj19KdcF95x_L4C5P0S6WkPFaXVklTYQ,368470 +googleapiclient/discovery_cache/documents/speech.v1.json,sha256=GGEKtQoIBpaSPC5aUoJ2ITnTKiz6pdQDynndl3t5xvQ,64012 +googleapiclient/discovery_cache/documents/speech.v1p1beta1.json,sha256=DRXTB7k62NiHvh0Ba2x1DZKAot2Hs6svqTAuKtOhVEU,65166 +googleapiclient/discovery_cache/documents/speech.v2beta1.json,sha256=uKUcKcn6zNl_egbyhzSYNTlr_o2tpGelQ0WctfRAU54,18493 +googleapiclient/discovery_cache/documents/sqladmin.v1.json,sha256=JsUudNDOmZCfCiExL77a2VSflfTeRTva3Hmc3jyhUyg,239088 +googleapiclient/discovery_cache/documents/sqladmin.v1beta4.json,sha256=8iu__iCsKDKFXnhLSSlhiPoVfpidD5NZsi1bZqp8GYA,240508 +googleapiclient/discovery_cache/documents/storage.v1.json,sha256=yofiohfcl8kwoEPYY1yVmzHrQRaRJTDxRRWddZUuAmw,197106 +googleapiclient/discovery_cache/documents/storagebatchoperations.v1.json,sha256=juPc8bWuyWDug-Ta6QJSl8BQ67qr9sCq0E_aeKbX1uw,38891 +googleapiclient/discovery_cache/documents/storagetransfer.v1.json,sha256=nlECn8prj7FS-pK6zcBzt_SJWQp2rWvPL_zT_Mj7TV8,85407 +googleapiclient/discovery_cache/documents/streetviewpublish.v1.json,sha256=6yewpIR1whuQeotQcU0Z5FM9nNBtK4KxCT2nE6ihTz0,48408 +googleapiclient/discovery_cache/documents/sts.v1.json,sha256=JZ0k92FpUt6bBNTcRBit5cIKGi7pUi_EBlBydlFWVPk,33314 +googleapiclient/discovery_cache/documents/sts.v1beta.json,sha256=GKQBwAcg1z50o2nLoboaDf6T2YwJZPeYTlsbiv-qL-I,31941 +googleapiclient/discovery_cache/documents/tagmanager.v1.json,sha256=DwiLhm0oFCAxipKlqoeRcwRv3yNhi-exJXbl75AEaGM,75026 +googleapiclient/discovery_cache/documents/tagmanager.v2.json,sha256=oWixDj6ojiIGiRtH3ZZp0vL2NqhKtzo26smxTkarPUA,158728 +googleapiclient/discovery_cache/documents/tasks.v1.json,sha256=aMN5ZbCVhnMJx6cI_dvd-JNja954CwOlNfOH1wPE9vE,23620 +googleapiclient/discovery_cache/documents/testing.v1.json,sha256=UEqwrgm6mE14YXfaCKLb-EYaWp7wnPNkvYVQ7qVpP5Y,97369 +googleapiclient/discovery_cache/documents/texttospeech.v1.json,sha256=Z_1HgWjol0a4Q4c2RV4MvffmlEexJEaBsmXuPXHM_u8,29279 +googleapiclient/discovery_cache/documents/texttospeech.v1beta1.json,sha256=wNU7Kd-puVZw79pX3qPE_wVcogWZGWCJCpHx6pjHqIA,28118 +googleapiclient/discovery_cache/documents/toolresults.v1beta3.json,sha256=txzCTQaEl_0JhlHqxcsrKwyhkSlutnqmwzqNHm6bMWc,129592 +googleapiclient/discovery_cache/documents/tpu.v1.json,sha256=d4MxwMXoOQbDTE0VJ7VXWDL5tWp9j8ihVIf9fe_ff4I,32402 +googleapiclient/discovery_cache/documents/tpu.v1alpha1.json,sha256=E_1HljMKvrOK6uEENR-WSIBUnYOFtQZOipzYOUp9E5w,32817 +googleapiclient/discovery_cache/documents/tpu.v2.json,sha256=egFPh5wxG9-Fiu7QHoKuDlx9C7a7Xk0iC67lSeR5hTo,57594 +googleapiclient/discovery_cache/documents/tpu.v2alpha1.json,sha256=gx2tsbSJ6JIi_K7uxM5gBP_3ZXX7CArqG35BoqbeoYc,69298 +googleapiclient/discovery_cache/documents/trafficdirector.v2.json,sha256=Mwr5Rl2tgkRXEwvkVxuYeYBMR1TlkznDoMZvp4TobFQ,32631 +googleapiclient/discovery_cache/documents/trafficdirector.v3.json,sha256=G1MIfP1pfzghRK_XAo2dOfwUyW-Erig3eUJzZ5whT_w,51784 +googleapiclient/discovery_cache/documents/transcoder.v1.json,sha256=t43xsDFWOeUM9NHitU5ml31GXC3W7uWfei4YKTW8g6Q,68273 +googleapiclient/discovery_cache/documents/transcoder.v1beta1.json,sha256=nj-9u_qqRm_1H3tlaTpWZ2AEkXlgI6uIzwTqj7DZQYg,60514 +googleapiclient/discovery_cache/documents/translate.v2.json,sha256=uIVhWVyniBow5R6_BxTdei59xpeUcu2hPy_fLyX8Jig,11984 +googleapiclient/discovery_cache/documents/translate.v3.json,sha256=qZ6w_xQD6n04iuKmlI0eFDGtWLYREc7aGWeYmYPeSB0,119777 +googleapiclient/discovery_cache/documents/translate.v3beta1.json,sha256=3JskOUIdMmdpZX9neNh6amXt0BNmaMOfqO-_WBrfOp0,69036 +googleapiclient/discovery_cache/documents/travelimpactmodel.v1.json,sha256=ce2Xwy6PaIY3JXayq5F-4W-RRE_J9VGQu4-BgcV-_bY,12773 +googleapiclient/discovery_cache/documents/vault.v1.json,sha256=bLGTfmbmH9MOJ1j-1eoMqE6Aw7Q5-sQkcgfLoSrAmc8,77743 +googleapiclient/discovery_cache/documents/vectortile.v1.json,sha256=ox05W0ZLG7Yn-6uUQOP3yeXgibQfaQ6tqA6iv865DQg,47652 +googleapiclient/discovery_cache/documents/verifiedaccess.v1.json,sha256=ZkV9tEhH50MT-olunVV3JgrrUGBAOEjvqGlYD4bEaOg,6762 +googleapiclient/discovery_cache/documents/verifiedaccess.v2.json,sha256=0lDFzVooC54YvXSBhhBtzOTV08KKRa9K0soHeuBxqGk,20018 +googleapiclient/discovery_cache/documents/versionhistory.v1.json,sha256=bX1p4jg1aH-GQsQ9Ohk9yabe8NclxmJY40dxNROPSNI,17231 +googleapiclient/discovery_cache/documents/videointelligence.v1.json,sha256=Wb0JQ8_hJLlHOaKcxcIl0pSwUYs4qHhdVhRazJ0LyfE,182086 +googleapiclient/discovery_cache/documents/videointelligence.v1beta2.json,sha256=gaUiGEavpK9QMmwUkdSM7Iz5GMa8L1ViZDJmYqwZcmA,174248 +googleapiclient/discovery_cache/documents/videointelligence.v1p1beta1.json,sha256=0R6RNP1xN6q3tsHYe39_5cPguY-wijN6KjXiWjy1Jps,174324 +googleapiclient/discovery_cache/documents/videointelligence.v1p2beta1.json,sha256=5-3eGILSg1an9WHYuRREidRHQw_sVfAtXtpYN9F5yFI,174324 +googleapiclient/discovery_cache/documents/videointelligence.v1p3beta1.json,sha256=0UNQ0rT7ETr3OcE32qqIcNTZx_mPg5YFzTBx0QdsTLU,174375 +googleapiclient/discovery_cache/documents/vision.v1.json,sha256=h4oQU338yEcP8F9Ux5L9GRuUklohw0-BwS_nrzxbeLI,313435 +googleapiclient/discovery_cache/documents/vision.v1p1beta1.json,sha256=WLUhg3ah5PTFA_cV0gc1tuVy_mcwhTE7muurC0mKHeM,278159 +googleapiclient/discovery_cache/documents/vision.v1p2beta1.json,sha256=FRMYZPzEEih3EmJB48C0S0BaWaF8qy2JRvG58QC2gt8,278159 +googleapiclient/discovery_cache/documents/vmmigration.v1.json,sha256=aGPYYWJPmOt4qPS1lWyBJ4zNjZW60mSrxnD9WKZ0dFo,189574 +googleapiclient/discovery_cache/documents/vmmigration.v1alpha1.json,sha256=6E7YCl3GaaeS07yu8blstXPcZQ4-sCvkVt0gvtz9qmI,197189 +googleapiclient/discovery_cache/documents/vmwareengine.v1.json,sha256=9oNgyjRKCjNQa9ASjXxIVopIYvk115qyRvO9lCbbxqU,282049 +googleapiclient/discovery_cache/documents/vpcaccess.v1.json,sha256=0xLMLJ6JKIzey6zikIs1z_OIwYo25ylh0h_Oi3oBr54,21403 +googleapiclient/discovery_cache/documents/vpcaccess.v1beta1.json,sha256=8pFTdBK9Pn5sun_O8Wg6FJdPEg7f0cXt2OW0nJEJv70,21802 +googleapiclient/discovery_cache/documents/walletobjects.v1.json,sha256=cxUtoublK8zEq0_MFbOW2sRpI5qji_UpdtVZh6ZFq0g,355331 +googleapiclient/discovery_cache/documents/webfonts.v1.json,sha256=3Dih30_RQmnDPNqGXpfOKPHzak-iycUG9ZQZ4XwZcXo,6487 +googleapiclient/discovery_cache/documents/webmasters.v3.json,sha256=TOTCcpZyUk-dbmnjFVFoQam0hq2wFQg2UV9x-4fuVLY,20097 +googleapiclient/discovery_cache/documents/webrisk.v1.json,sha256=so8K_q7m91psDyyd3aZ_7fKz3CqxLChoz2_El0Pbaig,26588 +googleapiclient/discovery_cache/documents/websecurityscanner.v1.json,sha256=TNLC26NywAM_aK_DpxvkX01hCc7ImJ4sGKE6E8-0JAU,44775 +googleapiclient/discovery_cache/documents/websecurityscanner.v1alpha.json,sha256=QDkWVUfvc0d8Bw95U-_IKqyD3aJ1xXcIcsun53gHdaU,36660 +googleapiclient/discovery_cache/documents/websecurityscanner.v1beta.json,sha256=Cy-vHk51aVECUYd1QFrnow39K0KwVF_RVD9qPdUS9l8,42878 +googleapiclient/discovery_cache/documents/workflowexecutions.v1.json,sha256=ujXLrXbRGfsVWUuU5_3IqX6aM_HgwjWwo6MNMMR_tpE,39175 +googleapiclient/discovery_cache/documents/workflowexecutions.v1beta.json,sha256=tERDKKmiGTK-l3wOrCAhVaA1SjA9d2Wp2fcbqaScb4E,14318 +googleapiclient/discovery_cache/documents/workflows.v1.json,sha256=ojBWVt2y4JKlS6eH4ZjSmmTk8vW5Npq0LEpKJj0b6Rk,28821 +googleapiclient/discovery_cache/documents/workflows.v1beta.json,sha256=dUndWb1xhicFE3Ku6WHE7zx1s1Qe87U6Kh0GcUuAIyQ,22686 +googleapiclient/discovery_cache/documents/workloadmanager.v1.json,sha256=YDgvt7ud7IAqK8uAjNqMIfMrfekRqFMKLuWorDu2iyk,94119 +googleapiclient/discovery_cache/documents/workspaceevents.v1.json,sha256=D4nxuL3wHzugmga7Qht5u8QmeCkWZNfwN4Y6FslQA1Y,31510 +googleapiclient/discovery_cache/documents/workstations.v1.json,sha256=qv0YSyJ4J8qi7Abn8E98AJ4Xwp_XOXOgMn6VoHGEsXU,106551 +googleapiclient/discovery_cache/documents/workstations.v1beta.json,sha256=TZ1bz1_0cCyFgFiLxH-m-hvpYG-uRDHfCdiqV0MJhYU,106291 +googleapiclient/discovery_cache/documents/youtube.v3.json,sha256=ZX2ajUc5GfASs16aZP_LfneXUXCJkWEIz0MunTBQ0Ao,374965 +googleapiclient/discovery_cache/documents/youtubeAnalytics.v1.json,sha256=KLPoKHO_XT4-LyIZjwSGh44f_htMwjePD2PXR8MH-YY,3220 +googleapiclient/discovery_cache/documents/youtubeAnalytics.v2.json,sha256=Ixl98t7bVU4LpG2rai6RgzSeW-TUmk4abOVGzzttGKQ,28888 +googleapiclient/discovery_cache/documents/youtubereporting.v1.json,sha256=fez-pYUk5gzTFG4W4mPJ7crQV1F1msk1Zdxf2DzpLl0,23094 +googleapiclient/discovery_cache/file_cache.py,sha256=sim3Mg4HgRYo3vX75jvcKy_aV568EvIrtBfvfbw-044,4774 +googleapiclient/errors.py,sha256=9h3uimcMcczBHZJFWAX_YDABzJeJugWB0jmj11rp-LI,5460 +googleapiclient/http.py,sha256=ITE51oqDBqN1-AA5D-Tnlj3egGc_5O0V5xSzBw3UTKI,68241 +googleapiclient/mimeparse.py,sha256=wwouQMCjppTocJtiQhkkTa27kocYwlFRALL2z11Xo1Y,6530 +googleapiclient/model.py,sha256=NQDO1GhOGNVCJlSSCLOecdA11yf8RDXfSLFxYb3R7EE,14085 +googleapiclient/sample_tools.py,sha256=hDBLJNwLluN6AGhaBR-3GXWDrOwRNPvXyseLOyz9l30,4315 +googleapiclient/schema.py,sha256=rR3u8WPQ_V8a7GCUsNuvtf6GxzwuMO0HaqsTBp3tnyM,10414 +googleapiclient/version.py,sha256=J-oEmlC-CMeFp0dObv8Ffabt0e3TCr39Tkvw899PAaE,599 diff --git a/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f907e7e175c8bc3cc7226dbe019836a82cefb1ea --- /dev/null +++ b/python_embeded/Lib/site-packages/google_api_python_client-2.174.0.dist-info/top_level.txt @@ -0,0 +1,3 @@ +apiclient +googleapiclient +googleapiclient/discovery_cache diff --git a/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/INSTALLER b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/LICENSE b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/METADATA b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..45a2da4278422c06e9b4c2e7bb9008256b7e055c --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/METADATA @@ -0,0 +1,167 @@ +Metadata-Version: 2.1 +Name: google-auth +Version: 2.40.3 +Summary: Google Authentication Library +Home-page: https://github.com/googleapis/google-auth-library-python +Author: Google Cloud Platform +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google auth oauth client +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.7 +License-File: LICENSE +Requires-Dist: cachetools<6.0,>=2.0.0 +Requires-Dist: pyasn1-modules>=0.2.1 +Requires-Dist: rsa<5,>=3.1.4 +Provides-Extra: aiohttp +Requires-Dist: aiohttp<4.0.0,>=3.6.2; extra == "aiohttp" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "aiohttp" +Provides-Extra: enterprise_cert +Requires-Dist: cryptography; extra == "enterprise-cert" +Requires-Dist: pyopenssl; extra == "enterprise-cert" +Provides-Extra: pyjwt +Requires-Dist: pyjwt>=2.0; extra == "pyjwt" +Requires-Dist: cryptography>=38.0.3; extra == "pyjwt" +Requires-Dist: cryptography<39.0.0; python_version < "3.8" and extra == "pyjwt" +Provides-Extra: pyopenssl +Requires-Dist: pyopenssl>=20.0.0; extra == "pyopenssl" +Requires-Dist: cryptography>=38.0.3; extra == "pyopenssl" +Requires-Dist: cryptography<39.0.0; python_version < "3.8" and extra == "pyopenssl" +Provides-Extra: reauth +Requires-Dist: pyu2f>=0.1.5; extra == "reauth" +Provides-Extra: requests +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "requests" +Provides-Extra: testing +Requires-Dist: grpcio; extra == "testing" +Requires-Dist: flask; extra == "testing" +Requires-Dist: freezegun; extra == "testing" +Requires-Dist: mock; extra == "testing" +Requires-Dist: oauth2client; extra == "testing" +Requires-Dist: pyjwt>=2.0; extra == "testing" +Requires-Dist: cryptography>=38.0.3; extra == "testing" +Requires-Dist: pytest; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-localserver; extra == "testing" +Requires-Dist: pyopenssl>=20.0.0; extra == "testing" +Requires-Dist: pyu2f>=0.1.5; extra == "testing" +Requires-Dist: responses; extra == "testing" +Requires-Dist: urllib3; extra == "testing" +Requires-Dist: packaging; extra == "testing" +Requires-Dist: aiohttp<4.0.0,>=3.6.2; extra == "testing" +Requires-Dist: requests<3.0.0,>=2.20.0; extra == "testing" +Requires-Dist: aioresponses; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pyopenssl<24.3.0; extra == "testing" +Requires-Dist: aiohttp<3.10.0; extra == "testing" +Requires-Dist: cryptography<39.0.0; python_version < "3.8" and extra == "testing" +Provides-Extra: urllib3 +Requires-Dist: urllib3; extra == "urllib3" +Requires-Dist: packaging; extra == "urllib3" + +Google Auth Python Library +========================== + +|pypi| + +This library simplifies using Google's various server-to-server authentication +mechanisms to access Google APIs. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-auth.svg + :target: https://pypi.python.org/pypi/google-auth + +Installing +---------- + +You can install using `pip`_:: + + $ pip install google-auth + +.. _pip: https://pip.pypa.io/en/stable/ + +For more information on setting up your Python development environment, please refer to `Python Development Environment Setup Guide`_ for Google Cloud Platform. + +.. _`Python Development Environment Setup Guide`: https://cloud.google.com/python/docs/setup + +Extras +------ + +google-auth has few extras that you can install. For example:: + + $ pip install google-auth[pyopenssl] + +Note that the extras pyopenssl and enterprise_cert should not be used together because they use conflicting versions of `cryptography`_. + +.. _`cryptography`: https://cryptography.io/en/latest/ + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Python >= 3.7 + +**NOTE**: +Python 3.7 was marked as `unsupported`_ by the python community in June 2023. +We recommend that all developers upgrade to Python 3.8 and newer as soon as +they can. Support for Python 3.7 will be removed from this library after +January 1 2024. Previous releases that support Python 3.7 will continue to be available +for download, but releases after January 1 2024 will only target Python 3.8 and +newer. + +.. _unsupported: https://devguide.python.org/versions/#unsupported-versions + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +- Python == 2.7: The last version of this library with support for Python 2.7 + was `google.auth == 1.34.0`. + +- Python 3.5: The last version of this library with support for Python 3.5 + was `google.auth == 1.23.0`. + +- Python 3.6: The last version of this library with support for Python 3.6 + was `google.auth == 2.22.0`. + +Documentation +------------- + +Google Auth Python Library has usage and reference documentation at https://googleapis.dev/python/google-auth/latest/index.html. + +Current Maintainers +------------------- +- googleapis-auth@google.com + +Authors +------- + +- `@theacodes `_ (Thea Flowers) +- `@dhermes `_ (Danny Hermes) +- `@lukesneeringer `_ (Luke Sneeringer) +- `@busunkim96 `_ (Bu Sun Kim) + +Contributing +------------ + +Contributions to this library are always welcome and highly encouraged. + +See `CONTRIBUTING.rst`_ for more information on how to get started. + +.. _CONTRIBUTING.rst: https://github.com/googleapis/google-auth-library-python/blob/main/CONTRIBUTING.rst + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/googleapis/google-auth-library-python/blob/main/LICENSE diff --git a/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/RECORD b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f02544fba3ecfd67b42fba7219722902a999ef76 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/RECORD @@ -0,0 +1,152 @@ +google/auth/__init__.py,sha256=wg5MWwRk8nfJFMmUMU2gLirrPdGe9NMwqLkdSwdFwE8,1639 +google/auth/__pycache__/__init__.cpython-312.pyc,, +google/auth/__pycache__/_cloud_sdk.cpython-312.pyc,, +google/auth/__pycache__/_credentials_async.cpython-312.pyc,, +google/auth/__pycache__/_credentials_base.cpython-312.pyc,, +google/auth/__pycache__/_default.cpython-312.pyc,, +google/auth/__pycache__/_default_async.cpython-312.pyc,, +google/auth/__pycache__/_exponential_backoff.cpython-312.pyc,, +google/auth/__pycache__/_helpers.cpython-312.pyc,, +google/auth/__pycache__/_jwt_async.cpython-312.pyc,, +google/auth/__pycache__/_oauth2client.cpython-312.pyc,, +google/auth/__pycache__/_refresh_worker.cpython-312.pyc,, +google/auth/__pycache__/_service_account_info.cpython-312.pyc,, +google/auth/__pycache__/api_key.cpython-312.pyc,, +google/auth/__pycache__/app_engine.cpython-312.pyc,, +google/auth/__pycache__/aws.cpython-312.pyc,, +google/auth/__pycache__/credentials.cpython-312.pyc,, +google/auth/__pycache__/downscoped.cpython-312.pyc,, +google/auth/__pycache__/environment_vars.cpython-312.pyc,, +google/auth/__pycache__/exceptions.cpython-312.pyc,, +google/auth/__pycache__/external_account.cpython-312.pyc,, +google/auth/__pycache__/external_account_authorized_user.cpython-312.pyc,, +google/auth/__pycache__/iam.cpython-312.pyc,, +google/auth/__pycache__/identity_pool.cpython-312.pyc,, +google/auth/__pycache__/impersonated_credentials.cpython-312.pyc,, +google/auth/__pycache__/jwt.cpython-312.pyc,, +google/auth/__pycache__/metrics.cpython-312.pyc,, +google/auth/__pycache__/pluggable.cpython-312.pyc,, +google/auth/__pycache__/version.cpython-312.pyc,, +google/auth/_cloud_sdk.py,sha256=u7tbE3KdHBCzZK8ka47xG3CHHtF0DhFDjmPSgz8lwXg,5212 +google/auth/_credentials_async.py,sha256=bHB28wMULOIEMmYqKEOU06A4co7uIXPcnfVC_TaA6KY,6802 +google/auth/_credentials_base.py,sha256=KxdCZyoFyvrfWhJbNnuYkpUhxs0bmbxYvcH8-xp5hUs,2692 +google/auth/_default.py,sha256=Nw4JKiNrObBbRSki2ov99WTTTA10iVyJlBLeuQE_V2s,28687 +google/auth/_default_async.py,sha256=r4bFozWfioQa4lIEC-psuRsLiVhnJbuW-uQ0daj7s3Q,11575 +google/auth/_exponential_backoff.py,sha256=qxA9ek80rBkoARx0Egl2b1MlYU0D-pQNVqgCmUh-lgU,5372 +google/auth/_helpers.py,sha256=1j2IZY5pltpQ3a0JsKM_kF_re7Xv1Fcaqrl-NJTKulo,16584 +google/auth/_jwt_async.py,sha256=5mGab5CkdnBMkQkS4mtNkwFkktp1jBw6G1sYQk8bYKY,5972 +google/auth/_oauth2client.py,sha256=hPxcl_8q6Oxr0hOHPUWaWObxI85Pv-0q6kZhRUrT5oY,5855 +google/auth/_refresh_worker.py,sha256=7apJkFsD9oL1yz1K7O8v-YN3f3TdNBiJdd7_Wmq6zpE,3375 +google/auth/_service_account_info.py,sha256=KGruc_OxS7O7_EADD4JEIjjz_-5Xa1_rlgk1t0p1nvk,2816 +google/auth/aio/__init__.py,sha256=e3ToAxXNHhqJLBgW8B66650xdqrTCZDLcwP2p5DhCPM,869 +google/auth/aio/__pycache__/__init__.cpython-312.pyc,, +google/auth/aio/__pycache__/_helpers.cpython-312.pyc,, +google/auth/aio/__pycache__/credentials.cpython-312.pyc,, +google/auth/aio/_helpers.py,sha256=glCa_-GYxDrcPBFt80LBhMz_V7vLjxAEEWfOZB8lwT0,2334 +google/auth/aio/credentials.py,sha256=lXY0_SJ9c36Mzp47fN4a8JT5HfNzFQtIIwsZEwzoDR4,5273 +google/auth/aio/transport/__init__.py,sha256=8dQWHpube1IeWw02q6AvMRTM5V_2iN4y3UMLenbmUUQ,4692 +google/auth/aio/transport/__pycache__/__init__.cpython-312.pyc,, +google/auth/aio/transport/__pycache__/aiohttp.cpython-312.pyc,, +google/auth/aio/transport/__pycache__/sessions.cpython-312.pyc,, +google/auth/aio/transport/aiohttp.py,sha256=sg3bdyCsoJ0N0v7Ww8qoJFr0qcF6TKhEmNw5dRb6R9I,6979 +google/auth/aio/transport/sessions.py,sha256=RcRHfkeo_ppEY1o8ts8aJqw76y54I8D0P8QT7yFq4aI,10388 +google/auth/api_key.py,sha256=PeieTYceHJIFCo0zQo1EA9NEDL_Ie6S78qmD-6Ig17s,2583 +google/auth/app_engine.py,sha256=LuEaoWM1UwcIUJ6OrLza0tTpqJBXbtzZ3XjN0C-6Wvk,6121 +google/auth/aws.py,sha256=2V5NLhboorkPLLwnA87VuyH9imruake6qhyHKV_rVYM,34568 +google/auth/compute_engine/__init__.py,sha256=BqeTka-oyHFATkys3SGKRlOyWQ8mVV0vVaP2hOwV4Qw,910 +google/auth/compute_engine/__pycache__/__init__.cpython-312.pyc,, +google/auth/compute_engine/__pycache__/_metadata.cpython-312.pyc,, +google/auth/compute_engine/__pycache__/credentials.cpython-312.pyc,, +google/auth/compute_engine/_metadata.py,sha256=IWloMOeSYNcJ40mfWstGx19kUR4_FK2pOVhRiT6d6zg,12860 +google/auth/compute_engine/credentials.py,sha256=5jGYgrb0fjc0jb_bcOTHr4PxZ2A-dPRzgAgFu0Ky8BA,19076 +google/auth/credentials.py,sha256=l0g0iATMCpJnJXU5aE6YD850yBnZpshdYyDrYzhmE40,18700 +google/auth/crypt/__init__.py,sha256=xxBMOPuzD-XOxPvzkleLa2oj4u-9FSjnFmUN3PBk00s,3324 +google/auth/crypt/__pycache__/__init__.cpython-312.pyc,, +google/auth/crypt/__pycache__/_cryptography_rsa.cpython-312.pyc,, +google/auth/crypt/__pycache__/_helpers.cpython-312.pyc,, +google/auth/crypt/__pycache__/_python_rsa.cpython-312.pyc,, +google/auth/crypt/__pycache__/base.cpython-312.pyc,, +google/auth/crypt/__pycache__/es256.cpython-312.pyc,, +google/auth/crypt/__pycache__/rsa.cpython-312.pyc,, +google/auth/crypt/_cryptography_rsa.py,sha256=o2QTRkfDRLtEBiq-fbpbTWypvxaxUDwzlx2NpXG9o0w,5158 +google/auth/crypt/_helpers.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google/auth/crypt/_python_rsa.py,sha256=L0kgvPXVdEGhajzxLRIgdk2T9rY0nlThrSlSz8Hc8XY,6123 +google/auth/crypt/base.py,sha256=3CJrnQsppR6h-WnTRqSrt1hPEQVkHcwNIVJ_B5M00hY,4190 +google/auth/crypt/es256.py,sha256=hXyeia3g6_TZf-UYdZVzFKgbPrLlgSuR1mMvYKSYqbg,6251 +google/auth/crypt/rsa.py,sha256=QI17aKQsX3gdbJkBef-zsm-X_YBjBollCaoA65Am-WI,1109 +google/auth/downscoped.py,sha256=KmmC8lbBWUFUsIYt1VpcbTXs3yYJYXteH19qdZQgobA,21793 +google/auth/environment_vars.py,sha256=ML9aFh5gwRStBDjn8BQSQHyWsA-OcMn-RB5FRMM8qOw,3297 +google/auth/exceptions.py,sha256=8oEeB_1UirJIyBoglQRpCFjCOcxcTaLr6EpBrrxjeEs,3193 +google/auth/external_account.py,sha256=v-Qln5KsbXYlO2xPlIxeGMBY5iA4Atj2cP-KgbF2CpY,25977 +google/auth/external_account_authorized_user.py,sha256=-garTidaTqA8XNOPdBxJl6tfx-ub_-dr7WPVKEI2eAs,13987 +google/auth/iam.py,sha256=DQcJ127yejPqQa20jwzrGfiWffiWioAYkxZI4cQAUm8,4674 +google/auth/identity_pool.py,sha256=JGMRr4edwIOybi969upW-n9g6u3bPvjy5oYt3bkzVoI,22554 +google/auth/impersonated_credentials.py,sha256=E5dkf_2P8-q476IaxIqzXRHZhJTEU0sYsBTB9bAPq3s,24971 +google/auth/jwt.py,sha256=1m_arp5x-4I5UTDaK9y50PSlKnUhnSKFyJW95k3-7cQ,31096 +google/auth/metrics.py,sha256=wx3m95QQCF885wYvPL4T01CHOdCBN5JvFCtbOakd98Q,5614 +google/auth/pluggable.py,sha256=peGQ4izmkZ3Fna7fjhBhQVXjtDBcHK12uEAteMyJ8s0,17322 +google/auth/py.typed,sha256=l05_LTgi3oy-einKBrw66s6aavgzG2o-SekKPOY3ayM,74 +google/auth/transport/__init__.py,sha256=vTdWUDBCXWF6wk3Xzu7L5I1lbtGYTxONi-IKYOmDdFM,3654 +google/auth/transport/__pycache__/__init__.cpython-312.pyc,, +google/auth/transport/__pycache__/_aiohttp_requests.cpython-312.pyc,, +google/auth/transport/__pycache__/_custom_tls_signer.cpython-312.pyc,, +google/auth/transport/__pycache__/_http_client.cpython-312.pyc,, +google/auth/transport/__pycache__/_mtls_helper.cpython-312.pyc,, +google/auth/transport/__pycache__/_requests_base.cpython-312.pyc,, +google/auth/transport/__pycache__/grpc.cpython-312.pyc,, +google/auth/transport/__pycache__/mtls.cpython-312.pyc,, +google/auth/transport/__pycache__/requests.cpython-312.pyc,, +google/auth/transport/__pycache__/urllib3.cpython-312.pyc,, +google/auth/transport/_aiohttp_requests.py,sha256=DdtN_5zXWm7ewsvejOfMfa9_KSYXFX8upLdGL_qKDCI,14820 +google/auth/transport/_custom_tls_signer.py,sha256=ilLlKFNognkvOWcnlYAWmUIUo9YhSrTSAKLa05zQ8Do,9989 +google/auth/transport/_http_client.py,sha256=_xiN4rF9SMT0cHwzvj0jRRXkkHxGG2IyOBOHxB-I1Ag,3798 +google/auth/transport/_mtls_helper.py,sha256=rhJ-QDEWeoiLGguwtMjruy6ObR89oqwtZ382sW1g3uM,14739 +google/auth/transport/_requests_base.py,sha256=4y0tTMR_hPGeAmBSyCU6_moh99ZxJZ4CF79E2s-t7TA,1657 +google/auth/transport/grpc.py,sha256=o6wDBMWKlTybwsE8CUdEcoEA2t_vdjRvQTGU9vcJPcc,13931 +google/auth/transport/mtls.py,sha256=C1Ox7fB0DSEdNkIJ7q5ofrQ-_I_cj1JOJ8o5_Zzgb24,3968 +google/auth/transport/requests.py,sha256=V2hL_RpEj2mVjy3-8iYTvAhJnzm5JuMPGIGxOwvcbaE,22513 +google/auth/transport/urllib3.py,sha256=kRH_Rd_4KuCcKKoZ_b92c-6d42R5CGeH5EuWtiYOhjM,16491 +google/auth/version.py,sha256=nnzHzJaLYzj7zp5qHqgHVhV4FwiPu5dmAVmCvKWVTek,598 +google/oauth2/__init__.py,sha256=IdFKxhIzlqNIalPgeB2P5hP6KkoxcpNk61hp7P2B85w,1196 +google/oauth2/__pycache__/__init__.cpython-312.pyc,, +google/oauth2/__pycache__/_client.cpython-312.pyc,, +google/oauth2/__pycache__/_client_async.cpython-312.pyc,, +google/oauth2/__pycache__/_credentials_async.cpython-312.pyc,, +google/oauth2/__pycache__/_id_token_async.cpython-312.pyc,, +google/oauth2/__pycache__/_reauth_async.cpython-312.pyc,, +google/oauth2/__pycache__/_service_account_async.cpython-312.pyc,, +google/oauth2/__pycache__/challenges.cpython-312.pyc,, +google/oauth2/__pycache__/credentials.cpython-312.pyc,, +google/oauth2/__pycache__/gdch_credentials.cpython-312.pyc,, +google/oauth2/__pycache__/id_token.cpython-312.pyc,, +google/oauth2/__pycache__/reauth.cpython-312.pyc,, +google/oauth2/__pycache__/service_account.cpython-312.pyc,, +google/oauth2/__pycache__/sts.cpython-312.pyc,, +google/oauth2/__pycache__/utils.cpython-312.pyc,, +google/oauth2/__pycache__/webauthn_handler.cpython-312.pyc,, +google/oauth2/__pycache__/webauthn_handler_factory.cpython-312.pyc,, +google/oauth2/__pycache__/webauthn_types.cpython-312.pyc,, +google/oauth2/_client.py,sha256=XOtqZf3J9U5zW9x5v6zPSKeF_YlRNdYlqfzOZPepxdc,17338 +google/oauth2/_client_async.py,sha256=gBB74HOw_UVT6i-84T4N_39YnyajYwP5Ih1Kmtsjeu8,10129 +google/oauth2/_credentials_async.py,sha256=hUrucQkcYuYlyCdHMci8tzaVncnjQlFc2sAfNu5Dt8k,4474 +google/oauth2/_id_token_async.py,sha256=o_DViJoWMGlL3zwTbW2unGDBfY569D_VMB4l7bx-Qpw,10115 +google/oauth2/_reauth_async.py,sha256=C6k3f4T0aoVWItl8shYjOl5ngaoTJw3zKVhqHAeBXU0,11696 +google/oauth2/_service_account_async.py,sha256=5-HBGWoHhbWpCRbd34YiopQepEsEf8gSiuMlSm5hN84,5131 +google/oauth2/challenges.py,sha256=__yS2EcWXlgdLLP4inbk0QjJuyXnztpT9r2DCuXvieI,10404 +google/oauth2/credentials.py,sha256=AqPdW8ymp1EnmiTgwyLdRxjaj2kISjHPw4Yh0JZUleI,24913 +google/oauth2/gdch_credentials.py,sha256=CY6iPnPuc2OCIe1Zujwg1Mu9QSl1iGJqGOy6TkUleHw,9007 +google/oauth2/id_token.py,sha256=G41ugqrEkj0VqP3hAFLH6IzmFqPZv81WkU6_lviKb4Q,13497 +google/oauth2/py.typed,sha256=I0muXRRdbdpJoZ_VyheisiTTYcmjTAitQpNvuuh6fMw,76 +google/oauth2/reauth.py,sha256=p9ybxvFyaSMM85jL2veKMM-DVb4TtrDVPNqsLeDPmyk,12845 +google/oauth2/service_account.py,sha256=PyKtS9QfflVfIgdyRju1I1VFr8V3A57IGzxUSAYGmgA,32232 +google/oauth2/sts.py,sha256=GjpFEvByl3EzyGt2v1kev6rvP7_uSQ3eTlpBK9vUhSc,6699 +google/oauth2/utils.py,sha256=4crAdpKbDtobpQfXJc3uF6Zm6F3IzffvRSo-9h_515w,6315 +google/oauth2/webauthn_handler.py,sha256=6hYiSDIFXlLwghsYf13ceDiOWdLYn6Dh7-YwSqTbLaA,2743 +google/oauth2/webauthn_handler_factory.py,sha256=soE5cokZ3pLNbBo1HC6F1N-N-I-ir-DGlD0trGPCpBs,429 +google/oauth2/webauthn_types.py,sha256=IHdqUe-EWOU-CmyLnHLniqc7vGHZ8HpavB0dcjn7Zl8,5386 +google_auth-2.40.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_auth-2.40.3.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +google_auth-2.40.3.dist-info/METADATA,sha256=ZtXNUVjkBEE6jjbKrauFnfn_SNpLHGH12AAzeLXYhTk,6203 +google_auth-2.40.3.dist-info/RECORD,, +google_auth-2.40.3.dist-info/WHEEL,sha256=OpXWERl2xLPRHTvd2ZXo_iluPEQd8uSbYkJ53NAER_Y,109 +google_auth-2.40.3.dist-info/top_level.txt,sha256=BWmDiI8eoKfseZ5-MI2AW66GLJLNH4Lz23AXXTrIlyQ,23 diff --git a/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/WHEEL b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ee810efb31c37815a70827942976bfcba5b5d2bc --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.3.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/top_level.txt b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..64f26a32e6269f22ba603fede491e460b08a91d8 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth-2.40.3.dist-info/top_level.txt @@ -0,0 +1,3 @@ +google +scripts +testing diff --git a/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/METADATA b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..cdf15e5479825f7e03eefd9b8c9d18cf05e3f247 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/METADATA @@ -0,0 +1,62 @@ +Metadata-Version: 2.1 +Name: google-auth-httplib2 +Version: 0.2.0 +Summary: Google Authentication Library: httplib2 transport +Home-page: https://github.com/GoogleCloudPlatform/google-auth-library-python-httplib2 +Author: Google Cloud Platform +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Keywords: google auth oauth client +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet :: WWW/HTTP +License-File: LICENSE +Requires-Dist: google-auth +Requires-Dist: httplib2 >=0.19.0 + +``httplib2`` Transport for Google Auth +====================================== + +|pypi| + +This library provides an `httplib2`_ transport for `google-auth`_. + +.. note:: ``httplib`` has lots of problems such as lack of threadsafety + and insecure usage of TLS. Using it is highly discouraged. This + library is intended to help existing users of ``oauth2client`` migrate to + ``google-auth``. + +.. |pypi| image:: https://img.shields.io/pypi/v/google-auth-httplib2.svg + :target: https://pypi.python.org/pypi/google-auth-httplib2 + +.. _httplib2: https://github.com/httplib2/httplib2 +.. _google-auth: https://github.com/GoogleCloudPlatform/google-auth-library-python/ + +Installing +---------- + +You can install using `pip`_:: + + $ pip install google-auth-httplib2 + +.. _pip: https://pip.pypa.io/en/stable/ + +License +------- + +Apache 2.0 - See `the LICENSE`_ for more information. + +.. _the LICENSE: https://github.com/GoogleCloudPlatform/google-auth-library-python/blob/main/LICENSE diff --git a/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/RECORD b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..82998fcbb48b2aca7d2d1d6fd2795c3804fcc6f9 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/RECORD @@ -0,0 +1,8 @@ +__pycache__/google_auth_httplib2.cpython-312.pyc,, +google_auth_httplib2-0.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_auth_httplib2-0.2.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +google_auth_httplib2-0.2.0.dist-info/METADATA,sha256=KbbX6r2o-hWv_6Mr3PkYxa96q59OBXu2mF9WJ8MMlJk,2179 +google_auth_httplib2-0.2.0.dist-info/RECORD,, +google_auth_httplib2-0.2.0.dist-info/WHEEL,sha256=P2T-6epvtXQ2cBOE_U1K4_noqlJFN3tj15djMgEu4NM,110 +google_auth_httplib2-0.2.0.dist-info/top_level.txt,sha256=xQr4X91CsNWr1mw3rrOH8mKnYLOW_Uhr5U7moYxkq4E,21 +google_auth_httplib2.py,sha256=Z-VdVWlB8Rcrwn4Q2MU9SHHJ5HZkPYHfDu8xHKsBeQI,10211 diff --git a/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f31e450fda2866f274547bb723d784248069898a --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.3) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f8b63c266a006ff9f89d5a998d7cb9e836bec45e --- /dev/null +++ b/python_embeded/Lib/site-packages/google_auth_httplib2-0.2.0.dist-info/top_level.txt @@ -0,0 +1 @@ +google_auth_httplib2 diff --git a/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/METADATA b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..61530f449ce239243119a2fd902344daff72573c --- /dev/null +++ b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/METADATA @@ -0,0 +1,1521 @@ +Metadata-Version: 2.4 +Name: google-genai +Version: 1.22.0 +Summary: GenAI Python SDK +Author-email: Google LLC +License: Apache-2.0 +Project-URL: Homepage, https://github.com/googleapis/python-genai +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Internet +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: anyio<5.0.0,>=4.8.0 +Requires-Dist: google-auth<3.0.0,>=2.14.1 +Requires-Dist: httpx<1.0.0,>=0.28.1 +Requires-Dist: pydantic<3.0.0,>=2.0.0 +Requires-Dist: requests<3.0.0,>=2.28.1 +Requires-Dist: tenacity<9.0.0,>=8.2.3 +Requires-Dist: websockets<15.1.0,>=13.0.0 +Requires-Dist: typing-extensions<5.0.0,>=4.11.0 +Provides-Extra: aiohttp +Requires-Dist: aiohttp<4.0.0; extra == "aiohttp" +Dynamic: license-file + +# Google Gen AI SDK + +[![PyPI version](https://img.shields.io/pypi/v/google-genai.svg)](https://pypi.org/project/google-genai/) +![Python support](https://img.shields.io/pypi/pyversions/google-genai) +[![PyPI - Downloads](https://img.shields.io/pypi/dw/google-genai)](https://pypistats.org/packages/google-genai) + +-------- +**Documentation:** https://googleapis.github.io/python-genai/ + +----- + +Google Gen AI Python SDK provides an interface for developers to integrate +Google's generative models into their Python applications. It supports the +[Gemini Developer API](https://ai.google.dev/gemini-api/docs) and +[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) +APIs. + +## Installation + +```sh +pip install google-genai +``` + +## Imports + +```python +from google import genai +from google.genai import types +``` + +## Create a client + +Please run one of the following code blocks to create a client for +different services ([Gemini Developer API](https://ai.google.dev/gemini-api/docs) or [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview)). + +```python +from google import genai + +# Only run this block for Gemini Developer API +client = genai.Client(api_key='GEMINI_API_KEY') +``` + +```python +from google import genai + +# Only run this block for Vertex AI API +client = genai.Client( + vertexai=True, project='your-project-id', location='us-central1' +) +``` + +**(Optional) Using environment variables:** + +You can create a client by configuring the necessary environment variables. +Configuration setup instructions depends on whether you're using the Gemini +Developer API or the Gemini API in Vertex AI. + +**Gemini Developer API:** Set `GOOGLE_API_KEY` as shown below: + +```bash +export GOOGLE_API_KEY='your-api-key' +``` + +**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`, +`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below: + +```bash +export GOOGLE_GENAI_USE_VERTEXAI=true +export GOOGLE_CLOUD_PROJECT='your-project-id' +export GOOGLE_CLOUD_LOCATION='us-central1' +``` + +```python +from google import genai + +client = genai.Client() +``` + +### API Selection + +By default, the SDK uses the beta API endpoints provided by Google to support +preview features in the APIs. The stable API endpoints can be selected by +setting the API version to `v1`. + +To set the API version use `http_options`. For example, to set the API version +to `v1` for Vertex AI: + +```python +from google import genai +from google.genai import types + +client = genai.Client( + vertexai=True, + project='your-project-id', + location='us-central1', + http_options=types.HttpOptions(api_version='v1') +) +``` + +To set the API version to `v1alpha` for the Gemini Developer API: + +```python +from google import genai +from google.genai import types + +client = genai.Client( + api_key='GEMINI_API_KEY', + http_options=types.HttpOptions(api_version='v1alpha') +) +``` + +### Faster async client option: Aiohttp + +By default we use httpx for both sync and async client implementations. In order +to have faster performance, you may install `google-genai[aiohttp]`. In Gen AI +SDK we configure `trust_env=True` to match with the default behavior of httpx. +Additional args of `aiohttp.ClientSession.request()` ([see _RequestOptions args](https://github.com/aio-libs/aiohttp/blob/v3.12.13/aiohttp/client.py#L170)) can be passed +through the following way: + +```python + +http_options = types.HttpOptions( + async_client_args={'cookies': ..., 'ssl': ...}, +) + +client=Client(..., http_options=http_options) +``` + +### Proxy + +Both httpx and aiohttp libraries use `urllib.request.getproxies` from +environment variables. Before client initialization, you may set proxy (and +optional SSL_CERT_FILE) by setting the environment variables: + + +```bash +export HTTPS_PROXY='http://username:password@proxy_uri:port' +export SSL_CERT_FILE='client.pem' +``` + +If you need `socks5` proxy, httpx [supports](https://www.python-httpx.org/advanced/proxies/#socks) `socks5` proxy if you pass it via +args to `httpx.Client()`. You may install `httpx[socks]` to use it. +Then, you can pass it through the following way: + +```python + +http_options = types.HttpOptions( + client_args={'proxy': 'socks5://user:pass@host:port'}, + async_client_args={'proxy': 'socks5://user:pass@host:port'},, +) + +client=Client(..., http_options=http_options) +``` + +## Types + +Parameter types can be specified as either dictionaries(`TypedDict`) or +[Pydantic Models](https://pydantic.readthedocs.io/en/stable/model.html). +Pydantic model types are available in the `types` module. + +## Models + +The `client.models` module exposes model inferencing and model getters. +See the 'Create a client' section above to initialize a client. + +### Generate Content + +#### with text content + +```python +response = client.models.generate_content( + model='gemini-2.0-flash-001', contents='Why is the sky blue?' +) +print(response.text) +``` + +#### with uploaded file (Gemini Developer API only) +download the file in console. + +```sh +!wget -q https://storage.googleapis.com/generativeai-downloads/data/a11.txt +``` + +python code. + +```python +file = client.files.upload(file='a11.txt') +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents=['Could you summarize this file?', file] +) +print(response.text) +``` + +#### How to structure `contents` argument for `generate_content` +The SDK always converts the inputs to the `contents` argument into +`list[types.Content]`. +The following shows some common ways to provide your inputs. + +##### Provide a `list[types.Content]` +This is the canonical way to provide contents, SDK will not do any conversion. + +##### Provide a `types.Content` instance + +```python +from google.genai import types + +contents = types.Content( + role='user', + parts=[types.Part.from_text(text='Why is the sky blue?')] +) +``` + +SDK converts this to + +```python +[ + types.Content( + role='user', + parts=[types.Part.from_text(text='Why is the sky blue?')] + ) +] +``` + +##### Provide a string + +```python +contents='Why is the sky blue?' +``` + +The SDK will assume this is a text part, and it converts this into the following: + +```python +[ + types.UserContent( + parts=[ + types.Part.from_text(text='Why is the sky blue?') + ] + ) +] +``` + +Where a `types.UserContent` is a subclass of `types.Content`, it sets the +`role` field to be `user`. + +##### Provide a list of string + +```python +contents=['Why is the sky blue?', 'Why is the cloud white?'] +``` + +The SDK assumes these are 2 text parts, it converts this into a single content, +like the following: + +```python +[ + types.UserContent( + parts=[ + types.Part.from_text(text='Why is the sky blue?'), + types.Part.from_text(text='Why is the cloud white?'), + ] + ) +] +``` + +Where a `types.UserContent` is a subclass of `types.Content`, the +`role` field in `types.UserContent` is fixed to be `user`. + +##### Provide a function call part + +```python +from google.genai import types + +contents = types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} +) +``` + +The SDK converts a function call part to a content with a `model` role: + +```python +[ + types.ModelContent( + parts=[ + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} + ) + ] + ) +] +``` + +Where a `types.ModelContent` is a subclass of `types.Content`, the +`role` field in `types.ModelContent` is fixed to be `model`. + +##### Provide a list of function call parts + +```python +from google.genai import types + +contents = [ + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} + ), + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'New York'} + ), +] +``` + +The SDK converts a list of function call parts to the a content with a `model` role: + +```python +[ + types.ModelContent( + parts=[ + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'Boston'} + ), + types.Part.from_function_call( + name='get_weather_by_location', + args={'location': 'New York'} + ) + ] + ) +] +``` + +Where a `types.ModelContent` is a subclass of `types.Content`, the +`role` field in `types.ModelContent` is fixed to be `model`. + +##### Provide a non function call part + +```python +from google.genai import types + +contents = types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', +) +``` + +The SDK converts all non function call parts into a content with a `user` role. + +```python +[ + types.UserContent(parts=[ + types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', + ) + ]) +] +``` + +##### Provide a list of non function call parts + +```python +from google.genai import types + +contents = [ + types.Part.from_text('What is this image about?'), + types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', + ) +] +``` + +The SDK will convert the list of parts into a content with a `user` role + +```python +[ + types.UserContent( + parts=[ + types.Part.from_text('What is this image about?'), + types.Part.from_uri( + file_uri: 'gs://generativeai-downloads/images/scones.jpg', + mime_type: 'image/jpeg', + ) + ] + ) +] +``` + +##### Mix types in contents + +You can also provide a list of `types.ContentUnion`. The SDK leaves items of +`types.Content` as is, it groups consecutive non function call parts into a +single `types.UserContent`, and it groups consecutive function call parts into +a single `types.ModelContent`. + +If you put a list within a list, the inner list can only contain +`types.PartUnion` items. The SDK will convert the inner list into a single +`types.UserContent`. + +### System Instructions and Other Configs + +The output of the model can be influenced by several optional settings +available in generate_content's config parameter. For example, increasing +`max_output_tokens` is essential for longer model responses. To make a model more +deterministic, lowering the `temperature` parameter reduces randomness, with +values near 0 minimizing variability. Capabilities and parameter defaults for +each model is shown in the +[Vertex AI docs](https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/2-5-flash) +and [Gemini API docs](https://ai.google.dev/gemini-api/docs/models) respectively. + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='high', + config=types.GenerateContentConfig( + system_instruction='I say high, you say low', + max_output_tokens=3, + temperature=0.3, + ), +) +print(response.text) +``` + +### Typed Config + +All API methods support Pydantic types for parameters as well as +dictionaries. You can get the type from `google.genai.types`. + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents=types.Part.from_text(text='Why is the sky blue?'), + config=types.GenerateContentConfig( + temperature=0, + top_p=0.95, + top_k=20, + candidate_count=1, + seed=5, + max_output_tokens=100, + stop_sequences=['STOP!'], + presence_penalty=0.0, + frequency_penalty=0.0, + ), +) + +print(response.text) +``` + +### List Base Models + +To retrieve tuned models, see [list tuned models](#list-tuned-models). + +```python +for model in client.models.list(): + print(model) +``` + +```python +pager = client.models.list(config={'page_size': 10}) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### List Base Models (Asynchronous) + +```python +async for job in await client.aio.models.list(): + print(job) +``` + +```python +async_pager = await client.aio.models.list(config={'page_size': 10}) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +### Safety Settings + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='Say something bad.', + config=types.GenerateContentConfig( + safety_settings=[ + types.SafetySetting( + category='HARM_CATEGORY_HATE_SPEECH', + threshold='BLOCK_ONLY_HIGH', + ) + ] + ), +) +print(response.text) +``` + +### Function Calling + +#### Automatic Python function Support + +You can pass a Python function directly and it will be automatically +called and responded by default. + +```python +from google.genai import types + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The city and state, e.g. San Francisco, CA + """ + return 'sunny' + + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='What is the weather like in Boston?', + config=types.GenerateContentConfig(tools=[get_current_weather]), +) + +print(response.text) +``` +#### Disabling automatic function calling +If you pass in a python function as a tool directly, and do not want +automatic function calling, you can disable automatic function calling +as follows: + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='What is the weather like in Boston?', + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + ), +) +``` + +With automatic function calling disabled, you will get a list of function call +parts in the response: + +```python +function_calls: Optional[List[types.FunctionCall]] = response.function_calls +``` + +#### Manually declare and invoke a function for function calling + +If you don't want to use the automatic function support, you can manually +declare the function and invoke it. + +The following example shows how to declare a function and pass it as a tool. +Then you will receive a function call part in the response. + +```python +from google.genai import types + +function = types.FunctionDeclaration( + name='get_current_weather', + description='Get the current weather in a given location', + parameters=types.Schema( + type='OBJECT', + properties={ + 'location': types.Schema( + type='STRING', + description='The city and state, e.g. San Francisco, CA', + ), + }, + required=['location'], + ), +) + +tool = types.Tool(function_declarations=[function]) + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='What is the weather like in Boston?', + config=types.GenerateContentConfig(tools=[tool]), +) + +print(response.function_calls[0]) +``` + +After you receive the function call part from the model, you can invoke the function +and get the function response. And then you can pass the function response to +the model. +The following example shows how to do it for a simple function invocation. + +```python +from google.genai import types + +user_prompt_content = types.Content( + role='user', + parts=[types.Part.from_text(text='What is the weather like in Boston?')], +) +function_call_part = response.function_calls[0] +function_call_content = response.candidates[0].content + + +try: + function_result = get_current_weather( + **function_call_part.function_call.args + ) + function_response = {'result': function_result} +except ( + Exception +) as e: # instead of raising the exception, you can let the model handle it + function_response = {'error': str(e)} + + +function_response_part = types.Part.from_function_response( + name=function_call_part.name, + response=function_response, +) +function_response_content = types.Content( + role='tool', parts=[function_response_part] +) + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents=[ + user_prompt_content, + function_call_content, + function_response_content, + ], + config=types.GenerateContentConfig( + tools=[tool], + ), +) + +print(response.text) +``` + +#### Function calling with `ANY` tools config mode + +If you configure function calling mode to be `ANY`, then the model will always +return function call parts. If you also pass a python function as a tool, by +default the SDK will perform automatic function calling until the remote calls exceed the +maximum remote call for automatic function calling (default to 10 times). + +If you'd like to disable automatic function calling in `ANY` mode: + +```python +from google.genai import types + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The city and state, e.g. San Francisco, CA + """ + return "sunny" + +response = client.models.generate_content( + model="gemini-2.0-flash-001", + contents="What is the weather like in Boston?", + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode='ANY') + ), + ), +) +``` + +If you'd like to set `x` number of automatic function call turns, you can +configure the maximum remote calls to be `x + 1`. +Assuming you prefer `1` turn for automatic function calling. + +```python +from google.genai import types + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The city and state, e.g. San Francisco, CA + """ + return "sunny" + +response = client.models.generate_content( + model="gemini-2.0-flash-001", + contents="What is the weather like in Boston?", + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + maximum_remote_calls=2 + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode='ANY') + ), + ), +) +``` +### JSON Response Schema + +However you define your schema, don't duplicate it in your input prompt, +including by giving examples of expected JSON output. If you do, the generated +output might be lower in quality. + +#### Pydantic Model Schema support + +Schemas can be provided as Pydantic Models. + +```python +from pydantic import BaseModel +from google.genai import types + + +class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='Give me information for the United States.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=CountryInfo, + ), +) +print(response.text) +``` + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='Give me information for the United States.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema={ + 'required': [ + 'name', + 'population', + 'capital', + 'continent', + 'gdp', + 'official_language', + 'total_area_sq_mi', + ], + 'properties': { + 'name': {'type': 'STRING'}, + 'population': {'type': 'INTEGER'}, + 'capital': {'type': 'STRING'}, + 'continent': {'type': 'STRING'}, + 'gdp': {'type': 'INTEGER'}, + 'official_language': {'type': 'STRING'}, + 'total_area_sq_mi': {'type': 'INTEGER'}, + }, + 'type': 'OBJECT', + }, + ), +) +print(response.text) +``` + +### Enum Response Schema + +#### Text Response + +You can set response_mime_type to 'text/x.enum' to return one of those enum +values as the response. + +```python +class InstrumentEnum(Enum): + PERCUSSION = 'Percussion' + STRING = 'String' + WOODWIND = 'Woodwind' + BRASS = 'Brass' + KEYBOARD = 'Keyboard' + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='What instrument plays multiple notes at once?', + config={ + 'response_mime_type': 'text/x.enum', + 'response_schema': InstrumentEnum, + }, + ) +print(response.text) +``` + +#### JSON Response + +You can also set response_mime_type to 'application/json', the response will be +identical but in quotes. + +```python +from enum import Enum + +class InstrumentEnum(Enum): + PERCUSSION = 'Percussion' + STRING = 'String' + WOODWIND = 'Woodwind' + BRASS = 'Brass' + KEYBOARD = 'Keyboard' + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='What instrument plays multiple notes at once?', + config={ + 'response_mime_type': 'application/json', + 'response_schema': InstrumentEnum, + }, + ) +print(response.text) +``` + +### Generate Content (Synchronous Streaming) + +Generate content in a streaming format so that the model outputs streams back +to you, rather than being returned as one chunk. + +#### Streaming for text content + +```python +for chunk in client.models.generate_content_stream( + model='gemini-2.0-flash-001', contents='Tell me a story in 300 words.' +): + print(chunk.text, end='') +``` + +#### Streaming for image content + +If your image is stored in [Google Cloud Storage](https://cloud.google.com/storage), +you can use the `from_uri` class method to create a `Part` object. + +```python +from google.genai import types + +for chunk in client.models.generate_content_stream( + model='gemini-2.0-flash-001', + contents=[ + 'What is this image about?', + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ], +): + print(chunk.text, end='') +``` + +If your image is stored in your local file system, you can read it in as bytes +data and use the `from_bytes` class method to create a `Part` object. + +```python +from google.genai import types + +YOUR_IMAGE_PATH = 'your_image_path' +YOUR_IMAGE_MIME_TYPE = 'your_image_mime_type' +with open(YOUR_IMAGE_PATH, 'rb') as f: + image_bytes = f.read() + +for chunk in client.models.generate_content_stream( + model='gemini-2.0-flash-001', + contents=[ + 'What is this image about?', + types.Part.from_bytes(data=image_bytes, mime_type=YOUR_IMAGE_MIME_TYPE), + ], +): + print(chunk.text, end='') +``` + +### Generate Content (Asynchronous Non Streaming) + +`client.aio` exposes all the analogous [`async` methods](https://docs.python.org/3/library/asyncio.html) +that are available on `client`. Note that it applies to all the modules. + +For example, `client.aio.models.generate_content` is the `async` version +of `client.models.generate_content` + +```python +response = await client.aio.models.generate_content( + model='gemini-2.0-flash-001', contents='Tell me a story in 300 words.' +) + +print(response.text) +``` + +### Generate Content (Asynchronous Streaming) + + +```python +async for chunk in await client.aio.models.generate_content_stream( + model='gemini-2.0-flash-001', contents='Tell me a story in 300 words.' +): + print(chunk.text, end='') +``` + +### Count Tokens and Compute Tokens + +```python +response = client.models.count_tokens( + model='gemini-2.0-flash-001', + contents='why is the sky blue?', +) +print(response) +``` + +#### Compute Tokens + +Compute tokens is only supported in Vertex AI. + +```python +response = client.models.compute_tokens( + model='gemini-2.0-flash-001', + contents='why is the sky blue?', +) +print(response) +``` + +##### Async + +```python +response = await client.aio.models.count_tokens( + model='gemini-2.0-flash-001', + contents='why is the sky blue?', +) +print(response) +``` + +### Embed Content + +```python +response = client.models.embed_content( + model='text-embedding-004', + contents='why is the sky blue?', +) +print(response) +``` + +```python +from google.genai import types + +# multiple contents with config +response = client.models.embed_content( + model='text-embedding-004', + contents=['why is the sky blue?', 'What is your age?'], + config=types.EmbedContentConfig(output_dimensionality=10), +) + +print(response) +``` + +### Imagen + +#### Generate Images + +Support for generate images in Gemini Developer API is behind an allowlist + +```python +from google.genai import types + +# Generate Image +response1 = client.models.generate_images( + model='imagen-3.0-generate-002', + prompt='An umbrella in the foreground, and a rainy night sky in the background', + config=types.GenerateImagesConfig( + number_of_images=1, + include_rai_reason=True, + output_mime_type='image/jpeg', + ), +) +response1.generated_images[0].image.show() +``` + +#### Upscale Image + +Upscale image is only supported in Vertex AI. + +```python +from google.genai import types + +# Upscale the generated image from above +response2 = client.models.upscale_image( + model='imagen-3.0-generate-001', + image=response1.generated_images[0].image, + upscale_factor='x2', + config=types.UpscaleImageConfig( + include_rai_reason=True, + output_mime_type='image/jpeg', + ), +) +response2.generated_images[0].image.show() +``` + +#### Edit Image + +Edit image uses a separate model from generate and upscale. + +Edit image is only supported in Vertex AI. + +```python +# Edit the generated image from above +from google.genai import types +from google.genai.types import RawReferenceImage, MaskReferenceImage + +raw_ref_image = RawReferenceImage( + reference_id=1, + reference_image=response1.generated_images[0].image, +) + +# Model computes a mask of the background +mask_ref_image = MaskReferenceImage( + reference_id=2, + config=types.MaskReferenceConfig( + mask_mode='MASK_MODE_BACKGROUND', + mask_dilation=0, + ), +) + +response3 = client.models.edit_image( + model='imagen-3.0-capability-001', + prompt='Sunlight and clear sky', + reference_images=[raw_ref_image, mask_ref_image], + config=types.EditImageConfig( + edit_mode='EDIT_MODE_INPAINT_INSERTION', + number_of_images=1, + include_rai_reason=True, + output_mime_type='image/jpeg', + ), +) +response3.generated_images[0].image.show() +``` + +### Veo + +#### Generate Videos + +Support for generate videos in Vertex and Gemini Developer API is behind an allowlist + +```python +from google.genai import types + +# Create operation +operation = client.models.generate_videos( + model='veo-2.0-generate-001', + prompt='A neon hologram of a cat driving at top speed', + config=types.GenerateVideosConfig( + number_of_videos=1, + fps=24, + duration_seconds=5, + enhance_prompt=True, + ), +) + +# Poll operation +while not operation.done: + time.sleep(20) + operation = client.operations.get(operation) + +video = operation.result.generated_videos[0].video +video.show() +``` + +## Chats + +Create a chat session to start a multi-turn conversations with the model. Then, +use `chat.send_message` function multiple times within the same chat session so +that it can reflect on its previous responses (i.e., engage in an ongoing + conversation). See the 'Create a client' section above to initialize a client. + +### Send Message (Synchronous Non-Streaming) + +```python +chat = client.chats.create(model='gemini-2.0-flash-001') +response = chat.send_message('tell me a story') +print(response.text) +response = chat.send_message('summarize the story you told me in 1 sentence') +print(response.text) +``` + +### Send Message (Synchronous Streaming) + +```python +chat = client.chats.create(model='gemini-2.0-flash-001') +for chunk in chat.send_message_stream('tell me a story'): + print(chunk.text) +``` + +### Send Message (Asynchronous Non-Streaming) + +```python +chat = client.aio.chats.create(model='gemini-2.0-flash-001') +response = await chat.send_message('tell me a story') +print(response.text) +``` + +### Send Message (Asynchronous Streaming) + +```python +chat = client.aio.chats.create(model='gemini-2.0-flash-001') +async for chunk in await chat.send_message_stream('tell me a story'): + print(chunk.text) +``` + +## Files + +Files are only supported in Gemini Developer API. See the 'Create a client' +section above to initialize a client. + +```cmd +!gsutil cp gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf . +!gsutil cp gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf . +``` + +### Upload + +```python +file1 = client.files.upload(file='2312.11805v3.pdf') +file2 = client.files.upload(file='2403.05530.pdf') + +print(file1) +print(file2) +``` + +### Get + +```python +file1 = client.files.upload(file='2312.11805v3.pdf') +file_info = client.files.get(name=file1.name) +``` + +### Delete + +```python +file3 = client.files.upload(file='2312.11805v3.pdf') + +client.files.delete(name=file3.name) +``` + +## Caches + +`client.caches` contains the control plane APIs for cached content. See the +'Create a client' section above to initialize a client. + +### Create + +```python +from google.genai import types + +if client.vertexai: + file_uris = [ + 'gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf', + 'gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf', + ] +else: + file_uris = [file1.uri, file2.uri] + +cached_content = client.caches.create( + model='gemini-2.0-flash-001', + config=types.CreateCachedContentConfig( + contents=[ + types.Content( + role='user', + parts=[ + types.Part.from_uri( + file_uri=file_uris[0], mime_type='application/pdf' + ), + types.Part.from_uri( + file_uri=file_uris[1], + mime_type='application/pdf', + ), + ], + ) + ], + system_instruction='What is the sum of the two pdfs?', + display_name='test cache', + ttl='3600s', + ), +) +``` + +### Get + +```python +cached_content = client.caches.get(name=cached_content.name) +``` + +### Generate Content with Caches + +```python +from google.genai import types + +response = client.models.generate_content( + model='gemini-2.0-flash-001', + contents='Summarize the pdfs', + config=types.GenerateContentConfig( + cached_content=cached_content.name, + ), +) +print(response.text) +``` + +## Tunings + +`client.tunings` contains tuning job APIs and supports supervised fine +tuning through `tune`. See the 'Create a client' section above to initialize a +client. + +### Tune + +- Vertex AI supports tuning from GCS source +- Gemini Developer API supports tuning from inline examples + +```python +from google.genai import types + +if client.vertexai: + model = 'gemini-2.0-flash-001' + training_dataset = types.TuningDataset( + gcs_uri='gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl', + ) +else: + model = 'models/gemini-2.0-flash-001' + training_dataset = types.TuningDataset( + examples=[ + types.TuningExample( + text_input=f'Input text {i}', + output=f'Output text {i}', + ) + for i in range(5) + ], + ) +``` + +```python +from google.genai import types + +tuning_job = client.tunings.tune( + base_model=model, + training_dataset=training_dataset, + config=types.CreateTuningJobConfig( + epoch_count=1, tuned_model_display_name='test_dataset_examples model' + ), +) +print(tuning_job) +``` + +### Get Tuning Job + +```python +tuning_job = client.tunings.get(name=tuning_job.name) +print(tuning_job) +``` + +```python +import time + +running_states = set( + [ + 'JOB_STATE_PENDING', + 'JOB_STATE_RUNNING', + ] +) + +while tuning_job.state in running_states: + print(tuning_job.state) + tuning_job = client.tunings.get(name=tuning_job.name) + time.sleep(10) +``` + +#### Use Tuned Model + +```python +response = client.models.generate_content( + model=tuning_job.tuned_model.endpoint, + contents='why is the sky blue?', +) + +print(response.text) +``` + +### Get Tuned Model + +```python +tuned_model = client.models.get(model=tuning_job.tuned_model.model) +print(tuned_model) +``` + +### List Tuned Models + +To retrieve base models, see [list base models](#list-base-models). + +```python +for model in client.models.list(config={'page_size': 10, 'query_base': False}): + print(model) +``` + +```python +pager = client.models.list(config={'page_size': 10, 'query_base': False}) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### Async + +```python +async for job in await client.aio.models.list(config={'page_size': 10, 'query_base': False}): + print(job) +``` + +```python +async_pager = await client.aio.models.list(config={'page_size': 10, 'query_base': False}) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +### Update Tuned Model + +```python +from google.genai import types + +model = pager[0] + +model = client.models.update( + model=model.name, + config=types.UpdateModelConfig( + display_name='my tuned model', description='my tuned model description' + ), +) + +print(model) +``` + + +### List Tuning Jobs + +```python +for job in client.tunings.list(config={'page_size': 10}): + print(job) +``` + +```python +pager = client.tunings.list(config={'page_size': 10}) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### Async + +```python +async for job in await client.aio.tunings.list(config={'page_size': 10}): + print(job) +``` + +```python +async_pager = await client.aio.tunings.list(config={'page_size': 10}) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +## Batch Prediction + +Only supported in Vertex AI. See the 'Create a client' section above to +initialize a client. + +### Create + +```python +# Specify model and source file only, destination and job display name will be auto-populated +job = client.batches.create( + model='gemini-2.0-flash-001', + src='bq://my-project.my-dataset.my-table', +) + +job +``` + +```python +# Get a job by name +job = client.batches.get(name=job.name) + +job.state +``` + +```python +completed_states = set( + [ + 'JOB_STATE_SUCCEEDED', + 'JOB_STATE_FAILED', + 'JOB_STATE_CANCELLED', + 'JOB_STATE_PAUSED', + ] +) + +while job.state not in completed_states: + print(job.state) + job = client.batches.get(name=job.name) + time.sleep(30) + +job +``` + +### List + +```python +for job in client.batches.list(config=types.ListBatchJobsConfig(page_size=10)): + print(job) +``` + +```python +pager = client.batches.list(config=types.ListBatchJobsConfig(page_size=10)) +print(pager.page_size) +print(pager[0]) +pager.next_page() +print(pager[0]) +``` + +#### Async + +```python +async for job in await client.aio.batches.list( + config=types.ListBatchJobsConfig(page_size=10) +): + print(job) +``` + +```python +async_pager = await client.aio.batches.list( + config=types.ListBatchJobsConfig(page_size=10) +) +print(async_pager.page_size) +print(async_pager[0]) +await async_pager.next_page() +print(async_pager[0]) +``` + +### Delete + +```python +# Delete the job resource +delete_job = client.batches.delete(name=job.name) + +delete_job +``` + +## Error Handling + +To handle errors raised by the model service, the SDK provides this [APIError](https://github.com/googleapis/python-genai/blob/main/google/genai/errors.py) class. + +```python +from google.genai import errors + +try: + client.models.generate_content( + model="invalid-model-name", + contents="What is your name?", + ) +except errors.APIError as e: + print(e.code) # 404 + print(e.message) +``` diff --git a/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/RECORD b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b247085068e0d7ed88ce8af21538880edf7be395 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/RECORD @@ -0,0 +1,66 @@ +google/genai/__init__.py,sha256=SYTxz3Ho06pP2TBlvDU0FkUJz8ytbR3MgEpS9HvVYq4,709 +google/genai/__pycache__/__init__.cpython-312.pyc,, +google/genai/__pycache__/_adapters.cpython-312.pyc,, +google/genai/__pycache__/_api_client.cpython-312.pyc,, +google/genai/__pycache__/_api_module.cpython-312.pyc,, +google/genai/__pycache__/_automatic_function_calling_util.cpython-312.pyc,, +google/genai/__pycache__/_base_url.cpython-312.pyc,, +google/genai/__pycache__/_common.cpython-312.pyc,, +google/genai/__pycache__/_extra_utils.cpython-312.pyc,, +google/genai/__pycache__/_live_converters.cpython-312.pyc,, +google/genai/__pycache__/_mcp_utils.cpython-312.pyc,, +google/genai/__pycache__/_replay_api_client.cpython-312.pyc,, +google/genai/__pycache__/_test_api_client.cpython-312.pyc,, +google/genai/__pycache__/_tokens_converters.cpython-312.pyc,, +google/genai/__pycache__/_transformers.cpython-312.pyc,, +google/genai/__pycache__/batches.cpython-312.pyc,, +google/genai/__pycache__/caches.cpython-312.pyc,, +google/genai/__pycache__/chats.cpython-312.pyc,, +google/genai/__pycache__/client.cpython-312.pyc,, +google/genai/__pycache__/errors.cpython-312.pyc,, +google/genai/__pycache__/files.cpython-312.pyc,, +google/genai/__pycache__/live.cpython-312.pyc,, +google/genai/__pycache__/live_music.cpython-312.pyc,, +google/genai/__pycache__/models.cpython-312.pyc,, +google/genai/__pycache__/operations.cpython-312.pyc,, +google/genai/__pycache__/pagers.cpython-312.pyc,, +google/genai/__pycache__/tokens.cpython-312.pyc,, +google/genai/__pycache__/tunings.cpython-312.pyc,, +google/genai/__pycache__/types.cpython-312.pyc,, +google/genai/__pycache__/version.cpython-312.pyc,, +google/genai/_adapters.py,sha256=Kok38miNYJff2n--l0zEK_hbq0y2rWOH7k75J7SMYbQ,1744 +google/genai/_api_client.py,sha256=AoCuJp2lI9zHvybCzcki2IK2DyUhfUDly4s9CGxUmoc,49887 +google/genai/_api_module.py,sha256=lj8eUWx8_LBGBz-49qz6_ywWm3GYp3d8Bg5JoOHbtbI,902 +google/genai/_automatic_function_calling_util.py,sha256=IJkPq2fT9pYxYm5Pbu5-e0nBoZKoZla7yT4_txWRKLs,10324 +google/genai/_base_url.py,sha256=E5H4dew14Y16qfnB3XRnjSCi19cJVlkaMNoM_8ip-PM,1597 +google/genai/_common.py,sha256=CuG7wvroFu9kV0Im-asXJGmfbaFCAjCocZyRxYDss5g,19849 +google/genai/_extra_utils.py,sha256=GoIh_SxB5nf_0sjErYkjm8wdg93sfemLKrU_5QhlcBo,20562 +google/genai/_live_converters.py,sha256=lbpN5E8DjL74a2XLcgND4pzs3bHDeVpUtPDN8s7IZCU,108613 +google/genai/_mcp_utils.py,sha256=khECx-DMuHemKzOQQ3msWp7FivPeEOnl3n1lvWc_b5o,3833 +google/genai/_replay_api_client.py,sha256=0IXroewCZbyZ01qN3ZQwW5OUZRMzCrf2-3nyfTerqNY,21363 +google/genai/_test_api_client.py,sha256=4ruFIy5_1qcbKqqIBu3HSQbpSOBrxiecBtDZaTGFR1s,4797 +google/genai/_tokens_converters.py,sha256=LxLZGgSWn6VC2-1R-4ArcuaPK45svg5P-bpC1LjBb3w,48901 +google/genai/_transformers.py,sha256=Nd_h_zYVOkWN1XTSnM9r3IR7R_qg3tPe2mE9jozaX-Q,36935 +google/genai/batches.py,sha256=ZpF3qgJUkPcpWjbaJtESiQq5qiZ0obsJl77yCtgZknA,170525 +google/genai/caches.py,sha256=Ckqqi0osoxNmkqYGvBGpvrZUx19D6hmuwS9UXcnGWmk,65911 +google/genai/chats.py,sha256=0QdOUeWEYDQgAWBy1f7a3z3yY9S8tXSowUzNrzazzj4,16651 +google/genai/client.py,sha256=wXnfZBSv9p-yKtX_gabUrfBXoYHuqHhzK_VgwRttMgY,10777 +google/genai/errors.py,sha256=UebysH1cDeIdtp1O06CW7lQjnNrWtuqZTeVgEJylX48,5589 +google/genai/files.py,sha256=MCcHRXiMFKjbnt78yVPejszEgGz_MHRXfJyDi5-07Gs,39655 +google/genai/live.py,sha256=6zKjLZKnd4J-t0XQ61yuzRJv8TwbhTW96Wr8dqeFPI8,38891 +google/genai/live_music.py,sha256=3GG9nsto8Vhkohcs-4CPMS4DFp1ZtMuLYzHfvEPYAeg,6971 +google/genai/models.py,sha256=7gBXwg6_RdW_HRD_iRFIAdqu0bkUkW0fAp_PMEPVwoU,239309 +google/genai/operations.py,sha256=99zs__fTWsyQu7rMGmBI1_4tuAJxLR0g3yp7ymsUsBA,19609 +google/genai/pagers.py,sha256=nyVYxp92rS-UaewO_oBgP593knofeLU6yOn6RolNoGQ,6797 +google/genai/py.typed,sha256=RsMFoLwBkAvY05t6izop4UHZtqOPLiKp3GkIEizzmQY,40 +google/genai/tokens.py,sha256=oew9I0fGuGLlXMdCn2Ot9Lv_herHMnvZOYjjdOz2CAM,12324 +google/genai/tunings.py,sha256=aUtotVuvn66vtsYiqwH3Av3arZ-sl3ooHCwkLijb6K4,48298 +google/genai/types.py,sha256=UmIBjW0qFbA2LN113DUtz8ZtgG1_7I0vIAPE0fVmTrc,459025 +google/genai/version.py,sha256=KWnZScqB5t3VtG5YNrQoE4_p36-OUcoYjWaKRdmLbQc,627 +google_genai-1.22.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_genai-1.22.0.dist-info/METADATA,sha256=bOufmJ0EEGx9pwhd0hPURu6MM7sR6WQnLGZiM7KY0hs,37123 +google_genai-1.22.0.dist-info/RECORD,, +google_genai-1.22.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google_genai-1.22.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +google_genai-1.22.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_genai-1.22.0.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/REQUESTED b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/python_embeded/Lib/site-packages/google_genai-1.22.0.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/INSTALLER b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/METADATA b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b9552c845598bb7ae422365140225d6fe5029d52 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/METADATA @@ -0,0 +1,82 @@ +Metadata-Version: 2.4 +Name: google-generativeai +Version: 0.8.5 +Summary: Google Generative AI High level API client library and tools. +Home-page: https://github.com/google/generative-ai-python +Author: Google LLC +Author-email: googleapis-packages@google.com +License: Apache 2.0 +Platform: Posix; MacOS X; Windows +Classifier: Development Status :: 7 - Inactive +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Typing :: Typed +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: google-ai-generativelanguage==0.6.15 +Requires-Dist: google-api-core +Requires-Dist: google-api-python-client +Requires-Dist: google-auth>=2.15.0 +Requires-Dist: protobuf +Requires-Dist: pydantic +Requires-Dist: tqdm +Requires-Dist: typing-extensions +Provides-Extra: dev +Requires-Dist: absl-py; extra == "dev" +Requires-Dist: black; extra == "dev" +Requires-Dist: nose2; extra == "dev" +Requires-Dist: pandas; extra == "dev" +Requires-Dist: pytype; extra == "dev" +Requires-Dist: pyyaml; extra == "dev" +Requires-Dist: Pillow; extra == "dev" +Requires-Dist: ipython; extra == "dev" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# [Deprecated] Google AI Python SDK for the Gemini API + +With Gemini 2.0, we took the chance to create a single unified SDK for all developers who want to use Google's GenAI models (Gemini, Veo, Imagen, etc). As part of that process, we took all of the feedback from this SDK and what developers like about other SDKs in the ecosystem to create the [Google Gen AI SDK](https://github.com/googleapis/python-genai). + +The full migration guide from the old SDK to new SDK is available in the [Gemini API docs](https://ai.google.dev/gemini-api/docs/migrate). + +The Gemini API docs are fully updated to show examples of the new Google Gen AI SDK. We know how disruptive an SDK change can be and don't take this change lightly, but our goal is to create an extremely simple and clear path for developers to build with our models so it felt necessary to make this change. + +Thank you for building with Gemini and [let us know](https://discuss.ai.google.dev/c/gemini-api/4) if you need any help! + +**Please be advised that this repository is now considered legacy.** For the latest features, performance improvements, and active development, we strongly recommend migrating to the official **[Google Generative AI SDK for Python](https://github.com/googleapis/python-genai)**. + +**Support Plan for this Repository:** + +* **Limited Maintenance:** Development is now restricted to **critical bug fixes only**. No new features will be added. +* **Purpose:** This limited support aims to provide stability for users while they transition to the new SDK. +* **End-of-Life Date:** All support for this repository (including bug fixes) will permanently end on **August 31st, 2025**. + +We encourage all users to begin planning their migration to the [Google Generative AI SDK](https://github.com/googleapis/python-genai) to ensure continued access to the latest capabilities and support. + + diff --git a/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/RECORD b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bd55c21a11db62b926d951f7c2d73f4ccdcf0adf --- /dev/null +++ b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/RECORD @@ -0,0 +1,150 @@ +google/generativeai/__init__.py,sha256=GaZ-GiesldHLs0UT3olM4HmJoaMTyPD8PKrcuzk5RbQ,2549 +google/generativeai/__pycache__/__init__.cpython-312.pyc,, +google/generativeai/__pycache__/answer.cpython-312.pyc,, +google/generativeai/__pycache__/caching.cpython-312.pyc,, +google/generativeai/__pycache__/client.cpython-312.pyc,, +google/generativeai/__pycache__/embedding.cpython-312.pyc,, +google/generativeai/__pycache__/files.cpython-312.pyc,, +google/generativeai/__pycache__/generative_models.cpython-312.pyc,, +google/generativeai/__pycache__/models.cpython-312.pyc,, +google/generativeai/__pycache__/operations.cpython-312.pyc,, +google/generativeai/__pycache__/permission.cpython-312.pyc,, +google/generativeai/__pycache__/protos.cpython-312.pyc,, +google/generativeai/__pycache__/responder.cpython-312.pyc,, +google/generativeai/__pycache__/retriever.cpython-312.pyc,, +google/generativeai/__pycache__/string_utils.cpython-312.pyc,, +google/generativeai/__pycache__/utils.cpython-312.pyc,, +google/generativeai/__pycache__/version.cpython-312.pyc,, +google/generativeai/answer.py,sha256=rxRKW4aO964nGIkta7xp4eg1yLoCrFdmlWkhZbrCecI,14058 +google/generativeai/audio_models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google/generativeai/audio_models/__pycache__/__init__.cpython-312.pyc,, +google/generativeai/audio_models/__pycache__/_audio_models.cpython-312.pyc,, +google/generativeai/audio_models/_audio_models.py,sha256=e0WTo1KHbCcmBCS8dvKC1Yd-_xwuxFwRHsfm-ic4lbk,102 +google/generativeai/caching.py,sha256=KJy7DAutyUuVsgcdj3Az8tFstKM33vGt2AuBsYfeYE8,10795 +google/generativeai/client.py,sha256=8ByOQzPZAgAH8YQXmvYwxEEtvyvQNcNBL2glJPkD8Gs,15071 +google/generativeai/embedding.py,sha256=JLEuuwaln0AEXWrRKEa1FUhqaY2Qu25vi33q7yFD6ps,12102 +google/generativeai/files.py,sha256=teSZGEoLXF0tmkDBGa-NmZZ_nie60yim__a7JA-I97s,4122 +google/generativeai/generative_models.py,sha256=NAFeT1bUbFlgbkz5ccUfZmiD34Wyw4bNv-QUsajJ75U,33828 +google/generativeai/models.py,sha256=UYWyRI0-lfhg5lGoiy-RK8C99lapTCfIeTQlS1JceS8,15915 +google/generativeai/notebook/__init__.py,sha256=CVZrwI1B6hcVoGkVXk5M1UPPF7mpH7PfSAjjyAnVW4o,1169 +google/generativeai/notebook/__pycache__/__init__.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/argument_parser.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/cmd_line_parser.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/command.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/command_utils.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/compare_cmd.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/compile_cmd.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/eval_cmd.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/flag_def.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/gspread_client.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/html_utils.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/input_utils.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/ipython_env.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/ipython_env_impl.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/magics.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/magics_engine.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/model_registry.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/output_utils.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/parsed_args_lib.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/post_process_utils.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/post_process_utils_test_helper.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/py_utils.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/run_cmd.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/sheets_id.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/sheets_sanitize_url.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/sheets_utils.cpython-312.pyc,, +google/generativeai/notebook/__pycache__/text_model.cpython-312.pyc,, +google/generativeai/notebook/argument_parser.py,sha256=akmRzKaDm-_aTGe8cy7a6zYlJpo7Cf2nMZ0FtPf_BwE,3961 +google/generativeai/notebook/cmd_line_parser.py,sha256=FmVwOGNsyknClyBya-sPO9JK_8kL5qpMGZ-v94gu_Q8,20405 +google/generativeai/notebook/command.py,sha256=BwpHMSSORuZfyCqVeJ9q694dPpmfL2jJrLhnbhWqAHw,1535 +google/generativeai/notebook/command_utils.py,sha256=9f1cxzGtKezr0BDzrY1rAjkrCt_rTYzp-GZzyj1bHEE,6271 +google/generativeai/notebook/compare_cmd.py,sha256=_S3yv9DrLicCspBlBYC4JuSCIT4vWDqf1PvQ_8O7PPI,2566 +google/generativeai/notebook/compile_cmd.py,sha256=LLGrGYCsG8PFj1DQ1Nu2NK3ihWxVeJ-ClVIM6mrRX3w,2365 +google/generativeai/notebook/eval_cmd.py,sha256=t8b-MvrQsvk94CmDyKg6Jn5W4uMhIfSG2wJZyEJu8Tk,2756 +google/generativeai/notebook/flag_def.py,sha256=MEc4kCX0YA5EvWEtw0gdBo7Tc5TLKeGGFP-dyLO69LM,17278 +google/generativeai/notebook/gspread_client.py,sha256=sgDaDHTDolqdlK32U8XvKWYlBx_WtBT4xLO5mHshuSM,7711 +google/generativeai/notebook/html_utils.py,sha256=1VW0U1yaIhvYQ9UGfzfBoey6tdhcSCdzLmCxly_22os,1555 +google/generativeai/notebook/input_utils.py,sha256=rO0ApC7-dRjGJK7dV8od78_CRhSliHRQYFsrXI0cq8o,2819 +google/generativeai/notebook/ipython_env.py,sha256=XvPFuaBF7SOsKBuftwW7Da0VDOPSbcjKIqq_BDGlSKc,1686 +google/generativeai/notebook/ipython_env_impl.py,sha256=bgWDdVS7bSHf1_PB99gF9PD2Eff95diopnVFLfA6DjI,1058 +google/generativeai/notebook/lib/__init__.py,sha256=XZJbp_UwFkIG3WxhEGGBxDjdv2pCkZF_n4r8aRJhbrw,598 +google/generativeai/notebook/lib/__pycache__/__init__.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/llm_function.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/llmfn_input_utils.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/llmfn_inputs_source.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/llmfn_output_row.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/llmfn_outputs.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/llmfn_post_process.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/llmfn_post_process_cmds.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/model.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/prompt_utils.cpython-312.pyc,, +google/generativeai/notebook/lib/__pycache__/unique_fn.cpython-312.pyc,, +google/generativeai/notebook/lib/llm_function.py,sha256=Oslg0g1RdTsowY8xe1qJ77Yga9hsQl4Whq8U6woE0f8,18317 +google/generativeai/notebook/lib/llmfn_input_utils.py,sha256=bLjxFzmn4KP78idKWpqUJQJCFvG5zWEeWZXzGFyKSTE,2969 +google/generativeai/notebook/lib/llmfn_inputs_source.py,sha256=yxrUzHVMdsvriXRd9x9Vv2JZ4QjfvhbeMf9ME3Xc1Xo,2443 +google/generativeai/notebook/lib/llmfn_output_row.py,sha256=6PXjNJi7Me2Pl0_xQ-DNahId6TkdpiBhLZ4Lsn2Y7GY,5917 +google/generativeai/notebook/lib/llmfn_outputs.py,sha256=SjwJRDP33WECSTz4KoIxx3I7nmF9vU1HnP_yYXNSu50,8532 +google/generativeai/notebook/lib/llmfn_post_process.py,sha256=X4_TJiBsrE77vlrCr1QBYtbfnPlPIMBiAZBFP0MmuCU,2470 +google/generativeai/notebook/lib/llmfn_post_process_cmds.py,sha256=i3ZBzmG2YT1qAbKaFB17r4AMbN95QSlP21pjpPZaelk,8570 +google/generativeai/notebook/lib/model.py,sha256=LlgdUxiY6FwoUkNxAfwFMdkqxBvr4A4bo0YRiP5wOFA,2055 +google/generativeai/notebook/lib/prompt_utils.py,sha256=7lVWJjn0eqzhhux70XiXokqsQo7RbOVUkuGN6hepJ38,1264 +google/generativeai/notebook/lib/unique_fn.py,sha256=yo1rucNEWEtrJ2rxbAa5HCLr9XF92sHwb7EB8NXYP6Y,1487 +google/generativeai/notebook/magics.py,sha256=hEtQm7kD_gITn8ntSNC-NPb9SkB7DOxyA7Ki0tesSeY,4616 +google/generativeai/notebook/magics_engine.py,sha256=TKbpNnA8VuNm36xuQYfKZH8e8JokjAX3Gqmrbj0WDx4,5468 +google/generativeai/notebook/model_registry.py,sha256=cMLfJICxIssmsXp23pLV_8xnSnbWDmOfNwCIjzlDLtU,1919 +google/generativeai/notebook/output_utils.py,sha256=QY-1UzR7yiYS5IEfU6vn0s-foLREVXznva2A2fA4kW8,2085 +google/generativeai/notebook/parsed_args_lib.py,sha256=dXH02fJkckm24TkWnnJcpqtseYRxekGBMS-QUjF3Bfs,3084 +google/generativeai/notebook/post_process_utils.py,sha256=SLa99MH-zGIJn9W3UppWT7aMH5QSu8OugjX0jIVeJec,5803 +google/generativeai/notebook/post_process_utils_test_helper.py,sha256=bMusySOKISqIhmd2_49p8103Np1lwdhshp6YuIjLPRY,991 +google/generativeai/notebook/py_utils.py,sha256=UACFs9bj-De6ceDAPtvIryNh9SxSk9vqtZNmVobumbY,2073 +google/generativeai/notebook/run_cmd.py,sha256=tCcfCPHK5NKwD1d7qRjGRWD8LxLldyf8RVOf0jVKn1g,2744 +google/generativeai/notebook/sheets_id.py,sha256=coYbKRwPjEoJJePA-1LErnBlTVibQdvT6P9AC87I0Bw,3071 +google/generativeai/notebook/sheets_sanitize_url.py,sha256=e6oirLNc2e3lf2RZgF4PqDz3gKDqvESUjMDrItOP47Y,2977 +google/generativeai/notebook/sheets_utils.py,sha256=rXsVzzlfAk7Z7w5CVGxfXsTQ8qZ5H4bNXPElBMpM--E,3964 +google/generativeai/notebook/text_model.py,sha256=2hHo8deXP_2JJGoTbeRJJfI4VljlC0ymPTKTo3blx5w,2640 +google/generativeai/operations.py,sha256=SIDtIPMZDTEpqMhRtc4SFr-53WuuvO9EKzE1vRGm_w8,5053 +google/generativeai/permission.py,sha256=V_v0xEOLgfYDtZPU0U6GhEGOzfKF1DH23W5GhRzrUjU,6367 +google/generativeai/protos.py,sha256=7Q7BDPEuQV6rMxGE_499APxfNFAFKzIWL4hCTiPd6dY,2738 +google/generativeai/py.typed,sha256=KneSh8WTMIRWGGEgie2ncIfK7rC0NjiLWiKsTouBtWo,41 +google/generativeai/responder.py,sha256=ximgn2mODWs9hWIy4wc9EPvyQwfiNp4BW8aGQt-gsPs,19972 +google/generativeai/retriever.py,sha256=r8wKeHD4h1b7LQxn_x-Z7FX7Z9jsgPH4sFH8qq-zJXk,8907 +google/generativeai/string_utils.py,sha256=vOU4fHULo9O69vtwsZ5DNQGndEV3ZDizX3sytv0ixZg,2441 +google/generativeai/types/__init__.py,sha256=k9mb3vGWpu3dsPZAkMV1iQN5A1T23bvP1kN3CMt12Wk,1153 +google/generativeai/types/__pycache__/__init__.cpython-312.pyc,, +google/generativeai/types/__pycache__/answer_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/caching_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/citation_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/content_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/file_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/generation_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/helper_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/model_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/palm_safety_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/permission_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/retriever_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/safety_types.cpython-312.pyc,, +google/generativeai/types/__pycache__/text_types.cpython-312.pyc,, +google/generativeai/types/answer_types.py,sha256=UiVpZM0ASYkR6Lig4ngeWBrQl91mK7ygTBQDdaDH3vc,2115 +google/generativeai/types/caching_types.py,sha256=JQoGErVp1zEjVaqi8bvIejp_HUhSnQEN-F0mT-tH18Q,2398 +google/generativeai/types/citation_types.py,sha256=SPJlWpyeZu-akpl9ZpeLwry77zuXApHX8b0h7MlT8-8,1229 +google/generativeai/types/content_types.py,sha256=mudeHsmwIE4NVwg03zO-7bjB4sD03yAmdEXp4_2hH_Y,32180 +google/generativeai/types/file_types.py,sha256=DeBRIpeJy-1TFTJiyBVojC9_3jg27fKVWHuc5v2oBrU,3960 +google/generativeai/types/generation_types.py,sha256=HumgmUXXI6ERiROyhlITA710-Tj2AGvEf1MRbUvQSp8,26055 +google/generativeai/types/helper_types.py,sha256=BAn8P8mqp0WWZ3oSFqZvvpwj8O2yQOZOl3zC14HxYHw,2840 +google/generativeai/types/model_types.py,sha256=LDP0S8V1YjlqXxHIbiuHVdaGZ0gvIg-V-oBwm3pdVqM,12760 +google/generativeai/types/palm_safety_types.py,sha256=wmjooyJ9a33D1I52fXU1dw45xTli3pk6p5IrLdX_N6c,10393 +google/generativeai/types/permission_types.py,sha256=r5EO_3lDwaSVGxnPFcrmbhMZop4F-m8CEK8WvJX8R3s,16549 +google/generativeai/types/retriever_types.py,sha256=J4_UEES1gwrlMdBUnvBeGsIhr1QtmsNtK3jcctUGmPs,61271 +google/generativeai/types/safety_types.py,sha256=bl9HbW8TNl4bSofESEDbQjvE1yzc5cXrG-aZcK6p5NY,10942 +google/generativeai/types/text_types.py,sha256=i30VvVfYDc3wQOOxOBwhm2uH8Kio4PN9lJ0DW2ddUa4,982 +google/generativeai/utils.py,sha256=G1Ps-Y18EZsfPcp3rmjF_Krps1bGOfbmcBij7_36Ulw,1090 +google/generativeai/version.py,sha256=JFfEx-QQKDDRrPPFPcNuh81NsqHVjVwN_LJXhzXwswM,656 +google_generativeai-0.8.5-py3.13-nspkg.pth,sha256=SSGHNp7YlGakPsphxkWm0fKg3pzrfQYRQ42ZPtiPF-4,467 +google_generativeai-0.8.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +google_generativeai-0.8.5.dist-info/METADATA,sha256=wORq09cD0tgUTDArjBKGWP-OBMdjQH5VuEmE7rtbQ2M,3937 +google_generativeai-0.8.5.dist-info/RECORD,, +google_generativeai-0.8.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +google_generativeai-0.8.5.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91 +google_generativeai-0.8.5.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +google_generativeai-0.8.5.dist-info/namespace_packages.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 +google_generativeai-0.8.5.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/REQUESTED b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/WHEEL b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1eb3c49d99559863120cfb8433fc8738fba43ba9 --- /dev/null +++ b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/namespace_packages.txt b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/namespace_packages.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/namespace_packages.txt @@ -0,0 +1 @@ +google diff --git a/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/top_level.txt b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/python_embeded/Lib/site-packages/google_generativeai-0.8.5.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/python_embeded/Lib/site-packages/googleapiclient/__init__.py b/python_embeded/Lib/site-packages/googleapiclient/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9218dd854063df739f78247c299643f2c6b29f0 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Set default logging handler to avoid "No handler found" warnings. +import logging + +try: # Python 2.7+ + from logging import NullHandler +except ImportError: + + class NullHandler(logging.Handler): + def emit(self, record): + pass + + +logging.getLogger(__name__).addHandler(NullHandler()) diff --git a/python_embeded/Lib/site-packages/googleapiclient/_auth.py b/python_embeded/Lib/site-packages/googleapiclient/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..065b2ecd307df1d69a7e6afe1b94086b8b33c838 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/_auth.py @@ -0,0 +1,167 @@ +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helpers for authentication using oauth2client or google-auth.""" + +import httplib2 + +try: + import google.auth + import google.auth.credentials + + HAS_GOOGLE_AUTH = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH = False + +try: + import google_auth_httplib2 +except ImportError: # pragma: NO COVER + google_auth_httplib2 = None + +try: + import oauth2client + import oauth2client.client + + HAS_OAUTH2CLIENT = True +except ImportError: # pragma: NO COVER + HAS_OAUTH2CLIENT = False + + +def credentials_from_file(filename, scopes=None, quota_project_id=None): + """Returns credentials loaded from a file.""" + if HAS_GOOGLE_AUTH: + credentials, _ = google.auth.load_credentials_from_file( + filename, scopes=scopes, quota_project_id=quota_project_id + ) + return credentials + else: + raise EnvironmentError( + "client_options.credentials_file is only supported in google-auth." + ) + + +def default_credentials(scopes=None, quota_project_id=None): + """Returns Application Default Credentials.""" + if HAS_GOOGLE_AUTH: + credentials, _ = google.auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + return credentials + elif HAS_OAUTH2CLIENT: + if scopes is not None or quota_project_id is not None: + raise EnvironmentError( + "client_options.scopes and client_options.quota_project_id are not supported in oauth2client." + "Please install google-auth." + ) + return oauth2client.client.GoogleCredentials.get_application_default() + else: + raise EnvironmentError( + "No authentication library is available. Please install either " + "google-auth or oauth2client." + ) + + +def with_scopes(credentials, scopes): + """Scopes the credentials if necessary. + + Args: + credentials (Union[ + google.auth.credentials.Credentials, + oauth2client.client.Credentials]): The credentials to scope. + scopes (Sequence[str]): The list of scopes. + + Returns: + Union[google.auth.credentials.Credentials, + oauth2client.client.Credentials]: The scoped credentials. + """ + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + return google.auth.credentials.with_scopes_if_required(credentials, scopes) + else: + try: + if credentials.create_scoped_required(): + return credentials.create_scoped(scopes) + else: + return credentials + except AttributeError: + return credentials + + +def authorized_http(credentials): + """Returns an http client that is authorized with the given credentials. + + Args: + credentials (Union[ + google.auth.credentials.Credentials, + oauth2client.client.Credentials]): The credentials to use. + + Returns: + Union[httplib2.Http, google_auth_httplib2.AuthorizedHttp]: An + authorized http client. + """ + from googleapiclient.http import build_http + + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + if google_auth_httplib2 is None: + raise ValueError( + "Credentials from google.auth specified, but " + "google-api-python-client is unable to use these credentials " + "unless google-auth-httplib2 is installed. Please install " + "google-auth-httplib2." + ) + return google_auth_httplib2.AuthorizedHttp(credentials, http=build_http()) + else: + return credentials.authorize(build_http()) + + +def refresh_credentials(credentials): + # Refresh must use a new http instance, as the one associated with the + # credentials could be a AuthorizedHttp or an oauth2client-decorated + # Http instance which would cause a weird recursive loop of refreshing + # and likely tear a hole in spacetime. + refresh_http = httplib2.Http() + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + request = google_auth_httplib2.Request(refresh_http) + return credentials.refresh(request) + else: + return credentials.refresh(refresh_http) + + +def apply_credentials(credentials, headers): + # oauth2client and google-auth have the same interface for this. + if not is_valid(credentials): + refresh_credentials(credentials) + return credentials.apply(headers) + + +def is_valid(credentials): + if HAS_GOOGLE_AUTH and isinstance(credentials, google.auth.credentials.Credentials): + return credentials.valid + else: + return ( + credentials.access_token is not None + and not credentials.access_token_expired + ) + + +def get_credentials_from_http(http): + if http is None: + return None + elif hasattr(http.request, "credentials"): + return http.request.credentials + elif hasattr(http, "credentials") and not isinstance( + http.credentials, httplib2.Credentials + ): + return http.credentials + else: + return None diff --git a/python_embeded/Lib/site-packages/googleapiclient/_helpers.py b/python_embeded/Lib/site-packages/googleapiclient/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..17b8a171514eb144ba67b75de58f526b36680ea1 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/_helpers.py @@ -0,0 +1,207 @@ +# Copyright 2015 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helper functions for commonly used utilities.""" + +import functools +import inspect +import logging +import urllib + +logger = logging.getLogger(__name__) + +POSITIONAL_WARNING = "WARNING" +POSITIONAL_EXCEPTION = "EXCEPTION" +POSITIONAL_IGNORE = "IGNORE" +POSITIONAL_SET = frozenset( + [POSITIONAL_WARNING, POSITIONAL_EXCEPTION, POSITIONAL_IGNORE] +) + +positional_parameters_enforcement = POSITIONAL_WARNING + +_SYM_LINK_MESSAGE = "File: {0}: Is a symbolic link." +_IS_DIR_MESSAGE = "{0}: Is a directory" +_MISSING_FILE_MESSAGE = "Cannot access {0}: No such file or directory" + + +def positional(max_positional_args): + """A decorator to declare that only the first N arguments may be positional. + + This decorator makes it easy to support Python 3 style keyword-only + parameters. For example, in Python 3 it is possible to write:: + + def fn(pos1, *, kwonly1=None, kwonly2=None): + ... + + All named parameters after ``*`` must be a keyword:: + + fn(10, 'kw1', 'kw2') # Raises exception. + fn(10, kwonly1='kw1') # Ok. + + Example + ^^^^^^^ + + To define a function like above, do:: + + @positional(1) + def fn(pos1, kwonly1=None, kwonly2=None): + ... + + If no default value is provided to a keyword argument, it becomes a + required keyword argument:: + + @positional(0) + def fn(required_kw): + ... + + This must be called with the keyword parameter:: + + fn() # Raises exception. + fn(10) # Raises exception. + fn(required_kw=10) # Ok. + + When defining instance or class methods always remember to account for + ``self`` and ``cls``:: + + class MyClass(object): + + @positional(2) + def my_method(self, pos1, kwonly1=None): + ... + + @classmethod + @positional(2) + def my_method(cls, pos1, kwonly1=None): + ... + + The positional decorator behavior is controlled by + ``_helpers.positional_parameters_enforcement``, which may be set to + ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or + ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do + nothing, respectively, if a declaration is violated. + + Args: + max_positional_arguments: Maximum number of positional arguments. All + parameters after this index must be + keyword only. + + Returns: + A decorator that prevents using arguments after max_positional_args + from being used as positional parameters. + + Raises: + TypeError: if a keyword-only argument is provided as a positional + parameter, but only if + _helpers.positional_parameters_enforcement is set to + POSITIONAL_EXCEPTION. + """ + + def positional_decorator(wrapped): + @functools.wraps(wrapped) + def positional_wrapper(*args, **kwargs): + if len(args) > max_positional_args: + plural_s = "" + if max_positional_args != 1: + plural_s = "s" + message = ( + "{function}() takes at most {args_max} positional " + "argument{plural} ({args_given} given)".format( + function=wrapped.__name__, + args_max=max_positional_args, + args_given=len(args), + plural=plural_s, + ) + ) + if positional_parameters_enforcement == POSITIONAL_EXCEPTION: + raise TypeError(message) + elif positional_parameters_enforcement == POSITIONAL_WARNING: + logger.warning(message) + return wrapped(*args, **kwargs) + + return positional_wrapper + + if isinstance(max_positional_args, int): + return positional_decorator + else: + args, _, _, defaults, _, _, _ = inspect.getfullargspec(max_positional_args) + return positional(len(args) - len(defaults))(max_positional_args) + + +def parse_unique_urlencoded(content): + """Parses unique key-value parameters from urlencoded content. + + Args: + content: string, URL-encoded key-value pairs. + + Returns: + dict, The key-value pairs from ``content``. + + Raises: + ValueError: if one of the keys is repeated. + """ + urlencoded_params = urllib.parse.parse_qs(content) + params = {} + for key, value in urlencoded_params.items(): + if len(value) != 1: + msg = "URL-encoded content contains a repeated value:" "%s -> %s" % ( + key, + ", ".join(value), + ) + raise ValueError(msg) + params[key] = value[0] + return params + + +def update_query_params(uri, params): + """Updates a URI with new query parameters. + + If a given key from ``params`` is repeated in the ``uri``, then + the URI will be considered invalid and an error will occur. + + If the URI is valid, then each value from ``params`` will + replace the corresponding value in the query parameters (if + it exists). + + Args: + uri: string, A valid URI, with potential existing query parameters. + params: dict, A dictionary of query parameters. + + Returns: + The same URI but with the new query parameters added. + """ + parts = urllib.parse.urlparse(uri) + query_params = parse_unique_urlencoded(parts.query) + query_params.update(params) + new_query = urllib.parse.urlencode(query_params) + new_parts = parts._replace(query=new_query) + return urllib.parse.urlunparse(new_parts) + + +def _add_query_parameter(url, name, value): + """Adds a query parameter to a url. + + Replaces the current value if it already exists in the URL. + + Args: + url: string, url to add the query parameter to. + name: string, query parameter name. + value: string, query parameter value. + + Returns: + Updated query parameter. Does not update the url if value is None. + """ + if value is None: + return url + else: + return update_query_params(url, {name: value}) diff --git a/python_embeded/Lib/site-packages/googleapiclient/channel.py b/python_embeded/Lib/site-packages/googleapiclient/channel.py new file mode 100644 index 0000000000000000000000000000000000000000..37bda1ea7e52630d2a775961816ea19d6174a62b --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/channel.py @@ -0,0 +1,315 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Channel notifications support. + +Classes and functions to support channel subscriptions and notifications +on those channels. + +Notes: + - This code is based on experimental APIs and is subject to change. + - Notification does not do deduplication of notification ids, that's up to + the receiver. + - Storing the Channel between calls is up to the caller. + + +Example setting up a channel: + + # Create a new channel that gets notifications via webhook. + channel = new_webhook_channel("https://example.com/my_web_hook") + + # Store the channel, keyed by 'channel.id'. Store it before calling the + # watch method because notifications may start arriving before the watch + # method returns. + ... + + resp = service.objects().watchAll( + bucket="some_bucket_id", body=channel.body()).execute() + channel.update(resp) + + # Store the channel, keyed by 'channel.id'. Store it after being updated + # since the resource_id value will now be correct, and that's needed to + # stop a subscription. + ... + + +An example Webhook implementation using webapp2. Note that webapp2 puts +headers in a case insensitive dictionary, as headers aren't guaranteed to +always be upper case. + + id = self.request.headers[X_GOOG_CHANNEL_ID] + + # Retrieve the channel by id. + channel = ... + + # Parse notification from the headers, including validating the id. + n = notification_from_headers(channel, self.request.headers) + + # Do app specific stuff with the notification here. + if n.resource_state == 'sync': + # Code to handle sync state. + elif n.resource_state == 'exists': + # Code to handle the exists state. + elif n.resource_state == 'not_exists': + # Code to handle the not exists state. + + +Example of unsubscribing. + + service.channels().stop(channel.body()).execute() +""" +from __future__ import absolute_import + +import datetime +import uuid + +from googleapiclient import _helpers as util +from googleapiclient import errors + +# The unix time epoch starts at midnight 1970. +EPOCH = datetime.datetime(1970, 1, 1) + +# Map the names of the parameters in the JSON channel description to +# the parameter names we use in the Channel class. +CHANNEL_PARAMS = { + "address": "address", + "id": "id", + "expiration": "expiration", + "params": "params", + "resourceId": "resource_id", + "resourceUri": "resource_uri", + "type": "type", + "token": "token", +} + +X_GOOG_CHANNEL_ID = "X-GOOG-CHANNEL-ID" +X_GOOG_MESSAGE_NUMBER = "X-GOOG-MESSAGE-NUMBER" +X_GOOG_RESOURCE_STATE = "X-GOOG-RESOURCE-STATE" +X_GOOG_RESOURCE_URI = "X-GOOG-RESOURCE-URI" +X_GOOG_RESOURCE_ID = "X-GOOG-RESOURCE-ID" + + +def _upper_header_keys(headers): + new_headers = {} + for k, v in headers.items(): + new_headers[k.upper()] = v + return new_headers + + +class Notification(object): + """A Notification from a Channel. + + Notifications are not usually constructed directly, but are returned + from functions like notification_from_headers(). + + Attributes: + message_number: int, The unique id number of this notification. + state: str, The state of the resource being monitored. + uri: str, The address of the resource being monitored. + resource_id: str, The unique identifier of the version of the resource at + this event. + """ + + @util.positional(5) + def __init__(self, message_number, state, resource_uri, resource_id): + """Notification constructor. + + Args: + message_number: int, The unique id number of this notification. + state: str, The state of the resource being monitored. Can be one + of "exists", "not_exists", or "sync". + resource_uri: str, The address of the resource being monitored. + resource_id: str, The identifier of the watched resource. + """ + self.message_number = message_number + self.state = state + self.resource_uri = resource_uri + self.resource_id = resource_id + + +class Channel(object): + """A Channel for notifications. + + Usually not constructed directly, instead it is returned from helper + functions like new_webhook_channel(). + + Attributes: + type: str, The type of delivery mechanism used by this channel. For + example, 'web_hook'. + id: str, A UUID for the channel. + token: str, An arbitrary string associated with the channel that + is delivered to the target address with each event delivered + over this channel. + address: str, The address of the receiving entity where events are + delivered. Specific to the channel type. + expiration: int, The time, in milliseconds from the epoch, when this + channel will expire. + params: dict, A dictionary of string to string, with additional parameters + controlling delivery channel behavior. + resource_id: str, An opaque id that identifies the resource that is + being watched. Stable across different API versions. + resource_uri: str, The canonicalized ID of the watched resource. + """ + + @util.positional(5) + def __init__( + self, + type, + id, + token, + address, + expiration=None, + params=None, + resource_id="", + resource_uri="", + ): + """Create a new Channel. + + In user code, this Channel constructor will not typically be called + manually since there are functions for creating channels for each specific + type with a more customized set of arguments to pass. + + Args: + type: str, The type of delivery mechanism used by this channel. For + example, 'web_hook'. + id: str, A UUID for the channel. + token: str, An arbitrary string associated with the channel that + is delivered to the target address with each event delivered + over this channel. + address: str, The address of the receiving entity where events are + delivered. Specific to the channel type. + expiration: int, The time, in milliseconds from the epoch, when this + channel will expire. + params: dict, A dictionary of string to string, with additional parameters + controlling delivery channel behavior. + resource_id: str, An opaque id that identifies the resource that is + being watched. Stable across different API versions. + resource_uri: str, The canonicalized ID of the watched resource. + """ + self.type = type + self.id = id + self.token = token + self.address = address + self.expiration = expiration + self.params = params + self.resource_id = resource_id + self.resource_uri = resource_uri + + def body(self): + """Build a body from the Channel. + + Constructs a dictionary that's appropriate for passing into watch() + methods as the value of body argument. + + Returns: + A dictionary representation of the channel. + """ + result = { + "id": self.id, + "token": self.token, + "type": self.type, + "address": self.address, + } + if self.params: + result["params"] = self.params + if self.resource_id: + result["resourceId"] = self.resource_id + if self.resource_uri: + result["resourceUri"] = self.resource_uri + if self.expiration: + result["expiration"] = self.expiration + + return result + + def update(self, resp): + """Update a channel with information from the response of watch(). + + When a request is sent to watch() a resource, the response returned + from the watch() request is a dictionary with updated channel information, + such as the resource_id, which is needed when stopping a subscription. + + Args: + resp: dict, The response from a watch() method. + """ + for json_name, param_name in CHANNEL_PARAMS.items(): + value = resp.get(json_name) + if value is not None: + setattr(self, param_name, value) + + +def notification_from_headers(channel, headers): + """Parse a notification from the webhook request headers, validate + the notification, and return a Notification object. + + Args: + channel: Channel, The channel that the notification is associated with. + headers: dict, A dictionary like object that contains the request headers + from the webhook HTTP request. + + Returns: + A Notification object. + + Raises: + errors.InvalidNotificationError if the notification is invalid. + ValueError if the X-GOOG-MESSAGE-NUMBER can't be converted to an int. + """ + headers = _upper_header_keys(headers) + channel_id = headers[X_GOOG_CHANNEL_ID] + if channel.id != channel_id: + raise errors.InvalidNotificationError( + "Channel id mismatch: %s != %s" % (channel.id, channel_id) + ) + else: + message_number = int(headers[X_GOOG_MESSAGE_NUMBER]) + state = headers[X_GOOG_RESOURCE_STATE] + resource_uri = headers[X_GOOG_RESOURCE_URI] + resource_id = headers[X_GOOG_RESOURCE_ID] + return Notification(message_number, state, resource_uri, resource_id) + + +@util.positional(2) +def new_webhook_channel(url, token=None, expiration=None, params=None): + """Create a new webhook Channel. + + Args: + url: str, URL to post notifications to. + token: str, An arbitrary string associated with the channel that + is delivered to the target address with each notification delivered + over this channel. + expiration: datetime.datetime, A time in the future when the channel + should expire. Can also be None if the subscription should use the + default expiration. Note that different services may have different + limits on how long a subscription lasts. Check the response from the + watch() method to see the value the service has set for an expiration + time. + params: dict, Extra parameters to pass on channel creation. Currently + not used for webhook channels. + """ + expiration_ms = 0 + if expiration: + delta = expiration - EPOCH + expiration_ms = ( + delta.microseconds / 1000 + (delta.seconds + delta.days * 24 * 3600) * 1000 + ) + if expiration_ms < 0: + expiration_ms = 0 + + return Channel( + "web_hook", + str(uuid.uuid4()), + token, + url, + expiration=expiration_ms, + params=params, + ) diff --git a/python_embeded/Lib/site-packages/googleapiclient/discovery.py b/python_embeded/Lib/site-packages/googleapiclient/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bbd77763c1218e42622ce6fb4f84ce6206e98f --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/discovery.py @@ -0,0 +1,1662 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Client for discovery based APIs. + +A client library for Google's discovery based APIs. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" +__all__ = ["build", "build_from_document", "fix_method_name", "key2param"] + +from collections import OrderedDict +import collections.abc + +# Standard library imports +import copy +from email.generator import BytesGenerator +from email.mime.multipart import MIMEMultipart +from email.mime.nonmultipart import MIMENonMultipart +import http.client as http_client +import io +import json +import keyword +import logging +import mimetypes +import os +import re +import urllib + +import google.api_core.client_options +from google.auth.exceptions import MutualTLSChannelError +from google.auth.transport import mtls +from google.oauth2 import service_account + +# Third-party imports +import httplib2 +import uritemplate + +try: + import google_auth_httplib2 +except ImportError: # pragma: NO COVER + google_auth_httplib2 = None + +try: + from google.api_core import universe + + HAS_UNIVERSE = True +except ImportError: + HAS_UNIVERSE = False + +# Local imports +from googleapiclient import _auth, mimeparse +from googleapiclient._helpers import _add_query_parameter, positional +from googleapiclient.errors import ( + HttpError, + InvalidJsonError, + MediaUploadSizeError, + UnacceptableMimeTypeError, + UnknownApiNameOrVersion, + UnknownFileType, +) +from googleapiclient.http import ( + BatchHttpRequest, + HttpMock, + HttpMockSequence, + HttpRequest, + MediaFileUpload, + MediaUpload, + build_http, +) +from googleapiclient.model import JsonModel, MediaModel, RawModel +from googleapiclient.schema import Schemas + +# The client library requires a version of httplib2 that supports RETRIES. +httplib2.RETRIES = 1 + +logger = logging.getLogger(__name__) + +URITEMPLATE = re.compile("{[^}]*}") +VARNAME = re.compile("[a-zA-Z0-9_-]+") +DISCOVERY_URI = ( + "https://www.googleapis.com/discovery/v1/apis/" "{api}/{apiVersion}/rest" +) +V1_DISCOVERY_URI = DISCOVERY_URI +V2_DISCOVERY_URI = ( + "https://{api}.googleapis.com/$discovery/rest?" "version={apiVersion}" +) +DEFAULT_METHOD_DOC = "A description of how to use this function" +HTTP_PAYLOAD_METHODS = frozenset(["PUT", "POST", "PATCH"]) + +_MEDIA_SIZE_BIT_SHIFTS = {"KB": 10, "MB": 20, "GB": 30, "TB": 40} +BODY_PARAMETER_DEFAULT_VALUE = {"description": "The request body.", "type": "object"} +MEDIA_BODY_PARAMETER_DEFAULT_VALUE = { + "description": ( + "The filename of the media request body, or an instance " + "of a MediaUpload object." + ), + "type": "string", + "required": False, +} +MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE = { + "description": ( + "The MIME type of the media request body, or an instance " + "of a MediaUpload object." + ), + "type": "string", + "required": False, +} +_PAGE_TOKEN_NAMES = ("pageToken", "nextPageToken") + +# Parameters controlling mTLS behavior. See https://google.aip.dev/auth/4114. +GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CERTIFICATE" +GOOGLE_API_USE_MTLS_ENDPOINT = "GOOGLE_API_USE_MTLS_ENDPOINT" +GOOGLE_CLOUD_UNIVERSE_DOMAIN = "GOOGLE_CLOUD_UNIVERSE_DOMAIN" +DEFAULT_UNIVERSE = "googleapis.com" +# Parameters accepted by the stack, but not visible via discovery. +# TODO(dhermes): Remove 'userip' in 'v2'. +STACK_QUERY_PARAMETERS = frozenset(["trace", "pp", "userip", "strict"]) +STACK_QUERY_PARAMETER_DEFAULT_VALUE = {"type": "string", "location": "query"} + + +class APICoreVersionError(ValueError): + def __init__(self): + message = ( + "google-api-core >= 2.18.0 is required to use the universe domain feature." + ) + super().__init__(message) + + +# Library-specific reserved words beyond Python keywords. +RESERVED_WORDS = frozenset(["body"]) + +# patch _write_lines to avoid munging '\r' into '\n' +# ( https://bugs.python.org/issue18886 https://bugs.python.org/issue19003 ) +class _BytesGenerator(BytesGenerator): + _write_lines = BytesGenerator.write + + +def fix_method_name(name): + """Fix method names to avoid '$' characters and reserved word conflicts. + + Args: + name: string, method name. + + Returns: + The name with '_' appended if the name is a reserved word and '$' and '-' + replaced with '_'. + """ + name = name.replace("$", "_").replace("-", "_") + if keyword.iskeyword(name) or name in RESERVED_WORDS: + return name + "_" + else: + return name + + +def key2param(key): + """Converts key names into parameter names. + + For example, converting "max-results" -> "max_results" + + Args: + key: string, the method key name. + + Returns: + A safe method name based on the key name. + """ + result = [] + key = list(key) + if not key[0].isalpha(): + result.append("x") + for c in key: + if c.isalnum(): + result.append(c) + else: + result.append("_") + + return "".join(result) + + +@positional(2) +def build( + serviceName, + version, + http=None, + discoveryServiceUrl=None, + developerKey=None, + model=None, + requestBuilder=HttpRequest, + credentials=None, + cache_discovery=True, + cache=None, + client_options=None, + adc_cert_path=None, + adc_key_path=None, + num_retries=1, + static_discovery=None, + always_use_jwt_access=False, +): + """Construct a Resource for interacting with an API. + + Construct a Resource object for interacting with an API. The serviceName and + version are the names from the Discovery service. + + Args: + serviceName: string, name of the service. + version: string, the version of the service. + http: httplib2.Http, An instance of httplib2.Http or something that acts + like it that HTTP requests will be made through. + discoveryServiceUrl: string, a URI Template that points to the location of + the discovery service. It should have two parameters {api} and + {apiVersion} that when filled in produce an absolute URI to the discovery + document for that service. + developerKey: string, key obtained from + https://code.google.com/apis/console. + model: googleapiclient.Model, converts to and from the wire format. + requestBuilder: googleapiclient.http.HttpRequest, encapsulator for an HTTP + request. + credentials: oauth2client.Credentials or + google.auth.credentials.Credentials, credentials to be used for + authentication. + cache_discovery: Boolean, whether or not to cache the discovery doc. + cache: googleapiclient.discovery_cache.base.CacheBase, an optional + cache object for the discovery documents. + client_options: Mapping object or google.api_core.client_options, client + options to set user options on the client. + (1) The API endpoint should be set through client_options. If API endpoint + is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used + to control which endpoint to use. + (2) client_cert_source is not supported, client cert should be provided using + client_encrypted_cert_source instead. In order to use the provided client + cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be + set to `true`. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_cert_path: str, client certificate file path to save the application + default client certificate for mTLS. This field is required if you want to + use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE` + environment variable must be set to `true` in order to use this field, + otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_key_path: str, client encrypted private key file path to save the + application default client encrypted private key for mTLS. This field is + required if you want to use the default client certificate. + `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to + `true` in order to use this field, otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + num_retries: Integer, number of times to retry discovery with + randomized exponential backoff in case of intermittent/connection issues. + static_discovery: Boolean, whether or not to use the static discovery docs + included in the library. The default value for `static_discovery` depends + on the value of `discoveryServiceUrl`. `static_discovery` will default to + `True` when `discoveryServiceUrl` is also not provided, otherwise it will + default to `False`. + always_use_jwt_access: Boolean, whether always use self signed JWT for service + account credentials. This only applies to + google.oauth2.service_account.Credentials. + + Returns: + A Resource object with methods for interacting with the service. + + Raises: + google.auth.exceptions.MutualTLSChannelError: if there are any problems + setting up mutual TLS channel. + """ + params = {"api": serviceName, "apiVersion": version} + + # The default value for `static_discovery` depends on the value of + # `discoveryServiceUrl`. `static_discovery` will default to `True` when + # `discoveryServiceUrl` is also not provided, otherwise it will default to + # `False`. This is added for backwards compatability with + # google-api-python-client 1.x which does not support the `static_discovery` + # parameter. + if static_discovery is None: + if discoveryServiceUrl is None: + static_discovery = True + else: + static_discovery = False + + if http is None: + discovery_http = build_http() + else: + discovery_http = http + + service = None + + for discovery_url in _discovery_service_uri_options(discoveryServiceUrl, version): + requested_url = uritemplate.expand(discovery_url, params) + + try: + content = _retrieve_discovery_doc( + requested_url, + discovery_http, + cache_discovery, + serviceName, + version, + cache, + developerKey, + num_retries=num_retries, + static_discovery=static_discovery, + ) + service = build_from_document( + content, + base=discovery_url, + http=http, + developerKey=developerKey, + model=model, + requestBuilder=requestBuilder, + credentials=credentials, + client_options=client_options, + adc_cert_path=adc_cert_path, + adc_key_path=adc_key_path, + always_use_jwt_access=always_use_jwt_access, + ) + break # exit if a service was created + except HttpError as e: + if e.resp.status == http_client.NOT_FOUND: + continue + else: + raise e + + # If discovery_http was created by this function, we are done with it + # and can safely close it + if http is None: + discovery_http.close() + + if service is None: + raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName, version)) + else: + return service + + +def _discovery_service_uri_options(discoveryServiceUrl, version): + """ + Returns Discovery URIs to be used for attempting to build the API Resource. + + Args: + discoveryServiceUrl: + string, the Original Discovery Service URL preferred by the customer. + version: + string, API Version requested + + Returns: + A list of URIs to be tried for the Service Discovery, in order. + """ + + if discoveryServiceUrl is not None: + return [discoveryServiceUrl] + if version is None: + # V1 Discovery won't work if the requested version is None + logger.warning( + "Discovery V1 does not support empty versions. Defaulting to V2..." + ) + return [V2_DISCOVERY_URI] + else: + return [DISCOVERY_URI, V2_DISCOVERY_URI] + + +def _retrieve_discovery_doc( + url, + http, + cache_discovery, + serviceName, + version, + cache=None, + developerKey=None, + num_retries=1, + static_discovery=True, +): + """Retrieves the discovery_doc from cache or the internet. + + Args: + url: string, the URL of the discovery document. + http: httplib2.Http, An instance of httplib2.Http or something that acts + like it through which HTTP requests will be made. + cache_discovery: Boolean, whether or not to cache the discovery doc. + serviceName: string, name of the service. + version: string, the version of the service. + cache: googleapiclient.discovery_cache.base.Cache, an optional cache + object for the discovery documents. + developerKey: string, Key for controlling API usage, generated + from the API Console. + num_retries: Integer, number of times to retry discovery with + randomized exponential backoff in case of intermittent/connection issues. + static_discovery: Boolean, whether or not to use the static discovery docs + included in the library. + + Returns: + A unicode string representation of the discovery document. + """ + from . import discovery_cache + + if cache_discovery: + if cache is None: + cache = discovery_cache.autodetect() + if cache: + content = cache.get(url) + if content: + return content + + # When `static_discovery=True`, use static discovery artifacts included + # with the library + if static_discovery: + content = discovery_cache.get_static_doc(serviceName, version) + if content: + return content + else: + raise UnknownApiNameOrVersion( + "name: %s version: %s" % (serviceName, version) + ) + + actual_url = url + # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment + # variable that contains the network address of the client sending the + # request. If it exists then add that to the request for the discovery + # document to avoid exceeding the quota on discovery requests. + if "REMOTE_ADDR" in os.environ: + actual_url = _add_query_parameter(url, "userIp", os.environ["REMOTE_ADDR"]) + if developerKey: + actual_url = _add_query_parameter(url, "key", developerKey) + logger.debug("URL being requested: GET %s", actual_url) + + # Execute this request with retries build into HttpRequest + # Note that it will already raise an error if we don't get a 2xx response + req = HttpRequest(http, HttpRequest.null_postproc, actual_url) + resp, content = req.execute(num_retries=num_retries) + + try: + content = content.decode("utf-8") + except AttributeError: + pass + + try: + service = json.loads(content) + except ValueError as e: + logger.error("Failed to parse as JSON: " + content) + raise InvalidJsonError() + if cache_discovery and cache: + cache.set(url, content) + return content + + +def _check_api_core_compatible_with_credentials_universe(credentials): + if not HAS_UNIVERSE: + credentials_universe = getattr(credentials, "universe_domain", None) + if credentials_universe and credentials_universe != DEFAULT_UNIVERSE: + raise APICoreVersionError + + +@positional(1) +def build_from_document( + service, + base=None, + future=None, + http=None, + developerKey=None, + model=None, + requestBuilder=HttpRequest, + credentials=None, + client_options=None, + adc_cert_path=None, + adc_key_path=None, + always_use_jwt_access=False, +): + """Create a Resource for interacting with an API. + + Same as `build()`, but constructs the Resource object from a discovery + document that is it given, as opposed to retrieving one over HTTP. + + Args: + service: string or object, the JSON discovery document describing the API. + The value passed in may either be the JSON string or the deserialized + JSON. + base: string, base URI for all HTTP requests, usually the discovery URI. + This parameter is no longer used as rootUrl and servicePath are included + within the discovery document. (deprecated) + future: string, discovery document with future capabilities (deprecated). + http: httplib2.Http, An instance of httplib2.Http or something that acts + like it that HTTP requests will be made through. + developerKey: string, Key for controlling API usage, generated + from the API Console. + model: Model class instance that serializes and de-serializes requests and + responses. + requestBuilder: Takes an http request and packages it up to be executed. + credentials: oauth2client.Credentials or + google.auth.credentials.Credentials, credentials to be used for + authentication. + client_options: Mapping object or google.api_core.client_options, client + options to set user options on the client. + (1) The API endpoint should be set through client_options. If API endpoint + is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used + to control which endpoint to use. + (2) client_cert_source is not supported, client cert should be provided using + client_encrypted_cert_source instead. In order to use the provided client + cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be + set to `true`. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_cert_path: str, client certificate file path to save the application + default client certificate for mTLS. This field is required if you want to + use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE` + environment variable must be set to `true` in order to use this field, + otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + adc_key_path: str, client encrypted private key file path to save the + application default client encrypted private key for mTLS. This field is + required if you want to use the default client certificate. + `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to + `true` in order to use this field, otherwise this field doesn't nothing. + More details on the environment variables are here: + https://google.aip.dev/auth/4114 + always_use_jwt_access: Boolean, whether always use self signed JWT for service + account credentials. This only applies to + google.oauth2.service_account.Credentials. + + Returns: + A Resource object with methods for interacting with the service. + + Raises: + google.auth.exceptions.MutualTLSChannelError: if there are any problems + setting up mutual TLS channel. + """ + + if client_options is None: + client_options = google.api_core.client_options.ClientOptions() + if isinstance(client_options, collections.abc.Mapping): + client_options = google.api_core.client_options.from_dict(client_options) + + if http is not None: + # if http is passed, the user cannot provide credentials + banned_options = [ + (credentials, "credentials"), + (client_options.credentials_file, "client_options.credentials_file"), + ] + for option, name in banned_options: + if option is not None: + raise ValueError( + "Arguments http and {} are mutually exclusive".format(name) + ) + + if isinstance(service, str): + service = json.loads(service) + elif isinstance(service, bytes): + service = json.loads(service.decode("utf-8")) + + if "rootUrl" not in service and isinstance(http, (HttpMock, HttpMockSequence)): + logger.error( + "You are using HttpMock or HttpMockSequence without" + + "having the service discovery doc in cache. Try calling " + + "build() without mocking once first to populate the " + + "cache." + ) + raise InvalidJsonError() + + # If an API Endpoint is provided on client options, use that as the base URL + base = urllib.parse.urljoin(service["rootUrl"], service["servicePath"]) + universe_domain = None + if HAS_UNIVERSE: + universe_domain_env = os.getenv(GOOGLE_CLOUD_UNIVERSE_DOMAIN, None) + universe_domain = universe.determine_domain( + client_options.universe_domain, universe_domain_env + ) + base = base.replace(universe.DEFAULT_UNIVERSE, universe_domain) + else: + client_universe = getattr(client_options, "universe_domain", None) + if client_universe: + raise APICoreVersionError + + audience_for_self_signed_jwt = base + if client_options.api_endpoint: + base = client_options.api_endpoint + + schema = Schemas(service) + + # If the http client is not specified, then we must construct an http client + # to make requests. If the service has scopes, then we also need to setup + # authentication. + if http is None: + # Does the service require scopes? + scopes = list( + service.get("auth", {}).get("oauth2", {}).get("scopes", {}).keys() + ) + + # If so, then the we need to setup authentication if no developerKey is + # specified. + if scopes and not developerKey: + # Make sure the user didn't pass multiple credentials + if client_options.credentials_file and credentials: + raise google.api_core.exceptions.DuplicateCredentialArgs( + "client_options.credentials_file and credentials are mutually exclusive." + ) + # Check for credentials file via client options + if client_options.credentials_file: + credentials = _auth.credentials_from_file( + client_options.credentials_file, + scopes=client_options.scopes, + quota_project_id=client_options.quota_project_id, + ) + # If the user didn't pass in credentials, attempt to acquire application + # default credentials. + if credentials is None: + credentials = _auth.default_credentials( + scopes=client_options.scopes, + quota_project_id=client_options.quota_project_id, + ) + + # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com". + _check_api_core_compatible_with_credentials_universe(credentials) + + # The credentials need to be scoped. + # If the user provided scopes via client_options don't override them + if not client_options.scopes: + credentials = _auth.with_scopes(credentials, scopes) + + # For google-auth service account credentials, enable self signed JWT if + # always_use_jwt_access is true. + if ( + credentials + and isinstance(credentials, service_account.Credentials) + and always_use_jwt_access + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(always_use_jwt_access) + credentials._create_self_signed_jwt(audience_for_self_signed_jwt) + + # If credentials are provided, create an authorized http instance; + # otherwise, skip authentication. + if credentials: + http = _auth.authorized_http(credentials) + + # If the service doesn't require scopes then there is no need for + # authentication. + else: + http = build_http() + + # Obtain client cert and create mTLS http channel if cert exists. + client_cert_to_use = None + use_client_cert = os.getenv(GOOGLE_API_USE_CLIENT_CERTIFICATE, "false") + if not use_client_cert in ("true", "false"): + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_CLIENT_CERTIFICATE value. Accepted values: true, false" + ) + if client_options and client_options.client_cert_source: + raise MutualTLSChannelError( + "ClientOptions.client_cert_source is not supported, please use ClientOptions.client_encrypted_cert_source." + ) + if use_client_cert == "true": + if ( + client_options + and hasattr(client_options, "client_encrypted_cert_source") + and client_options.client_encrypted_cert_source + ): + client_cert_to_use = client_options.client_encrypted_cert_source + elif ( + adc_cert_path and adc_key_path and mtls.has_default_client_cert_source() + ): + client_cert_to_use = mtls.default_client_encrypted_cert_source( + adc_cert_path, adc_key_path + ) + if client_cert_to_use: + cert_path, key_path, passphrase = client_cert_to_use() + + # The http object we built could be google_auth_httplib2.AuthorizedHttp + # or httplib2.Http. In the first case we need to extract the wrapped + # httplib2.Http object from google_auth_httplib2.AuthorizedHttp. + http_channel = ( + http.http + if google_auth_httplib2 + and isinstance(http, google_auth_httplib2.AuthorizedHttp) + else http + ) + http_channel.add_certificate(key_path, cert_path, "", passphrase) + + # If user doesn't provide api endpoint via client options, decide which + # api endpoint to use. + if "mtlsRootUrl" in service and ( + not client_options or not client_options.api_endpoint + ): + mtls_endpoint = urllib.parse.urljoin( + service["mtlsRootUrl"], service["servicePath"] + ) + use_mtls_endpoint = os.getenv(GOOGLE_API_USE_MTLS_ENDPOINT, "auto") + + if not use_mtls_endpoint in ("never", "auto", "always"): + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Switch to mTLS endpoint, if environment variable is "always", or + # environment varibable is "auto" and client cert exists. + if use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_to_use + ): + if HAS_UNIVERSE and universe_domain != universe.DEFAULT_UNIVERSE: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {universe.DEFAULT_UNIVERSE}." + ) + base = mtls_endpoint + else: + # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com". + http_credentials = getattr(http, "credentials", None) + _check_api_core_compatible_with_credentials_universe(http_credentials) + + if model is None: + features = service.get("features", []) + model = JsonModel("dataWrapper" in features) + + return Resource( + http=http, + baseUrl=base, + model=model, + developerKey=developerKey, + requestBuilder=requestBuilder, + resourceDesc=service, + rootDesc=service, + schema=schema, + universe_domain=universe_domain, + ) + + +def _cast(value, schema_type): + """Convert value to a string based on JSON Schema type. + + See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on + JSON Schema. + + Args: + value: any, the value to convert + schema_type: string, the type that value should be interpreted as + + Returns: + A string representation of 'value' based on the schema_type. + """ + if schema_type == "string": + if type(value) == type("") or type(value) == type(""): + return value + else: + return str(value) + elif schema_type == "integer": + return str(int(value)) + elif schema_type == "number": + return str(float(value)) + elif schema_type == "boolean": + return str(bool(value)).lower() + else: + if type(value) == type("") or type(value) == type(""): + return value + else: + return str(value) + + +def _media_size_to_long(maxSize): + """Convert a string media size, such as 10GB or 3TB into an integer. + + Args: + maxSize: string, size as a string, such as 2MB or 7GB. + + Returns: + The size as an integer value. + """ + if len(maxSize) < 2: + return 0 + units = maxSize[-2:].upper() + bit_shift = _MEDIA_SIZE_BIT_SHIFTS.get(units) + if bit_shift is not None: + return int(maxSize[:-2]) << bit_shift + else: + return int(maxSize) + + +def _media_path_url_from_info(root_desc, path_url): + """Creates an absolute media path URL. + + Constructed using the API root URI and service path from the discovery + document and the relative path for the API method. + + Args: + root_desc: Dictionary; the entire original deserialized discovery document. + path_url: String; the relative URL for the API method. Relative to the API + root, which is specified in the discovery document. + + Returns: + String; the absolute URI for media upload for the API method. + """ + return "%(root)supload/%(service_path)s%(path)s" % { + "root": root_desc["rootUrl"], + "service_path": root_desc["servicePath"], + "path": path_url, + } + + +def _fix_up_parameters(method_desc, root_desc, http_method, schema): + """Updates parameters of an API method with values specific to this library. + + Specifically, adds whatever global parameters are specified by the API to the + parameters for the individual method. Also adds parameters which don't + appear in the discovery document, but are available to all discovery based + APIs (these are listed in STACK_QUERY_PARAMETERS). + + SIDE EFFECTS: This updates the parameters dictionary object in the method + description. + + Args: + method_desc: Dictionary with metadata describing an API method. Value comes + from the dictionary of methods stored in the 'methods' key in the + deserialized discovery document. + root_desc: Dictionary; the entire original deserialized discovery document. + http_method: String; the HTTP method used to call the API method described + in method_desc. + schema: Object, mapping of schema names to schema descriptions. + + Returns: + The updated Dictionary stored in the 'parameters' key of the method + description dictionary. + """ + parameters = method_desc.setdefault("parameters", {}) + + # Add in the parameters common to all methods. + for name, description in root_desc.get("parameters", {}).items(): + parameters[name] = description + + # Add in undocumented query parameters. + for name in STACK_QUERY_PARAMETERS: + parameters[name] = STACK_QUERY_PARAMETER_DEFAULT_VALUE.copy() + + # Add 'body' (our own reserved word) to parameters if the method supports + # a request payload. + if http_method in HTTP_PAYLOAD_METHODS and "request" in method_desc: + body = BODY_PARAMETER_DEFAULT_VALUE.copy() + body.update(method_desc["request"]) + parameters["body"] = body + + return parameters + + +def _fix_up_media_upload(method_desc, root_desc, path_url, parameters): + """Adds 'media_body' and 'media_mime_type' parameters if supported by method. + + SIDE EFFECTS: If there is a 'mediaUpload' in the method description, adds + 'media_upload' key to parameters. + + Args: + method_desc: Dictionary with metadata describing an API method. Value comes + from the dictionary of methods stored in the 'methods' key in the + deserialized discovery document. + root_desc: Dictionary; the entire original deserialized discovery document. + path_url: String; the relative URL for the API method. Relative to the API + root, which is specified in the discovery document. + parameters: A dictionary describing method parameters for method described + in method_desc. + + Returns: + Triple (accept, max_size, media_path_url) where: + - accept is a list of strings representing what content types are + accepted for media upload. Defaults to empty list if not in the + discovery document. + - max_size is a long representing the max size in bytes allowed for a + media upload. Defaults to 0L if not in the discovery document. + - media_path_url is a String; the absolute URI for media upload for the + API method. Constructed using the API root URI and service path from + the discovery document and the relative path for the API method. If + media upload is not supported, this is None. + """ + media_upload = method_desc.get("mediaUpload", {}) + accept = media_upload.get("accept", []) + max_size = _media_size_to_long(media_upload.get("maxSize", "")) + media_path_url = None + + if media_upload: + media_path_url = _media_path_url_from_info(root_desc, path_url) + parameters["media_body"] = MEDIA_BODY_PARAMETER_DEFAULT_VALUE.copy() + parameters["media_mime_type"] = MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE.copy() + + return accept, max_size, media_path_url + + +def _fix_up_method_description(method_desc, root_desc, schema): + """Updates a method description in a discovery document. + + SIDE EFFECTS: Changes the parameters dictionary in the method description with + extra parameters which are used locally. + + Args: + method_desc: Dictionary with metadata describing an API method. Value comes + from the dictionary of methods stored in the 'methods' key in the + deserialized discovery document. + root_desc: Dictionary; the entire original deserialized discovery document. + schema: Object, mapping of schema names to schema descriptions. + + Returns: + Tuple (path_url, http_method, method_id, accept, max_size, media_path_url) + where: + - path_url is a String; the relative URL for the API method. Relative to + the API root, which is specified in the discovery document. + - http_method is a String; the HTTP method used to call the API method + described in the method description. + - method_id is a String; the name of the RPC method associated with the + API method, and is in the method description in the 'id' key. + - accept is a list of strings representing what content types are + accepted for media upload. Defaults to empty list if not in the + discovery document. + - max_size is a long representing the max size in bytes allowed for a + media upload. Defaults to 0L if not in the discovery document. + - media_path_url is a String; the absolute URI for media upload for the + API method. Constructed using the API root URI and service path from + the discovery document and the relative path for the API method. If + media upload is not supported, this is None. + """ + path_url = method_desc["path"] + http_method = method_desc["httpMethod"] + method_id = method_desc["id"] + + parameters = _fix_up_parameters(method_desc, root_desc, http_method, schema) + # Order is important. `_fix_up_media_upload` needs `method_desc` to have a + # 'parameters' key and needs to know if there is a 'body' parameter because it + # also sets a 'media_body' parameter. + accept, max_size, media_path_url = _fix_up_media_upload( + method_desc, root_desc, path_url, parameters + ) + + return path_url, http_method, method_id, accept, max_size, media_path_url + + +def _fix_up_media_path_base_url(media_path_url, base_url): + """ + Update the media upload base url if its netloc doesn't match base url netloc. + + This can happen in case the base url was overridden by + client_options.api_endpoint. + + Args: + media_path_url: String; the absolute URI for media upload. + base_url: string, base URL for the API. All requests are relative to this URI. + + Returns: + String; the absolute URI for media upload. + """ + parsed_media_url = urllib.parse.urlparse(media_path_url) + parsed_base_url = urllib.parse.urlparse(base_url) + if parsed_media_url.netloc == parsed_base_url.netloc: + return media_path_url + return urllib.parse.urlunparse( + parsed_media_url._replace(netloc=parsed_base_url.netloc) + ) + + +def _urljoin(base, url): + """Custom urljoin replacement supporting : before / in url.""" + # In general, it's unsafe to simply join base and url. However, for + # the case of discovery documents, we know: + # * base will never contain params, query, or fragment + # * url will never contain a scheme or net_loc. + # In general, this means we can safely join on /; we just need to + # ensure we end up with precisely one / joining base and url. The + # exception here is the case of media uploads, where url will be an + # absolute url. + if url.startswith("http://") or url.startswith("https://"): + return urllib.parse.urljoin(base, url) + new_base = base if base.endswith("/") else base + "/" + new_url = url[1:] if url.startswith("/") else url + return new_base + new_url + + +# TODO(dhermes): Convert this class to ResourceMethod and make it callable +class ResourceMethodParameters(object): + """Represents the parameters associated with a method. + + Attributes: + argmap: Map from method parameter name (string) to query parameter name + (string). + required_params: List of required parameters (represented by parameter + name as string). + repeated_params: List of repeated parameters (represented by parameter + name as string). + pattern_params: Map from method parameter name (string) to regular + expression (as a string). If the pattern is set for a parameter, the + value for that parameter must match the regular expression. + query_params: List of parameters (represented by parameter name as string) + that will be used in the query string. + path_params: Set of parameters (represented by parameter name as string) + that will be used in the base URL path. + param_types: Map from method parameter name (string) to parameter type. Type + can be any valid JSON schema type; valid values are 'any', 'array', + 'boolean', 'integer', 'number', 'object', or 'string'. Reference: + http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1 + enum_params: Map from method parameter name (string) to list of strings, + where each list of strings is the list of acceptable enum values. + """ + + def __init__(self, method_desc): + """Constructor for ResourceMethodParameters. + + Sets default values and defers to set_parameters to populate. + + Args: + method_desc: Dictionary with metadata describing an API method. Value + comes from the dictionary of methods stored in the 'methods' key in + the deserialized discovery document. + """ + self.argmap = {} + self.required_params = [] + self.repeated_params = [] + self.pattern_params = {} + self.query_params = [] + # TODO(dhermes): Change path_params to a list if the extra URITEMPLATE + # parsing is gotten rid of. + self.path_params = set() + self.param_types = {} + self.enum_params = {} + + self.set_parameters(method_desc) + + def set_parameters(self, method_desc): + """Populates maps and lists based on method description. + + Iterates through each parameter for the method and parses the values from + the parameter dictionary. + + Args: + method_desc: Dictionary with metadata describing an API method. Value + comes from the dictionary of methods stored in the 'methods' key in + the deserialized discovery document. + """ + parameters = method_desc.get("parameters", {}) + sorted_parameters = OrderedDict(sorted(parameters.items())) + for arg, desc in sorted_parameters.items(): + param = key2param(arg) + self.argmap[param] = arg + + if desc.get("pattern"): + self.pattern_params[param] = desc["pattern"] + if desc.get("enum"): + self.enum_params[param] = desc["enum"] + if desc.get("required"): + self.required_params.append(param) + if desc.get("repeated"): + self.repeated_params.append(param) + if desc.get("location") == "query": + self.query_params.append(param) + if desc.get("location") == "path": + self.path_params.add(param) + self.param_types[param] = desc.get("type", "string") + + # TODO(dhermes): Determine if this is still necessary. Discovery based APIs + # should have all path parameters already marked with + # 'location: path'. + for match in URITEMPLATE.finditer(method_desc["path"]): + for namematch in VARNAME.finditer(match.group(0)): + name = key2param(namematch.group(0)) + self.path_params.add(name) + if name in self.query_params: + self.query_params.remove(name) + + +def createMethod(methodName, methodDesc, rootDesc, schema): + """Creates a method for attaching to a Resource. + + Args: + methodName: string, name of the method to use. + methodDesc: object, fragment of deserialized discovery document that + describes the method. + rootDesc: object, the entire deserialized discovery document. + schema: object, mapping of schema names to schema descriptions. + """ + methodName = fix_method_name(methodName) + ( + pathUrl, + httpMethod, + methodId, + accept, + maxSize, + mediaPathUrl, + ) = _fix_up_method_description(methodDesc, rootDesc, schema) + + parameters = ResourceMethodParameters(methodDesc) + + def method(self, **kwargs): + # Don't bother with doc string, it will be over-written by createMethod. + + # Validate credentials for the configured universe. + self._validate_credentials() + + for name in kwargs: + if name not in parameters.argmap: + raise TypeError("Got an unexpected keyword argument {}".format(name)) + + # Remove args that have a value of None. + keys = list(kwargs.keys()) + for name in keys: + if kwargs[name] is None: + del kwargs[name] + + for name in parameters.required_params: + if name not in kwargs: + # temporary workaround for non-paging methods incorrectly requiring + # page token parameter (cf. drive.changes.watch vs. drive.changes.list) + if name not in _PAGE_TOKEN_NAMES or _findPageTokenName( + _methodProperties(methodDesc, schema, "response") + ): + raise TypeError('Missing required parameter "%s"' % name) + + for name, regex in parameters.pattern_params.items(): + if name in kwargs: + if isinstance(kwargs[name], str): + pvalues = [kwargs[name]] + else: + pvalues = kwargs[name] + for pvalue in pvalues: + if re.match(regex, pvalue) is None: + raise TypeError( + 'Parameter "%s" value "%s" does not match the pattern "%s"' + % (name, pvalue, regex) + ) + + for name, enums in parameters.enum_params.items(): + if name in kwargs: + # We need to handle the case of a repeated enum + # name differently, since we want to handle both + # arg='value' and arg=['value1', 'value2'] + if name in parameters.repeated_params and not isinstance( + kwargs[name], str + ): + values = kwargs[name] + else: + values = [kwargs[name]] + for value in values: + if value not in enums: + raise TypeError( + 'Parameter "%s" value "%s" is not an allowed value in "%s"' + % (name, value, str(enums)) + ) + + actual_query_params = {} + actual_path_params = {} + for key, value in kwargs.items(): + to_type = parameters.param_types.get(key, "string") + # For repeated parameters we cast each member of the list. + if key in parameters.repeated_params and type(value) == type([]): + cast_value = [_cast(x, to_type) for x in value] + else: + cast_value = _cast(value, to_type) + if key in parameters.query_params: + actual_query_params[parameters.argmap[key]] = cast_value + if key in parameters.path_params: + actual_path_params[parameters.argmap[key]] = cast_value + body_value = kwargs.get("body", None) + media_filename = kwargs.get("media_body", None) + media_mime_type = kwargs.get("media_mime_type", None) + + if self._developerKey: + actual_query_params["key"] = self._developerKey + + model = self._model + if methodName.endswith("_media"): + model = MediaModel() + elif "response" not in methodDesc: + model = RawModel() + + api_version = methodDesc.get("apiVersion", None) + + headers = {} + headers, params, query, body = model.request( + headers, actual_path_params, actual_query_params, body_value, api_version + ) + + expanded_url = uritemplate.expand(pathUrl, params) + url = _urljoin(self._baseUrl, expanded_url + query) + + resumable = None + multipart_boundary = "" + + if media_filename: + # Ensure we end up with a valid MediaUpload object. + if isinstance(media_filename, str): + if media_mime_type is None: + logger.warning( + "media_mime_type argument not specified: trying to auto-detect for %s", + media_filename, + ) + media_mime_type, _ = mimetypes.guess_type(media_filename) + if media_mime_type is None: + raise UnknownFileType(media_filename) + if not mimeparse.best_match([media_mime_type], ",".join(accept)): + raise UnacceptableMimeTypeError(media_mime_type) + media_upload = MediaFileUpload(media_filename, mimetype=media_mime_type) + elif isinstance(media_filename, MediaUpload): + media_upload = media_filename + else: + raise TypeError("media_filename must be str or MediaUpload.") + + # Check the maxSize + if media_upload.size() is not None and media_upload.size() > maxSize > 0: + raise MediaUploadSizeError("Media larger than: %s" % maxSize) + + # Use the media path uri for media uploads + expanded_url = uritemplate.expand(mediaPathUrl, params) + url = _urljoin(self._baseUrl, expanded_url + query) + url = _fix_up_media_path_base_url(url, self._baseUrl) + if media_upload.resumable(): + url = _add_query_parameter(url, "uploadType", "resumable") + + if media_upload.resumable(): + # This is all we need to do for resumable, if the body exists it gets + # sent in the first request, otherwise an empty body is sent. + resumable = media_upload + else: + # A non-resumable upload + if body is None: + # This is a simple media upload + headers["content-type"] = media_upload.mimetype() + body = media_upload.getbytes(0, media_upload.size()) + url = _add_query_parameter(url, "uploadType", "media") + else: + # This is a multipart/related upload. + msgRoot = MIMEMultipart("related") + # msgRoot should not write out it's own headers + setattr(msgRoot, "_write_headers", lambda self: None) + + # attach the body as one part + msg = MIMENonMultipart(*headers["content-type"].split("/")) + msg.set_payload(body) + msgRoot.attach(msg) + + # attach the media as the second part + msg = MIMENonMultipart(*media_upload.mimetype().split("/")) + msg["Content-Transfer-Encoding"] = "binary" + + payload = media_upload.getbytes(0, media_upload.size()) + msg.set_payload(payload) + msgRoot.attach(msg) + # encode the body: note that we can't use `as_string`, because + # it plays games with `From ` lines. + fp = io.BytesIO() + g = _BytesGenerator(fp, mangle_from_=False) + g.flatten(msgRoot, unixfrom=False) + body = fp.getvalue() + + multipart_boundary = msgRoot.get_boundary() + headers["content-type"] = ( + "multipart/related; " 'boundary="%s"' + ) % multipart_boundary + url = _add_query_parameter(url, "uploadType", "multipart") + + logger.debug("URL being requested: %s %s" % (httpMethod, url)) + return self._requestBuilder( + self._http, + model.response, + url, + method=httpMethod, + body=body, + headers=headers, + methodId=methodId, + resumable=resumable, + ) + + docs = [methodDesc.get("description", DEFAULT_METHOD_DOC), "\n\n"] + if len(parameters.argmap) > 0: + docs.append("Args:\n") + + # Skip undocumented params and params common to all methods. + skip_parameters = list(rootDesc.get("parameters", {}).keys()) + skip_parameters.extend(STACK_QUERY_PARAMETERS) + + all_args = list(parameters.argmap.keys()) + args_ordered = [key2param(s) for s in methodDesc.get("parameterOrder", [])] + + # Move body to the front of the line. + if "body" in all_args: + args_ordered.append("body") + + for name in sorted(all_args): + if name not in args_ordered: + args_ordered.append(name) + + for arg in args_ordered: + if arg in skip_parameters: + continue + + repeated = "" + if arg in parameters.repeated_params: + repeated = " (repeated)" + required = "" + if arg in parameters.required_params: + required = " (required)" + paramdesc = methodDesc["parameters"][parameters.argmap[arg]] + paramdoc = paramdesc.get("description", "A parameter") + if "$ref" in paramdesc: + docs.append( + (" %s: object, %s%s%s\n The object takes the form of:\n\n%s\n\n") + % ( + arg, + paramdoc, + required, + repeated, + schema.prettyPrintByName(paramdesc["$ref"]), + ) + ) + else: + paramtype = paramdesc.get("type", "string") + docs.append( + " %s: %s, %s%s%s\n" % (arg, paramtype, paramdoc, required, repeated) + ) + enum = paramdesc.get("enum", []) + enumDesc = paramdesc.get("enumDescriptions", []) + if enum and enumDesc: + docs.append(" Allowed values\n") + for (name, desc) in zip(enum, enumDesc): + docs.append(" %s - %s\n" % (name, desc)) + if "response" in methodDesc: + if methodName.endswith("_media"): + docs.append("\nReturns:\n The media object as a string.\n\n ") + else: + docs.append("\nReturns:\n An object of the form:\n\n ") + docs.append(schema.prettyPrintSchema(methodDesc["response"])) + + setattr(method, "__doc__", "".join(docs)) + return (methodName, method) + + +def createNextMethod( + methodName, + pageTokenName="pageToken", + nextPageTokenName="nextPageToken", + isPageTokenParameter=True, +): + """Creates any _next methods for attaching to a Resource. + + The _next methods allow for easy iteration through list() responses. + + Args: + methodName: string, name of the method to use. + pageTokenName: string, name of request page token field. + nextPageTokenName: string, name of response page token field. + isPageTokenParameter: Boolean, True if request page token is a query + parameter, False if request page token is a field of the request body. + """ + methodName = fix_method_name(methodName) + + def methodNext(self, previous_request, previous_response): + """Retrieves the next page of results. + + Args: + previous_request: The request for the previous page. (required) + previous_response: The response from the request for the previous page. (required) + + Returns: + A request object that you can call 'execute()' on to request the next + page. Returns None if there are no more items in the collection. + """ + # Retrieve nextPageToken from previous_response + # Use as pageToken in previous_request to create new request. + + nextPageToken = previous_response.get(nextPageTokenName, None) + if not nextPageToken: + return None + + request = copy.copy(previous_request) + + if isPageTokenParameter: + # Replace pageToken value in URI + request.uri = _add_query_parameter( + request.uri, pageTokenName, nextPageToken + ) + logger.debug("Next page request URL: %s %s" % (methodName, request.uri)) + else: + # Replace pageToken value in request body + model = self._model + body = model.deserialize(request.body) + body[pageTokenName] = nextPageToken + request.body = model.serialize(body) + request.body_size = len(request.body) + if "content-length" in request.headers: + del request.headers["content-length"] + logger.debug("Next page request body: %s %s" % (methodName, body)) + + return request + + return (methodName, methodNext) + + +class Resource(object): + """A class for interacting with a resource.""" + + def __init__( + self, + http, + baseUrl, + model, + requestBuilder, + developerKey, + resourceDesc, + rootDesc, + schema, + universe_domain=universe.DEFAULT_UNIVERSE if HAS_UNIVERSE else "", + ): + """Build a Resource from the API description. + + Args: + http: httplib2.Http, Object to make http requests with. + baseUrl: string, base URL for the API. All requests are relative to this + URI. + model: googleapiclient.Model, converts to and from the wire format. + requestBuilder: class or callable that instantiates an + googleapiclient.HttpRequest object. + developerKey: string, key obtained from + https://code.google.com/apis/console + resourceDesc: object, section of deserialized discovery document that + describes a resource. Note that the top level discovery document + is considered a resource. + rootDesc: object, the entire deserialized discovery document. + schema: object, mapping of schema names to schema descriptions. + universe_domain: string, the universe for the API. The default universe + is "googleapis.com". + """ + self._dynamic_attrs = [] + + self._http = http + self._baseUrl = baseUrl + self._model = model + self._developerKey = developerKey + self._requestBuilder = requestBuilder + self._resourceDesc = resourceDesc + self._rootDesc = rootDesc + self._schema = schema + self._universe_domain = universe_domain + self._credentials_validated = False + + self._set_service_methods() + + def _set_dynamic_attr(self, attr_name, value): + """Sets an instance attribute and tracks it in a list of dynamic attributes. + + Args: + attr_name: string; The name of the attribute to be set + value: The value being set on the object and tracked in the dynamic cache. + """ + self._dynamic_attrs.append(attr_name) + self.__dict__[attr_name] = value + + def __getstate__(self): + """Trim the state down to something that can be pickled. + + Uses the fact that the instance variable _dynamic_attrs holds attrs that + will be wiped and restored on pickle serialization. + """ + state_dict = copy.copy(self.__dict__) + for dynamic_attr in self._dynamic_attrs: + del state_dict[dynamic_attr] + del state_dict["_dynamic_attrs"] + return state_dict + + def __setstate__(self, state): + """Reconstitute the state of the object from being pickled. + + Uses the fact that the instance variable _dynamic_attrs holds attrs that + will be wiped and restored on pickle serialization. + """ + self.__dict__.update(state) + self._dynamic_attrs = [] + self._set_service_methods() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, exc_tb): + self.close() + + def close(self): + """Close httplib2 connections.""" + # httplib2 leaves sockets open by default. + # Cleanup using the `close` method. + # https://github.com/httplib2/httplib2/issues/148 + self._http.close() + + def _set_service_methods(self): + self._add_basic_methods(self._resourceDesc, self._rootDesc, self._schema) + self._add_nested_resources(self._resourceDesc, self._rootDesc, self._schema) + self._add_next_methods(self._resourceDesc, self._schema) + + def _add_basic_methods(self, resourceDesc, rootDesc, schema): + # If this is the root Resource, add a new_batch_http_request() method. + if resourceDesc == rootDesc: + batch_uri = "%s%s" % ( + rootDesc["rootUrl"], + rootDesc.get("batchPath", "batch"), + ) + + def new_batch_http_request(callback=None): + """Create a BatchHttpRequest object based on the discovery document. + + Args: + callback: callable, A callback to be called for each response, of the + form callback(id, response, exception). The first parameter is the + request id, and the second is the deserialized response object. The + third is an apiclient.errors.HttpError exception object if an HTTP + error occurred while processing the request, or None if no error + occurred. + + Returns: + A BatchHttpRequest object based on the discovery document. + """ + return BatchHttpRequest(callback=callback, batch_uri=batch_uri) + + self._set_dynamic_attr("new_batch_http_request", new_batch_http_request) + + # Add basic methods to Resource + if "methods" in resourceDesc: + for methodName, methodDesc in resourceDesc["methods"].items(): + fixedMethodName, method = createMethod( + methodName, methodDesc, rootDesc, schema + ) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + # Add in _media methods. The functionality of the attached method will + # change when it sees that the method name ends in _media. + if methodDesc.get("supportsMediaDownload", False): + fixedMethodName, method = createMethod( + methodName + "_media", methodDesc, rootDesc, schema + ) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + + def _add_nested_resources(self, resourceDesc, rootDesc, schema): + # Add in nested resources + if "resources" in resourceDesc: + + def createResourceMethod(methodName, methodDesc): + """Create a method on the Resource to access a nested Resource. + + Args: + methodName: string, name of the method to use. + methodDesc: object, fragment of deserialized discovery document that + describes the method. + """ + methodName = fix_method_name(methodName) + + def methodResource(self): + return Resource( + http=self._http, + baseUrl=self._baseUrl, + model=self._model, + developerKey=self._developerKey, + requestBuilder=self._requestBuilder, + resourceDesc=methodDesc, + rootDesc=rootDesc, + schema=schema, + universe_domain=self._universe_domain, + ) + + setattr(methodResource, "__doc__", "A collection resource.") + setattr(methodResource, "__is_resource__", True) + + return (methodName, methodResource) + + for methodName, methodDesc in resourceDesc["resources"].items(): + fixedMethodName, method = createResourceMethod(methodName, methodDesc) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + + def _add_next_methods(self, resourceDesc, schema): + # Add _next() methods if and only if one of the names 'pageToken' or + # 'nextPageToken' occurs among the fields of both the method's response + # type either the method's request (query parameters) or request body. + if "methods" not in resourceDesc: + return + for methodName, methodDesc in resourceDesc["methods"].items(): + nextPageTokenName = _findPageTokenName( + _methodProperties(methodDesc, schema, "response") + ) + if not nextPageTokenName: + continue + isPageTokenParameter = True + pageTokenName = _findPageTokenName(methodDesc.get("parameters", {})) + if not pageTokenName: + isPageTokenParameter = False + pageTokenName = _findPageTokenName( + _methodProperties(methodDesc, schema, "request") + ) + if not pageTokenName: + continue + fixedMethodName, method = createNextMethod( + methodName + "_next", + pageTokenName, + nextPageTokenName, + isPageTokenParameter, + ) + self._set_dynamic_attr( + fixedMethodName, method.__get__(self, self.__class__) + ) + + def _validate_credentials(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + UniverseMismatchError: If the configured universe domain is not valid. + """ + credentials = getattr(self._http, "credentials", None) + + self._credentials_validated = ( + ( + self._credentials_validated + or universe.compare_domains(self._universe_domain, credentials) + ) + if HAS_UNIVERSE + else True + ) + return self._credentials_validated + + +def _findPageTokenName(fields): + """Search field names for one like a page token. + + Args: + fields: container of string, names of fields. + + Returns: + First name that is either 'pageToken' or 'nextPageToken' if one exists, + otherwise None. + """ + return next( + (tokenName for tokenName in _PAGE_TOKEN_NAMES if tokenName in fields), None + ) + + +def _methodProperties(methodDesc, schema, name): + """Get properties of a field in a method description. + + Args: + methodDesc: object, fragment of deserialized discovery document that + describes the method. + schema: object, mapping of schema names to schema descriptions. + name: string, name of top-level field in method description. + + Returns: + Object representing fragment of deserialized discovery document + corresponding to 'properties' field of object corresponding to named field + in method description, if it exists, otherwise empty dict. + """ + desc = methodDesc.get(name, {}) + if "$ref" in desc: + desc = schema.get(desc["$ref"], {}) + return desc.get("properties", {}) diff --git a/python_embeded/Lib/site-packages/googleapiclient/errors.py b/python_embeded/Lib/site-packages/googleapiclient/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..288594a68a5647ff5179bccc0adcf18a697d4c41 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/errors.py @@ -0,0 +1,197 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Errors for the library. + +All exceptions defined by the library +should be defined in this file. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + +import json + +from googleapiclient import _helpers as util + + +class Error(Exception): + """Base error for this module.""" + + pass + + +class HttpError(Error): + """HTTP data was invalid or unexpected.""" + + @util.positional(3) + def __init__(self, resp, content, uri=None): + self.resp = resp + if not isinstance(content, bytes): + raise TypeError("HTTP content should be bytes") + self.content = content + self.uri = uri + self.error_details = "" + self.reason = self._get_reason() + + @property + def status_code(self): + """Return the HTTP status code from the response content.""" + return self.resp.status + + def _get_reason(self): + """Calculate the reason for the error from the response content.""" + reason = self.resp.reason + try: + try: + data = json.loads(self.content.decode("utf-8")) + except json.JSONDecodeError: + # In case it is not json + data = self.content.decode("utf-8") + if isinstance(data, dict): + reason = data["error"]["message"] + error_detail_keyword = next( + ( + kw + for kw in ["detail", "details", "errors", "message"] + if kw in data["error"] + ), + "", + ) + if error_detail_keyword: + self.error_details = data["error"][error_detail_keyword] + elif isinstance(data, list) and len(data) > 0: + first_error = data[0] + reason = first_error["error"]["message"] + if "details" in first_error["error"]: + self.error_details = first_error["error"]["details"] + else: + self.error_details = data + except (ValueError, KeyError, TypeError): + pass + if reason is None: + reason = "" + return reason.strip() + + def __repr__(self): + if self.error_details: + return '' % ( + self.resp.status, + self.uri, + self.reason, + self.error_details, + ) + elif self.uri: + return '' % ( + self.resp.status, + self.uri, + self.reason, + ) + else: + return '' % (self.resp.status, self.reason) + + __str__ = __repr__ + + +class InvalidJsonError(Error): + """The JSON returned could not be parsed.""" + + pass + + +class UnknownFileType(Error): + """File type unknown or unexpected.""" + + pass + + +class UnknownLinkType(Error): + """Link type unknown or unexpected.""" + + pass + + +class UnknownApiNameOrVersion(Error): + """No API with that name and version exists.""" + + pass + + +class UnacceptableMimeTypeError(Error): + """That is an unacceptable mimetype for this operation.""" + + pass + + +class MediaUploadSizeError(Error): + """Media is larger than the method can accept.""" + + pass + + +class ResumableUploadError(HttpError): + """Error occurred during resumable upload.""" + + pass + + +class InvalidChunkSizeError(Error): + """The given chunksize is not valid.""" + + pass + + +class InvalidNotificationError(Error): + """The channel Notification is invalid.""" + + pass + + +class BatchError(HttpError): + """Error occurred during batch operations.""" + + @util.positional(2) + def __init__(self, reason, resp=None, content=None): + self.resp = resp + self.content = content + self.reason = reason + + def __repr__(self): + if getattr(self.resp, "status", None) is None: + return '' % (self.reason) + else: + return '' % (self.resp.status, self.reason) + + __str__ = __repr__ + + +class UnexpectedMethodError(Error): + """Exception raised by RequestMockBuilder on unexpected calls.""" + + @util.positional(1) + def __init__(self, methodId=None): + """Constructor for an UnexpectedMethodError.""" + super(UnexpectedMethodError, self).__init__( + "Received unexpected call %s" % methodId + ) + + +class UnexpectedBodyError(Error): + """Exception raised by RequestMockBuilder on unexpected bodies.""" + + def __init__(self, expected, provided): + """Constructor for an UnexpectedMethodError.""" + super(UnexpectedBodyError, self).__init__( + "Expected: [%s] - Provided: [%s]" % (expected, provided) + ) diff --git a/python_embeded/Lib/site-packages/googleapiclient/http.py b/python_embeded/Lib/site-packages/googleapiclient/http.py new file mode 100644 index 0000000000000000000000000000000000000000..187f6f5dac856e27d583e66ca805d80e26f8f6df --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/http.py @@ -0,0 +1,1962 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Classes to encapsulate a single HTTP request. + +The classes implement a command pattern, with every +object supporting an execute() method that does the +actual HTTP request. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + +import copy +import http.client as http_client +import io +import json +import logging +import mimetypes +import os +import random +import socket +import time +import urllib +import uuid + +import httplib2 + +# TODO(issue 221): Remove this conditional import jibbajabba. +try: + import ssl +except ImportError: + _ssl_SSLError = object() +else: + _ssl_SSLError = ssl.SSLError + +from email.generator import Generator +from email.mime.multipart import MIMEMultipart +from email.mime.nonmultipart import MIMENonMultipart +from email.parser import FeedParser + +from googleapiclient import _auth +from googleapiclient import _helpers as util +from googleapiclient.errors import ( + BatchError, + HttpError, + InvalidChunkSizeError, + ResumableUploadError, + UnexpectedBodyError, + UnexpectedMethodError, +) +from googleapiclient.model import JsonModel + +LOGGER = logging.getLogger(__name__) + +DEFAULT_CHUNK_SIZE = 100 * 1024 * 1024 + +MAX_URI_LENGTH = 2048 + +MAX_BATCH_LIMIT = 1000 + +_TOO_MANY_REQUESTS = 429 + +DEFAULT_HTTP_TIMEOUT_SEC = 60 + +_LEGACY_BATCH_URI = "https://www.googleapis.com/batch" + + +def _should_retry_response(resp_status, content): + """Determines whether a response should be retried. + + Args: + resp_status: The response status received. + content: The response content body. + + Returns: + True if the response should be retried, otherwise False. + """ + reason = None + + # Retry on 5xx errors. + if resp_status >= 500: + return True + + # Retry on 429 errors. + if resp_status == _TOO_MANY_REQUESTS: + return True + + # For 403 errors, we have to check for the `reason` in the response to + # determine if we should retry. + if resp_status == http_client.FORBIDDEN: + # If there's no details about the 403 type, don't retry. + if not content: + return False + + # Content is in JSON format. + try: + data = json.loads(content.decode("utf-8")) + if isinstance(data, dict): + # There are many variations of the error json so we need + # to determine the keyword which has the error detail. Make sure + # that the order of the keywords below isn't changed as it can + # break user code. If the "errors" key exists, we must use that + # first. + # See Issue #1243 + # https://github.com/googleapis/google-api-python-client/issues/1243 + error_detail_keyword = next( + ( + kw + for kw in ["errors", "status", "message"] + if kw in data["error"] + ), + "", + ) + + if error_detail_keyword: + reason = data["error"][error_detail_keyword] + + if isinstance(reason, list) and len(reason) > 0: + reason = reason[0] + if "reason" in reason: + reason = reason["reason"] + else: + reason = data[0]["error"]["errors"]["reason"] + except (UnicodeDecodeError, ValueError, KeyError): + LOGGER.warning("Invalid JSON content from response: %s", content) + return False + + LOGGER.warning('Encountered 403 Forbidden with reason "%s"', reason) + + # Only retry on rate limit related failures. + if reason in ("userRateLimitExceeded", "rateLimitExceeded"): + return True + + # Everything else is a success or non-retriable so break. + return False + + +def _retry_request( + http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs +): + """Retries an HTTP request multiple times while handling errors. + + If after all retries the request still fails, last error is either returned as + return value (for HTTP 5xx errors) or thrown (for ssl.SSLError). + + Args: + http: Http object to be used to execute request. + num_retries: Maximum number of retries. + req_type: Type of the request (used for logging retries). + sleep, rand: Functions to sleep for random time between retries. + uri: URI to be requested. + method: HTTP method to be used. + args, kwargs: Additional arguments passed to http.request. + + Returns: + resp, content - Response from the http request (may be HTTP 5xx). + """ + resp = None + content = None + exception = None + for retry_num in range(num_retries + 1): + if retry_num > 0: + # Sleep before retrying. + sleep_time = rand() * 2**retry_num + LOGGER.warning( + "Sleeping %.2f seconds before retry %d of %d for %s: %s %s, after %s", + sleep_time, + retry_num, + num_retries, + req_type, + method, + uri, + resp.status if resp else exception, + ) + sleep(sleep_time) + + try: + exception = None + resp, content = http.request(uri, method, *args, **kwargs) + # Retry on SSL errors and socket timeout errors. + except _ssl_SSLError as ssl_error: + exception = ssl_error + except socket.timeout as socket_timeout: + # Needs to be before socket.error as it's a subclass of OSError + # socket.timeout has no errorcode + exception = socket_timeout + except ConnectionError as connection_error: + # Needs to be before socket.error as it's a subclass of OSError + exception = connection_error + except OSError as socket_error: + # errno's contents differ by platform, so we have to match by name. + # Some of these same errors may have been caught above, e.g. ECONNRESET *should* be + # raised as a ConnectionError, but some libraries will raise it as a socket.error + # with an errno corresponding to ECONNRESET + if socket.errno.errorcode.get(socket_error.errno) not in { + "WSAETIMEDOUT", + "ETIMEDOUT", + "EPIPE", + "ECONNABORTED", + "ECONNREFUSED", + "ECONNRESET", + }: + raise + exception = socket_error + except httplib2.ServerNotFoundError as server_not_found_error: + exception = server_not_found_error + + if exception: + if retry_num == num_retries: + raise exception + else: + continue + + if not _should_retry_response(resp.status, content): + break + + return resp, content + + +class MediaUploadProgress(object): + """Status of a resumable upload.""" + + def __init__(self, resumable_progress, total_size): + """Constructor. + + Args: + resumable_progress: int, bytes sent so far. + total_size: int, total bytes in complete upload, or None if the total + upload size isn't known ahead of time. + """ + self.resumable_progress = resumable_progress + self.total_size = total_size + + def progress(self): + """Percent of upload completed, as a float. + + Returns: + the percentage complete as a float, returning 0.0 if the total size of + the upload is unknown. + """ + if self.total_size is not None and self.total_size != 0: + return float(self.resumable_progress) / float(self.total_size) + else: + return 0.0 + + +class MediaDownloadProgress(object): + """Status of a resumable download.""" + + def __init__(self, resumable_progress, total_size): + """Constructor. + + Args: + resumable_progress: int, bytes received so far. + total_size: int, total bytes in complete download. + """ + self.resumable_progress = resumable_progress + self.total_size = total_size + + def progress(self): + """Percent of download completed, as a float. + + Returns: + the percentage complete as a float, returning 0.0 if the total size of + the download is unknown. + """ + if self.total_size is not None and self.total_size != 0: + return float(self.resumable_progress) / float(self.total_size) + else: + return 0.0 + + +class MediaUpload(object): + """Describes a media object to upload. + + Base class that defines the interface of MediaUpload subclasses. + + Note that subclasses of MediaUpload may allow you to control the chunksize + when uploading a media object. It is important to keep the size of the chunk + as large as possible to keep the upload efficient. Other factors may influence + the size of the chunk you use, particularly if you are working in an + environment where individual HTTP requests may have a hardcoded time limit, + such as under certain classes of requests under Google App Engine. + + Streams are io.Base compatible objects that support seek(). Some MediaUpload + subclasses support using streams directly to upload data. Support for + streaming may be indicated by a MediaUpload sub-class and if appropriate for a + platform that stream will be used for uploading the media object. The support + for streaming is indicated by has_stream() returning True. The stream() method + should return an io.Base object that supports seek(). On platforms where the + underlying httplib module supports streaming, for example Python 2.6 and + later, the stream will be passed into the http library which will result in + less memory being used and possibly faster uploads. + + If you need to upload media that can't be uploaded using any of the existing + MediaUpload sub-class then you can sub-class MediaUpload for your particular + needs. + """ + + def chunksize(self): + """Chunk size for resumable uploads. + + Returns: + Chunk size in bytes. + """ + raise NotImplementedError() + + def mimetype(self): + """Mime type of the body. + + Returns: + Mime type. + """ + return "application/octet-stream" + + def size(self): + """Size of upload. + + Returns: + Size of the body, or None of the size is unknown. + """ + return None + + def resumable(self): + """Whether this upload is resumable. + + Returns: + True if resumable upload or False. + """ + return False + + def getbytes(self, begin, end): + """Get bytes from the media. + + Args: + begin: int, offset from beginning of file. + length: int, number of bytes to read, starting at begin. + + Returns: + A string of bytes read. May be shorter than length if EOF was reached + first. + """ + raise NotImplementedError() + + def has_stream(self): + """Does the underlying upload support a streaming interface. + + Streaming means it is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + + Returns: + True if the call to stream() will return an instance of a seekable io.Base + subclass. + """ + return False + + def stream(self): + """A stream interface to the data being uploaded. + + Returns: + The returned value is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + """ + raise NotImplementedError() + + @util.positional(1) + def _to_json(self, strip=None): + """Utility function for creating a JSON representation of a MediaUpload. + + Args: + strip: array, An array of names of members to not include in the JSON. + + Returns: + string, a JSON representation of this instance, suitable to pass to + from_json(). + """ + t = type(self) + d = copy.copy(self.__dict__) + if strip is not None: + for member in strip: + del d[member] + d["_class"] = t.__name__ + d["_module"] = t.__module__ + return json.dumps(d) + + def to_json(self): + """Create a JSON representation of an instance of MediaUpload. + + Returns: + string, a JSON representation of this instance, suitable to pass to + from_json(). + """ + return self._to_json() + + @classmethod + def new_from_json(cls, s): + """Utility class method to instantiate a MediaUpload subclass from a JSON + representation produced by to_json(). + + Args: + s: string, JSON from to_json(). + + Returns: + An instance of the subclass of MediaUpload that was serialized with + to_json(). + """ + data = json.loads(s) + # Find and call the right classmethod from_json() to restore the object. + module = data["_module"] + m = __import__(module, fromlist=module.split(".")[:-1]) + kls = getattr(m, data["_class"]) + from_json = getattr(kls, "from_json") + return from_json(s) + + +class MediaIoBaseUpload(MediaUpload): + """A MediaUpload for a io.Base objects. + + Note that the Python file object is compatible with io.Base and can be used + with this class also. + + fh = BytesIO('...Some data to upload...') + media = MediaIoBaseUpload(fh, mimetype='image/png', + chunksize=1024*1024, resumable=True) + farm.animals().insert( + id='cow', + name='cow.png', + media_body=media).execute() + + Depending on the platform you are working on, you may pass -1 as the + chunksize, which indicates that the entire file should be uploaded in a single + request. If the underlying platform supports streams, such as Python 2.6 or + later, then this can be very efficient as it avoids multiple connections, and + also avoids loading the entire file into memory before sending it. Note that + Google App Engine has a 5MB limit on request size, so you should never set + your chunksize larger than 5MB, or to -1. + """ + + @util.positional(3) + def __init__(self, fd, mimetype, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): + """Constructor. + + Args: + fd: io.Base or file object, The source of the bytes to upload. MUST be + opened in blocking mode, do not use streams opened in non-blocking mode. + The given stream must be seekable, that is, it must be able to call + seek() on fd. + mimetype: string, Mime-type of the file. + chunksize: int, File will be uploaded in chunks of this many bytes. Only + used if resumable=True. Pass in a value of -1 if the file is to be + uploaded as a single chunk. Note that Google App Engine has a 5MB limit + on request size, so you should never set your chunksize larger than 5MB, + or to -1. + resumable: bool, True if this is a resumable upload. False means upload + in a single request. + """ + super(MediaIoBaseUpload, self).__init__() + self._fd = fd + self._mimetype = mimetype + if not (chunksize == -1 or chunksize > 0): + raise InvalidChunkSizeError() + self._chunksize = chunksize + self._resumable = resumable + + self._fd.seek(0, os.SEEK_END) + self._size = self._fd.tell() + + def chunksize(self): + """Chunk size for resumable uploads. + + Returns: + Chunk size in bytes. + """ + return self._chunksize + + def mimetype(self): + """Mime type of the body. + + Returns: + Mime type. + """ + return self._mimetype + + def size(self): + """Size of upload. + + Returns: + Size of the body, or None of the size is unknown. + """ + return self._size + + def resumable(self): + """Whether this upload is resumable. + + Returns: + True if resumable upload or False. + """ + return self._resumable + + def getbytes(self, begin, length): + """Get bytes from the media. + + Args: + begin: int, offset from beginning of file. + length: int, number of bytes to read, starting at begin. + + Returns: + A string of bytes read. May be shorted than length if EOF was reached + first. + """ + self._fd.seek(begin) + return self._fd.read(length) + + def has_stream(self): + """Does the underlying upload support a streaming interface. + + Streaming means it is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + + Returns: + True if the call to stream() will return an instance of a seekable io.Base + subclass. + """ + return True + + def stream(self): + """A stream interface to the data being uploaded. + + Returns: + The returned value is an io.IOBase subclass that supports seek, i.e. + seekable() returns True. + """ + return self._fd + + def to_json(self): + """This upload type is not serializable.""" + raise NotImplementedError("MediaIoBaseUpload is not serializable.") + + +class MediaFileUpload(MediaIoBaseUpload): + """A MediaUpload for a file. + + Construct a MediaFileUpload and pass as the media_body parameter of the + method. For example, if we had a service that allowed uploading images: + + media = MediaFileUpload('cow.png', mimetype='image/png', + chunksize=1024*1024, resumable=True) + farm.animals().insert( + id='cow', + name='cow.png', + media_body=media).execute() + + Depending on the platform you are working on, you may pass -1 as the + chunksize, which indicates that the entire file should be uploaded in a single + request. If the underlying platform supports streams, such as Python 2.6 or + later, then this can be very efficient as it avoids multiple connections, and + also avoids loading the entire file into memory before sending it. Note that + Google App Engine has a 5MB limit on request size, so you should never set + your chunksize larger than 5MB, or to -1. + """ + + @util.positional(2) + def __init__( + self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False + ): + """Constructor. + + Args: + filename: string, Name of the file. + mimetype: string, Mime-type of the file. If None then a mime-type will be + guessed from the file extension. + chunksize: int, File will be uploaded in chunks of this many bytes. Only + used if resumable=True. Pass in a value of -1 if the file is to be + uploaded in a single chunk. Note that Google App Engine has a 5MB limit + on request size, so you should never set your chunksize larger than 5MB, + or to -1. + resumable: bool, True if this is a resumable upload. False means upload + in a single request. + """ + self._fd = None + self._filename = filename + self._fd = open(self._filename, "rb") + if mimetype is None: + # No mimetype provided, make a guess. + mimetype, _ = mimetypes.guess_type(filename) + if mimetype is None: + # Guess failed, use octet-stream. + mimetype = "application/octet-stream" + super(MediaFileUpload, self).__init__( + self._fd, mimetype, chunksize=chunksize, resumable=resumable + ) + + def __del__(self): + if self._fd: + self._fd.close() + + def to_json(self): + """Creating a JSON representation of an instance of MediaFileUpload. + + Returns: + string, a JSON representation of this instance, suitable to pass to + from_json(). + """ + return self._to_json(strip=["_fd"]) + + @staticmethod + def from_json(s): + d = json.loads(s) + return MediaFileUpload( + d["_filename"], + mimetype=d["_mimetype"], + chunksize=d["_chunksize"], + resumable=d["_resumable"], + ) + + +class MediaInMemoryUpload(MediaIoBaseUpload): + """MediaUpload for a chunk of bytes. + + DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or io.StringIO for + the stream. + """ + + @util.positional(2) + def __init__( + self, + body, + mimetype="application/octet-stream", + chunksize=DEFAULT_CHUNK_SIZE, + resumable=False, + ): + """Create a new MediaInMemoryUpload. + + DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or io.StringIO for + the stream. + + Args: + body: string, Bytes of body content. + mimetype: string, Mime-type of the file or default of + 'application/octet-stream'. + chunksize: int, File will be uploaded in chunks of this many bytes. Only + used if resumable=True. + resumable: bool, True if this is a resumable upload. False means upload + in a single request. + """ + fd = io.BytesIO(body) + super(MediaInMemoryUpload, self).__init__( + fd, mimetype, chunksize=chunksize, resumable=resumable + ) + + +class MediaIoBaseDownload(object): + """ "Download media resources. + + Note that the Python file object is compatible with io.Base and can be used + with this class also. + + + Example: + request = farms.animals().get_media(id='cow') + fh = io.FileIO('cow.png', mode='wb') + downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024) + + done = False + while done is False: + status, done = downloader.next_chunk() + if status: + print "Download %d%%." % int(status.progress() * 100) + print "Download Complete!" + """ + + @util.positional(3) + def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE): + """Constructor. + + Args: + fd: io.Base or file object, The stream in which to write the downloaded + bytes. + request: googleapiclient.http.HttpRequest, the media request to perform in + chunks. + chunksize: int, File will be downloaded in chunks of this many bytes. + """ + self._fd = fd + self._request = request + self._uri = request.uri + self._chunksize = chunksize + self._progress = 0 + self._total_size = None + self._done = False + + # Stubs for testing. + self._sleep = time.sleep + self._rand = random.random + + self._headers = {} + for k, v in request.headers.items(): + # allow users to supply custom headers by setting them on the request + # but strip out the ones that are set by default on requests generated by + # API methods like Drive's files().get(fileId=...) + if not k.lower() in ("accept", "accept-encoding", "user-agent"): + self._headers[k] = v + + @util.positional(1) + def next_chunk(self, num_retries=0): + """Get the next chunk of the download. + + Args: + num_retries: Integer, number of times to retry with randomized + exponential backoff. If all retries fail, the raised HttpError + represents the last request. If zero (default), we attempt the + request only once. + + Returns: + (status, done): (MediaDownloadProgress, boolean) + The value of 'done' will be True when the media has been fully + downloaded or the total size of the media is unknown. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx. + httplib2.HttpLib2Error if a transport error has occurred. + """ + headers = self._headers.copy() + headers["range"] = "bytes=%d-%d" % ( + self._progress, + self._progress + self._chunksize - 1, + ) + http = self._request.http + + resp, content = _retry_request( + http, + num_retries, + "media download", + self._sleep, + self._rand, + self._uri, + "GET", + headers=headers, + ) + + if resp.status in [200, 206]: + if "content-location" in resp and resp["content-location"] != self._uri: + self._uri = resp["content-location"] + self._progress += len(content) + self._fd.write(content) + + if "content-range" in resp: + content_range = resp["content-range"] + length = content_range.rsplit("/", 1)[1] + self._total_size = int(length) + elif "content-length" in resp: + self._total_size = int(resp["content-length"]) + + if self._total_size is None or self._progress == self._total_size: + self._done = True + return MediaDownloadProgress(self._progress, self._total_size), self._done + elif resp.status == 416: + # 416 is Range Not Satisfiable + # This typically occurs with a zero byte file + content_range = resp["content-range"] + length = content_range.rsplit("/", 1)[1] + self._total_size = int(length) + if self._total_size == 0: + self._done = True + return ( + MediaDownloadProgress(self._progress, self._total_size), + self._done, + ) + raise HttpError(resp, content, uri=self._uri) + + +class _StreamSlice(object): + """Truncated stream. + + Takes a stream and presents a stream that is a slice of the original stream. + This is used when uploading media in chunks. In later versions of Python a + stream can be passed to httplib in place of the string of data to send. The + problem is that httplib just blindly reads to the end of the stream. This + wrapper presents a virtual stream that only reads to the end of the chunk. + """ + + def __init__(self, stream, begin, chunksize): + """Constructor. + + Args: + stream: (io.Base, file object), the stream to wrap. + begin: int, the seek position the chunk begins at. + chunksize: int, the size of the chunk. + """ + self._stream = stream + self._begin = begin + self._chunksize = chunksize + self._stream.seek(begin) + + def read(self, n=-1): + """Read n bytes. + + Args: + n, int, the number of bytes to read. + + Returns: + A string of length 'n', or less if EOF is reached. + """ + # The data left available to read sits in [cur, end) + cur = self._stream.tell() + end = self._begin + self._chunksize + if n == -1 or cur + n > end: + n = end - cur + return self._stream.read(n) + + +class HttpRequest(object): + """Encapsulates a single HTTP request.""" + + @util.positional(4) + def __init__( + self, + http, + postproc, + uri, + method="GET", + body=None, + headers=None, + methodId=None, + resumable=None, + ): + """Constructor for an HttpRequest. + + Args: + http: httplib2.Http, the transport object to use to make a request + postproc: callable, called on the HTTP response and content to transform + it into a data object before returning, or raising an exception + on an error. + uri: string, the absolute URI to send the request to + method: string, the HTTP method to use + body: string, the request body of the HTTP request, + headers: dict, the HTTP request headers + methodId: string, a unique identifier for the API method being called. + resumable: MediaUpload, None if this is not a resumbale request. + """ + self.uri = uri + self.method = method + self.body = body + self.headers = headers or {} + self.methodId = methodId + self.http = http + self.postproc = postproc + self.resumable = resumable + self.response_callbacks = [] + self._in_error_state = False + + # The size of the non-media part of the request. + self.body_size = len(self.body or "") + + # The resumable URI to send chunks to. + self.resumable_uri = None + + # The bytes that have been uploaded. + self.resumable_progress = 0 + + # Stubs for testing. + self._rand = random.random + self._sleep = time.sleep + + @util.positional(1) + def execute(self, http=None, num_retries=0): + """Execute the request. + + Args: + http: httplib2.Http, an http object to be used in place of the + one the HttpRequest request object was constructed with. + num_retries: Integer, number of times to retry with randomized + exponential backoff. If all retries fail, the raised HttpError + represents the last request. If zero (default), we attempt the + request only once. + + Returns: + A deserialized object model of the response body as determined + by the postproc. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx. + httplib2.HttpLib2Error if a transport error has occurred. + """ + if http is None: + http = self.http + + if self.resumable: + body = None + while body is None: + _, body = self.next_chunk(http=http, num_retries=num_retries) + return body + + # Non-resumable case. + + if "content-length" not in self.headers: + self.headers["content-length"] = str(self.body_size) + # If the request URI is too long then turn it into a POST request. + # Assume that a GET request never contains a request body. + if len(self.uri) > MAX_URI_LENGTH and self.method == "GET": + self.method = "POST" + self.headers["x-http-method-override"] = "GET" + self.headers["content-type"] = "application/x-www-form-urlencoded" + parsed = urllib.parse.urlparse(self.uri) + self.uri = urllib.parse.urlunparse( + (parsed.scheme, parsed.netloc, parsed.path, parsed.params, None, None) + ) + self.body = parsed.query + self.headers["content-length"] = str(len(self.body)) + + # Handle retries for server-side errors. + resp, content = _retry_request( + http, + num_retries, + "request", + self._sleep, + self._rand, + str(self.uri), + method=str(self.method), + body=self.body, + headers=self.headers, + ) + + for callback in self.response_callbacks: + callback(resp) + if resp.status >= 300: + raise HttpError(resp, content, uri=self.uri) + return self.postproc(resp, content) + + @util.positional(2) + def add_response_callback(self, cb): + """add_response_headers_callback + + Args: + cb: Callback to be called on receiving the response headers, of signature: + + def cb(resp): + # Where resp is an instance of httplib2.Response + """ + self.response_callbacks.append(cb) + + @util.positional(1) + def next_chunk(self, http=None, num_retries=0): + """Execute the next step of a resumable upload. + + Can only be used if the method being executed supports media uploads and + the MediaUpload object passed in was flagged as using resumable upload. + + Example: + + media = MediaFileUpload('cow.png', mimetype='image/png', + chunksize=1000, resumable=True) + request = farm.animals().insert( + id='cow', + name='cow.png', + media_body=media) + + response = None + while response is None: + status, response = request.next_chunk() + if status: + print "Upload %d%% complete." % int(status.progress() * 100) + + + Args: + http: httplib2.Http, an http object to be used in place of the + one the HttpRequest request object was constructed with. + num_retries: Integer, number of times to retry with randomized + exponential backoff. If all retries fail, the raised HttpError + represents the last request. If zero (default), we attempt the + request only once. + + Returns: + (status, body): (ResumableMediaStatus, object) + The body will be None until the resumable media is fully uploaded. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx. + httplib2.HttpLib2Error if a transport error has occurred. + """ + if http is None: + http = self.http + + if self.resumable.size() is None: + size = "*" + else: + size = str(self.resumable.size()) + + if self.resumable_uri is None: + start_headers = copy.copy(self.headers) + start_headers["X-Upload-Content-Type"] = self.resumable.mimetype() + if size != "*": + start_headers["X-Upload-Content-Length"] = size + start_headers["content-length"] = str(self.body_size) + + resp, content = _retry_request( + http, + num_retries, + "resumable URI request", + self._sleep, + self._rand, + self.uri, + method=self.method, + body=self.body, + headers=start_headers, + ) + + if resp.status == 200 and "location" in resp: + self.resumable_uri = resp["location"] + else: + raise ResumableUploadError(resp, content) + elif self._in_error_state: + # If we are in an error state then query the server for current state of + # the upload by sending an empty PUT and reading the 'range' header in + # the response. + headers = {"Content-Range": "bytes */%s" % size, "content-length": "0"} + resp, content = http.request(self.resumable_uri, "PUT", headers=headers) + status, body = self._process_response(resp, content) + if body: + # The upload was complete. + return (status, body) + + if self.resumable.has_stream(): + data = self.resumable.stream() + if self.resumable.chunksize() == -1: + data.seek(self.resumable_progress) + chunk_end = self.resumable.size() - self.resumable_progress - 1 + else: + # Doing chunking with a stream, so wrap a slice of the stream. + data = _StreamSlice( + data, self.resumable_progress, self.resumable.chunksize() + ) + chunk_end = min( + self.resumable_progress + self.resumable.chunksize() - 1, + self.resumable.size() - 1, + ) + else: + data = self.resumable.getbytes( + self.resumable_progress, self.resumable.chunksize() + ) + + # A short read implies that we are at EOF, so finish the upload. + if len(data) < self.resumable.chunksize(): + size = str(self.resumable_progress + len(data)) + + chunk_end = self.resumable_progress + len(data) - 1 + + headers = { + # Must set the content-length header here because httplib can't + # calculate the size when working with _StreamSlice. + "Content-Length": str(chunk_end - self.resumable_progress + 1), + } + + # An empty file results in chunk_end = -1 and size = 0 + # sending "bytes 0--1/0" results in an invalid request + # Only add header "Content-Range" if chunk_end != -1 + if chunk_end != -1: + headers["Content-Range"] = "bytes %d-%d/%s" % ( + self.resumable_progress, + chunk_end, + size, + ) + + for retry_num in range(num_retries + 1): + if retry_num > 0: + self._sleep(self._rand() * 2**retry_num) + LOGGER.warning( + "Retry #%d for media upload: %s %s, following status: %d" + % (retry_num, self.method, self.uri, resp.status) + ) + + try: + resp, content = http.request( + self.resumable_uri, method="PUT", body=data, headers=headers + ) + except: + self._in_error_state = True + raise + if not _should_retry_response(resp.status, content): + break + + return self._process_response(resp, content) + + def _process_response(self, resp, content): + """Process the response from a single chunk upload. + + Args: + resp: httplib2.Response, the response object. + content: string, the content of the response. + + Returns: + (status, body): (ResumableMediaStatus, object) + The body will be None until the resumable media is fully uploaded. + + Raises: + googleapiclient.errors.HttpError if the response was not a 2xx or a 308. + """ + if resp.status in [200, 201]: + self._in_error_state = False + return None, self.postproc(resp, content) + elif resp.status == 308: + self._in_error_state = False + # A "308 Resume Incomplete" indicates we are not done. + try: + self.resumable_progress = int(resp["range"].split("-")[1]) + 1 + except KeyError: + # If resp doesn't contain range header, resumable progress is 0 + self.resumable_progress = 0 + if "location" in resp: + self.resumable_uri = resp["location"] + else: + self._in_error_state = True + raise HttpError(resp, content, uri=self.uri) + + return ( + MediaUploadProgress(self.resumable_progress, self.resumable.size()), + None, + ) + + def to_json(self): + """Returns a JSON representation of the HttpRequest.""" + d = copy.copy(self.__dict__) + if d["resumable"] is not None: + d["resumable"] = self.resumable.to_json() + del d["http"] + del d["postproc"] + del d["_sleep"] + del d["_rand"] + + return json.dumps(d) + + @staticmethod + def from_json(s, http, postproc): + """Returns an HttpRequest populated with info from a JSON object.""" + d = json.loads(s) + if d["resumable"] is not None: + d["resumable"] = MediaUpload.new_from_json(d["resumable"]) + return HttpRequest( + http, + postproc, + uri=d["uri"], + method=d["method"], + body=d["body"], + headers=d["headers"], + methodId=d["methodId"], + resumable=d["resumable"], + ) + + @staticmethod + def null_postproc(resp, contents): + return resp, contents + + +class BatchHttpRequest(object): + """Batches multiple HttpRequest objects into a single HTTP request. + + Example: + from googleapiclient.http import BatchHttpRequest + + def list_animals(request_id, response, exception): + \"\"\"Do something with the animals list response.\"\"\" + if exception is not None: + # Do something with the exception. + pass + else: + # Do something with the response. + pass + + def list_farmers(request_id, response, exception): + \"\"\"Do something with the farmers list response.\"\"\" + if exception is not None: + # Do something with the exception. + pass + else: + # Do something with the response. + pass + + service = build('farm', 'v2') + + batch = BatchHttpRequest() + + batch.add(service.animals().list(), list_animals) + batch.add(service.farmers().list(), list_farmers) + batch.execute(http=http) + """ + + @util.positional(1) + def __init__(self, callback=None, batch_uri=None): + """Constructor for a BatchHttpRequest. + + Args: + callback: callable, A callback to be called for each response, of the + form callback(id, response, exception). The first parameter is the + request id, and the second is the deserialized response object. The + third is an googleapiclient.errors.HttpError exception object if an HTTP error + occurred while processing the request, or None if no error occurred. + batch_uri: string, URI to send batch requests to. + """ + if batch_uri is None: + batch_uri = _LEGACY_BATCH_URI + + if batch_uri == _LEGACY_BATCH_URI: + LOGGER.warning( + "You have constructed a BatchHttpRequest using the legacy batch " + "endpoint %s. This endpoint will be turned down on August 12, 2020. " + "Please provide the API-specific endpoint or use " + "service.new_batch_http_request(). For more details see " + "https://developers.googleblog.com/2018/03/discontinuing-support-for-json-rpc-and.html" + "and https://developers.google.com/api-client-library/python/guide/batch.", + _LEGACY_BATCH_URI, + ) + self._batch_uri = batch_uri + + # Global callback to be called for each individual response in the batch. + self._callback = callback + + # A map from id to request. + self._requests = {} + + # A map from id to callback. + self._callbacks = {} + + # List of request ids, in the order in which they were added. + self._order = [] + + # The last auto generated id. + self._last_auto_id = 0 + + # Unique ID on which to base the Content-ID headers. + self._base_id = None + + # A map from request id to (httplib2.Response, content) response pairs + self._responses = {} + + # A map of id(Credentials) that have been refreshed. + self._refreshed_credentials = {} + + def _refresh_and_apply_credentials(self, request, http): + """Refresh the credentials and apply to the request. + + Args: + request: HttpRequest, the request. + http: httplib2.Http, the global http object for the batch. + """ + # For the credentials to refresh, but only once per refresh_token + # If there is no http per the request then refresh the http passed in + # via execute() + creds = None + request_credentials = False + + if request.http is not None: + creds = _auth.get_credentials_from_http(request.http) + request_credentials = True + + if creds is None and http is not None: + creds = _auth.get_credentials_from_http(http) + + if creds is not None: + if id(creds) not in self._refreshed_credentials: + _auth.refresh_credentials(creds) + self._refreshed_credentials[id(creds)] = 1 + + # Only apply the credentials if we are using the http object passed in, + # otherwise apply() will get called during _serialize_request(). + if request.http is None or not request_credentials: + _auth.apply_credentials(creds, request.headers) + + def _id_to_header(self, id_): + """Convert an id to a Content-ID header value. + + Args: + id_: string, identifier of individual request. + + Returns: + A Content-ID header with the id_ encoded into it. A UUID is prepended to + the value because Content-ID headers are supposed to be universally + unique. + """ + if self._base_id is None: + self._base_id = uuid.uuid4() + + # NB: we intentionally leave whitespace between base/id and '+', so RFC2822 + # line folding works properly on Python 3; see + # https://github.com/googleapis/google-api-python-client/issues/164 + return "<%s + %s>" % (self._base_id, urllib.parse.quote(id_)) + + def _header_to_id(self, header): + """Convert a Content-ID header value to an id. + + Presumes the Content-ID header conforms to the format that _id_to_header() + returns. + + Args: + header: string, Content-ID header value. + + Returns: + The extracted id value. + + Raises: + BatchError if the header is not in the expected format. + """ + if header[0] != "<" or header[-1] != ">": + raise BatchError("Invalid value for Content-ID: %s" % header) + if "+" not in header: + raise BatchError("Invalid value for Content-ID: %s" % header) + base, id_ = header[1:-1].split(" + ", 1) + + return urllib.parse.unquote(id_) + + def _serialize_request(self, request): + """Convert an HttpRequest object into a string. + + Args: + request: HttpRequest, the request to serialize. + + Returns: + The request as a string in application/http format. + """ + # Construct status line + parsed = urllib.parse.urlparse(request.uri) + request_line = urllib.parse.urlunparse( + ("", "", parsed.path, parsed.params, parsed.query, "") + ) + status_line = request.method + " " + request_line + " HTTP/1.1\n" + major, minor = request.headers.get("content-type", "application/json").split( + "/" + ) + msg = MIMENonMultipart(major, minor) + headers = request.headers.copy() + + if request.http is not None: + credentials = _auth.get_credentials_from_http(request.http) + if credentials is not None: + _auth.apply_credentials(credentials, headers) + + # MIMENonMultipart adds its own Content-Type header. + if "content-type" in headers: + del headers["content-type"] + + for key, value in headers.items(): + msg[key] = value + msg["Host"] = parsed.netloc + msg.set_unixfrom(None) + + if request.body is not None: + msg.set_payload(request.body) + msg["content-length"] = str(len(request.body)) + + # Serialize the mime message. + fp = io.StringIO() + # maxheaderlen=0 means don't line wrap headers. + g = Generator(fp, maxheaderlen=0) + g.flatten(msg, unixfrom=False) + body = fp.getvalue() + + return status_line + body + + def _deserialize_response(self, payload): + """Convert string into httplib2 response and content. + + Args: + payload: string, headers and body as a string. + + Returns: + A pair (resp, content), such as would be returned from httplib2.request. + """ + # Strip off the status line + status_line, payload = payload.split("\n", 1) + protocol, status, reason = status_line.split(" ", 2) + + # Parse the rest of the response + parser = FeedParser() + parser.feed(payload) + msg = parser.close() + msg["status"] = status + + # Create httplib2.Response from the parsed headers. + resp = httplib2.Response(msg) + resp.reason = reason + resp.version = int(protocol.split("/", 1)[1].replace(".", "")) + + content = payload.split("\r\n\r\n", 1)[1] + + return resp, content + + def _new_id(self): + """Create a new id. + + Auto incrementing number that avoids conflicts with ids already used. + + Returns: + string, a new unique id. + """ + self._last_auto_id += 1 + while str(self._last_auto_id) in self._requests: + self._last_auto_id += 1 + return str(self._last_auto_id) + + @util.positional(2) + def add(self, request, callback=None, request_id=None): + """Add a new request. + + Every callback added will be paired with a unique id, the request_id. That + unique id will be passed back to the callback when the response comes back + from the server. The default behavior is to have the library generate it's + own unique id. If the caller passes in a request_id then they must ensure + uniqueness for each request_id, and if they are not an exception is + raised. Callers should either supply all request_ids or never supply a + request id, to avoid such an error. + + Args: + request: HttpRequest, Request to add to the batch. + callback: callable, A callback to be called for this response, of the + form callback(id, response, exception). The first parameter is the + request id, and the second is the deserialized response object. The + third is an googleapiclient.errors.HttpError exception object if an HTTP error + occurred while processing the request, or None if no errors occurred. + request_id: string, A unique id for the request. The id will be passed + to the callback with the response. + + Returns: + None + + Raises: + BatchError if a media request is added to a batch. + KeyError is the request_id is not unique. + """ + + if len(self._order) >= MAX_BATCH_LIMIT: + raise BatchError( + "Exceeded the maximum calls(%d) in a single batch request." + % MAX_BATCH_LIMIT + ) + if request_id is None: + request_id = self._new_id() + if request.resumable is not None: + raise BatchError("Media requests cannot be used in a batch request.") + if request_id in self._requests: + raise KeyError("A request with this ID already exists: %s" % request_id) + self._requests[request_id] = request + self._callbacks[request_id] = callback + self._order.append(request_id) + + def _execute(self, http, order, requests): + """Serialize batch request, send to server, process response. + + Args: + http: httplib2.Http, an http object to be used to make the request with. + order: list, list of request ids in the order they were added to the + batch. + requests: list, list of request objects to send. + + Raises: + httplib2.HttpLib2Error if a transport error has occurred. + googleapiclient.errors.BatchError if the response is the wrong format. + """ + message = MIMEMultipart("mixed") + # Message should not write out it's own headers. + setattr(message, "_write_headers", lambda self: None) + + # Add all the individual requests. + for request_id in order: + request = requests[request_id] + + msg = MIMENonMultipart("application", "http") + msg["Content-Transfer-Encoding"] = "binary" + msg["Content-ID"] = self._id_to_header(request_id) + + body = self._serialize_request(request) + msg.set_payload(body) + message.attach(msg) + + # encode the body: note that we can't use `as_string`, because + # it plays games with `From ` lines. + fp = io.StringIO() + g = Generator(fp, mangle_from_=False) + g.flatten(message, unixfrom=False) + body = fp.getvalue() + + headers = {} + headers["content-type"] = ( + "multipart/mixed; " 'boundary="%s"' + ) % message.get_boundary() + + resp, content = http.request( + self._batch_uri, method="POST", body=body, headers=headers + ) + + if resp.status >= 300: + raise HttpError(resp, content, uri=self._batch_uri) + + # Prepend with a content-type header so FeedParser can handle it. + header = "content-type: %s\r\n\r\n" % resp["content-type"] + # PY3's FeedParser only accepts unicode. So we should decode content + # here, and encode each payload again. + content = content.decode("utf-8") + for_parser = header + content + + parser = FeedParser() + parser.feed(for_parser) + mime_response = parser.close() + + if not mime_response.is_multipart(): + raise BatchError( + "Response not in multipart/mixed format.", resp=resp, content=content + ) + + for part in mime_response.get_payload(): + request_id = self._header_to_id(part["Content-ID"]) + response, content = self._deserialize_response(part.get_payload()) + # We encode content here to emulate normal http response. + if isinstance(content, str): + content = content.encode("utf-8") + self._responses[request_id] = (response, content) + + @util.positional(1) + def execute(self, http=None): + """Execute all the requests as a single batched HTTP request. + + Args: + http: httplib2.Http, an http object to be used in place of the one the + HttpRequest request object was constructed with. If one isn't supplied + then use a http object from the requests in this batch. + + Returns: + None + + Raises: + httplib2.HttpLib2Error if a transport error has occurred. + googleapiclient.errors.BatchError if the response is the wrong format. + """ + # If we have no requests return + if len(self._order) == 0: + return None + + # If http is not supplied use the first valid one given in the requests. + if http is None: + for request_id in self._order: + request = self._requests[request_id] + if request is not None: + http = request.http + break + + if http is None: + raise ValueError("Missing a valid http object.") + + # Special case for OAuth2Credentials-style objects which have not yet been + # refreshed with an initial access_token. + creds = _auth.get_credentials_from_http(http) + if creds is not None: + if not _auth.is_valid(creds): + LOGGER.info("Attempting refresh to obtain initial access_token") + _auth.refresh_credentials(creds) + + self._execute(http, self._order, self._requests) + + # Loop over all the requests and check for 401s. For each 401 request the + # credentials should be refreshed and then sent again in a separate batch. + redo_requests = {} + redo_order = [] + + for request_id in self._order: + resp, content = self._responses[request_id] + if resp["status"] == "401": + redo_order.append(request_id) + request = self._requests[request_id] + self._refresh_and_apply_credentials(request, http) + redo_requests[request_id] = request + + if redo_requests: + self._execute(http, redo_order, redo_requests) + + # Now process all callbacks that are erroring, and raise an exception for + # ones that return a non-2xx response? Or add extra parameter to callback + # that contains an HttpError? + + for request_id in self._order: + resp, content = self._responses[request_id] + + request = self._requests[request_id] + callback = self._callbacks[request_id] + + response = None + exception = None + try: + if resp.status >= 300: + raise HttpError(resp, content, uri=request.uri) + response = request.postproc(resp, content) + except HttpError as e: + exception = e + + if callback is not None: + callback(request_id, response, exception) + if self._callback is not None: + self._callback(request_id, response, exception) + + +class HttpRequestMock(object): + """Mock of HttpRequest. + + Do not construct directly, instead use RequestMockBuilder. + """ + + def __init__(self, resp, content, postproc): + """Constructor for HttpRequestMock + + Args: + resp: httplib2.Response, the response to emulate coming from the request + content: string, the response body + postproc: callable, the post processing function usually supplied by + the model class. See model.JsonModel.response() as an example. + """ + self.resp = resp + self.content = content + self.postproc = postproc + if resp is None: + self.resp = httplib2.Response({"status": 200, "reason": "OK"}) + if "reason" in self.resp: + self.resp.reason = self.resp["reason"] + + def execute(self, http=None): + """Execute the request. + + Same behavior as HttpRequest.execute(), but the response is + mocked and not really from an HTTP request/response. + """ + return self.postproc(self.resp, self.content) + + +class RequestMockBuilder(object): + """A simple mock of HttpRequest + + Pass in a dictionary to the constructor that maps request methodIds to + tuples of (httplib2.Response, content, opt_expected_body) that should be + returned when that method is called. None may also be passed in for the + httplib2.Response, in which case a 200 OK response will be generated. + If an opt_expected_body (str or dict) is provided, it will be compared to + the body and UnexpectedBodyError will be raised on inequality. + + Example: + response = '{"data": {"id": "tag:google.c...' + requestBuilder = RequestMockBuilder( + { + 'plus.activities.get': (None, response), + } + ) + googleapiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder) + + Methods that you do not supply a response for will return a + 200 OK with an empty string as the response content or raise an excpetion + if check_unexpected is set to True. The methodId is taken from the rpcName + in the discovery document. + + For more details see the project wiki. + """ + + def __init__(self, responses, check_unexpected=False): + """Constructor for RequestMockBuilder + + The constructed object should be a callable object + that can replace the class HttpResponse. + + responses - A dictionary that maps methodIds into tuples + of (httplib2.Response, content). The methodId + comes from the 'rpcName' field in the discovery + document. + check_unexpected - A boolean setting whether or not UnexpectedMethodError + should be raised on unsupplied method. + """ + self.responses = responses + self.check_unexpected = check_unexpected + + def __call__( + self, + http, + postproc, + uri, + method="GET", + body=None, + headers=None, + methodId=None, + resumable=None, + ): + """Implements the callable interface that discovery.build() expects + of requestBuilder, which is to build an object compatible with + HttpRequest.execute(). See that method for the description of the + parameters and the expected response. + """ + if methodId in self.responses: + response = self.responses[methodId] + resp, content = response[:2] + if len(response) > 2: + # Test the body against the supplied expected_body. + expected_body = response[2] + if bool(expected_body) != bool(body): + # Not expecting a body and provided one + # or expecting a body and not provided one. + raise UnexpectedBodyError(expected_body, body) + if isinstance(expected_body, str): + expected_body = json.loads(expected_body) + body = json.loads(body) + if body != expected_body: + raise UnexpectedBodyError(expected_body, body) + return HttpRequestMock(resp, content, postproc) + elif self.check_unexpected: + raise UnexpectedMethodError(methodId=methodId) + else: + model = JsonModel(False) + return HttpRequestMock(None, "{}", model.response) + + +class HttpMock(object): + """Mock of httplib2.Http""" + + def __init__(self, filename=None, headers=None): + """ + Args: + filename: string, absolute filename to read response from + headers: dict, header to return with response + """ + if headers is None: + headers = {"status": "200"} + if filename: + with open(filename, "rb") as f: + self.data = f.read() + else: + self.data = None + self.response_headers = headers + self.headers = None + self.uri = None + self.method = None + self.body = None + self.headers = None + + def request( + self, + uri, + method="GET", + body=None, + headers=None, + redirections=1, + connection_type=None, + ): + self.uri = uri + self.method = method + self.body = body + self.headers = headers + return httplib2.Response(self.response_headers), self.data + + def close(self): + return None + + +class HttpMockSequence(object): + """Mock of httplib2.Http + + Mocks a sequence of calls to request returning different responses for each + call. Create an instance initialized with the desired response headers + and content and then use as if an httplib2.Http instance. + + http = HttpMockSequence([ + ({'status': '401'}, ''), + ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), + ({'status': '200'}, 'echo_request_headers'), + ]) + resp, content = http.request("http://examples.com") + + There are special values you can pass in for content to trigger + behavours that are helpful in testing. + + 'echo_request_headers' means return the request headers in the response body + 'echo_request_headers_as_json' means return the request headers in + the response body + 'echo_request_body' means return the request body in the response body + 'echo_request_uri' means return the request uri in the response body + """ + + def __init__(self, iterable): + """ + Args: + iterable: iterable, a sequence of pairs of (headers, body) + """ + self._iterable = iterable + self.follow_redirects = True + self.request_sequence = list() + + def request( + self, + uri, + method="GET", + body=None, + headers=None, + redirections=1, + connection_type=None, + ): + # Remember the request so after the fact this mock can be examined + self.request_sequence.append((uri, method, body, headers)) + resp, content = self._iterable.pop(0) + if isinstance(content, str): + content = content.encode("utf-8") + + if content == b"echo_request_headers": + content = headers + elif content == b"echo_request_headers_as_json": + content = json.dumps(headers) + elif content == b"echo_request_body": + if hasattr(body, "read"): + content = body.read() + else: + content = body + elif content == b"echo_request_uri": + content = uri + if isinstance(content, str): + content = content.encode("utf-8") + return httplib2.Response(resp), content + + +def set_user_agent(http, user_agent): + """Set the user-agent on every request. + + Args: + http - An instance of httplib2.Http + or something that acts like it. + user_agent: string, the value for the user-agent header. + + Returns: + A modified instance of http that was passed in. + + Example: + + h = httplib2.Http() + h = set_user_agent(h, "my-app-name/6.0") + + Most of the time the user-agent will be set doing auth, this is for the rare + cases where you are accessing an unauthenticated endpoint. + """ + request_orig = http.request + + # The closure that will replace 'httplib2.Http.request'. + def new_request( + uri, + method="GET", + body=None, + headers=None, + redirections=httplib2.DEFAULT_MAX_REDIRECTS, + connection_type=None, + ): + """Modify the request headers to add the user-agent.""" + if headers is None: + headers = {} + if "user-agent" in headers: + headers["user-agent"] = user_agent + " " + headers["user-agent"] + else: + headers["user-agent"] = user_agent + resp, content = request_orig( + uri, + method=method, + body=body, + headers=headers, + redirections=redirections, + connection_type=connection_type, + ) + return resp, content + + http.request = new_request + return http + + +def tunnel_patch(http): + """Tunnel PATCH requests over POST. + Args: + http - An instance of httplib2.Http + or something that acts like it. + + Returns: + A modified instance of http that was passed in. + + Example: + + h = httplib2.Http() + h = tunnel_patch(h, "my-app-name/6.0") + + Useful if you are running on a platform that doesn't support PATCH. + Apply this last if you are using OAuth 1.0, as changing the method + will result in a different signature. + """ + request_orig = http.request + + # The closure that will replace 'httplib2.Http.request'. + def new_request( + uri, + method="GET", + body=None, + headers=None, + redirections=httplib2.DEFAULT_MAX_REDIRECTS, + connection_type=None, + ): + """Modify the request headers to add the user-agent.""" + if headers is None: + headers = {} + if method == "PATCH": + if "oauth_token" in headers.get("authorization", ""): + LOGGER.warning( + "OAuth 1.0 request made with Credentials after tunnel_patch." + ) + headers["x-http-method-override"] = "PATCH" + method = "POST" + resp, content = request_orig( + uri, + method=method, + body=body, + headers=headers, + redirections=redirections, + connection_type=connection_type, + ) + return resp, content + + http.request = new_request + return http + + +def build_http(): + """Builds httplib2.Http object + + Returns: + A httplib2.Http object, which is used to make http requests, and which has timeout set by default. + To override default timeout call + + socket.setdefaulttimeout(timeout_in_sec) + + before interacting with this method. + """ + if socket.getdefaulttimeout() is not None: + http_timeout = socket.getdefaulttimeout() + else: + http_timeout = DEFAULT_HTTP_TIMEOUT_SEC + http = httplib2.Http(timeout=http_timeout) + # 308's are used by several Google APIs (Drive, YouTube) + # for Resumable Uploads rather than Permanent Redirects. + # This asks httplib2 to exclude 308s from the status codes + # it treats as redirects + try: + http.redirect_codes = http.redirect_codes - {308} + except AttributeError: + # Apache Beam tests depend on this library and cannot + # currently upgrade their httplib2 version + # http.redirect_codes does not exist in previous versions + # of httplib2, so pass + pass + + return http diff --git a/python_embeded/Lib/site-packages/googleapiclient/mimeparse.py b/python_embeded/Lib/site-packages/googleapiclient/mimeparse.py new file mode 100644 index 0000000000000000000000000000000000000000..d3dedee9c53370e9ba67f252d34a7e0cccd2a244 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/mimeparse.py @@ -0,0 +1,183 @@ +# Copyright 2014 Joe Gregorio +# +# Licensed under the MIT License + +"""MIME-Type Parser + +This module provides basic functions for handling mime-types. It can handle +matching mime-types against a list of media-ranges. See section 14.1 of the +HTTP specification [RFC 2616] for a complete explanation. + + http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 + +Contents: + - parse_mime_type(): Parses a mime-type into its component parts. + - parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q' + quality parameter. + - quality(): Determines the quality ('q') of a mime-type when + compared against a list of media-ranges. + - quality_parsed(): Just like quality() except the second parameter must be + pre-parsed. + - best_match(): Choose the mime-type with the highest quality ('q') + from a list of candidates. +""" +from __future__ import absolute_import + +from functools import reduce + +__version__ = "0.1.3" +__author__ = "Joe Gregorio" +__email__ = "joe@bitworking.org" +__license__ = "MIT License" +__credits__ = "" + + +def parse_mime_type(mime_type): + """Parses a mime-type into its component parts. + + Carves up a mime-type and returns a tuple of the (type, subtype, params) + where 'params' is a dictionary of all the parameters for the media range. + For example, the media range 'application/xhtml;q=0.5' would get parsed + into: + + ('application', 'xhtml', {'q', '0.5'}) + """ + parts = mime_type.split(";") + params = dict( + [tuple([s.strip() for s in param.split("=", 1)]) for param in parts[1:]] + ) + full_type = parts[0].strip() + # Java URLConnection class sends an Accept header that includes a + # single '*'. Turn it into a legal wildcard. + if full_type == "*": + full_type = "*/*" + (type, subtype) = full_type.split("/") + + return (type.strip(), subtype.strip(), params) + + +def parse_media_range(range): + """Parse a media-range into its component parts. + + Carves up a media range and returns a tuple of the (type, subtype, + params) where 'params' is a dictionary of all the parameters for the media + range. For example, the media range 'application/*;q=0.5' would get parsed + into: + + ('application', '*', {'q', '0.5'}) + + In addition this function also guarantees that there is a value for 'q' + in the params dictionary, filling it in with a proper default if + necessary. + """ + (type, subtype, params) = parse_mime_type(range) + if ( + "q" not in params + or not params["q"] + or not float(params["q"]) + or float(params["q"]) > 1 + or float(params["q"]) < 0 + ): + params["q"] = "1" + + return (type, subtype, params) + + +def fitness_and_quality_parsed(mime_type, parsed_ranges): + """Find the best match for a mime-type amongst parsed media-ranges. + + Find the best match for a given mime-type against a list of media_ranges + that have already been parsed by parse_media_range(). Returns a tuple of + the fitness value and the value of the 'q' quality parameter of the best + match, or (-1, 0) if no match was found. Just as for quality_parsed(), + 'parsed_ranges' must be a list of parsed media ranges. + """ + best_fitness = -1 + best_fit_q = 0 + (target_type, target_subtype, target_params) = parse_media_range(mime_type) + for (type, subtype, params) in parsed_ranges: + type_match = type == target_type or type == "*" or target_type == "*" + subtype_match = ( + subtype == target_subtype or subtype == "*" or target_subtype == "*" + ) + if type_match and subtype_match: + param_matches = reduce( + lambda x, y: x + y, + [ + 1 + for (key, value) in target_params.items() + if key != "q" and key in params and value == params[key] + ], + 0, + ) + fitness = (type == target_type) and 100 or 0 + fitness += (subtype == target_subtype) and 10 or 0 + fitness += param_matches + if fitness > best_fitness: + best_fitness = fitness + best_fit_q = params["q"] + + return best_fitness, float(best_fit_q) + + +def quality_parsed(mime_type, parsed_ranges): + """Find the best match for a mime-type amongst parsed media-ranges. + + Find the best match for a given mime-type against a list of media_ranges + that have already been parsed by parse_media_range(). Returns the 'q' + quality parameter of the best match, 0 if no match was found. This function + bahaves the same as quality() except that 'parsed_ranges' must be a list of + parsed media ranges. + """ + + return fitness_and_quality_parsed(mime_type, parsed_ranges)[1] + + +def quality(mime_type, ranges): + """Return the quality ('q') of a mime-type against a list of media-ranges. + + Returns the quality 'q' of a mime-type when compared against the + media-ranges in ranges. For example: + + >>> quality('text/html','text/*;q=0.3, text/html;q=0.7, + text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5') + 0.7 + + """ + parsed_ranges = [parse_media_range(r) for r in ranges.split(",")] + + return quality_parsed(mime_type, parsed_ranges) + + +def best_match(supported, header): + """Return mime-type with the highest quality ('q') from list of candidates. + + Takes a list of supported mime-types and finds the best match for all the + media-ranges listed in header. The value of header must be a string that + conforms to the format of the HTTP Accept: header. The value of 'supported' + is a list of mime-types. The list of supported mime-types should be sorted + in order of increasing desirability, in case of a situation where there is + a tie. + + >>> best_match(['application/xbel+xml', 'text/xml'], + 'text/*;q=0.5,*/*; q=0.1') + 'text/xml' + """ + split_header = _filter_blank(header.split(",")) + parsed_header = [parse_media_range(r) for r in split_header] + weighted_matches = [] + pos = 0 + for mime_type in supported: + weighted_matches.append( + (fitness_and_quality_parsed(mime_type, parsed_header), pos, mime_type) + ) + pos += 1 + weighted_matches.sort() + + return weighted_matches[-1][0][1] and weighted_matches[-1][2] or "" + + +def _filter_blank(i): + for s in i: + if s.strip(): + yield s diff --git a/python_embeded/Lib/site-packages/googleapiclient/model.py b/python_embeded/Lib/site-packages/googleapiclient/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dee1cb7f377bd81acfd9b43b72d20034ee5cb096 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/model.py @@ -0,0 +1,429 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Model objects for requests and responses. + +Each API may support one or more serializations, such +as JSON, Atom, etc. The model classes are responsible +for converting between the wire format and the Python +object representation. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + +import json +import logging +import platform +import urllib +import warnings + +from googleapiclient import version as googleapiclient_version +from googleapiclient.errors import HttpError + +try: + from google.api_core.version_header import API_VERSION_METADATA_KEY + + HAS_API_VERSION = True +except ImportError: + HAS_API_VERSION = False + +_LIBRARY_VERSION = googleapiclient_version.__version__ +_PY_VERSION = platform.python_version() + +LOGGER = logging.getLogger(__name__) + +dump_request_response = False + + +def _abstract(): + raise NotImplementedError("You need to override this function") + + +class Model(object): + """Model base class. + + All Model classes should implement this interface. + The Model serializes and de-serializes between a wire + format such as JSON and a Python object representation. + """ + + def request(self, headers, path_params, query_params, body_value): + """Updates outgoing requests with a serialized body. + + Args: + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query_params: dict, parameters that appear in the query + body_value: object, the request body as a Python object, which must be + serializable. + Returns: + A tuple of (headers, path_params, query, body) + + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query: string, query part of the request URI + body: string, the body serialized in the desired wire format. + """ + _abstract() + + def response(self, resp, content): + """Convert the response wire format into a Python object. + + Args: + resp: httplib2.Response, the HTTP response headers and status + content: string, the body of the HTTP response + + Returns: + The body de-serialized as a Python object. + + Raises: + googleapiclient.errors.HttpError if a non 2xx response is received. + """ + _abstract() + + +class BaseModel(Model): + """Base model class. + + Subclasses should provide implementations for the "serialize" and + "deserialize" methods, as well as values for the following class attributes. + + Attributes: + accept: The value to use for the HTTP Accept header. + content_type: The value to use for the HTTP Content-type header. + no_content_response: The value to return when deserializing a 204 "No + Content" response. + alt_param: The value to supply as the "alt" query parameter for requests. + """ + + accept = None + content_type = None + no_content_response = None + alt_param = None + + def _log_request(self, headers, path_params, query, body): + """Logs debugging information about the request if requested.""" + if dump_request_response: + LOGGER.info("--request-start--") + LOGGER.info("-headers-start-") + for h, v in headers.items(): + LOGGER.info("%s: %s", h, v) + LOGGER.info("-headers-end-") + LOGGER.info("-path-parameters-start-") + for h, v in path_params.items(): + LOGGER.info("%s: %s", h, v) + LOGGER.info("-path-parameters-end-") + LOGGER.info("body: %s", body) + LOGGER.info("query: %s", query) + LOGGER.info("--request-end--") + + def request(self, headers, path_params, query_params, body_value, api_version=None): + """Updates outgoing requests with a serialized body. + + Args: + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query_params: dict, parameters that appear in the query + body_value: object, the request body as a Python object, which must be + serializable by json. + api_version: str, The precise API version represented by this request, + which will result in an API Version header being sent along with the + HTTP request. + Returns: + A tuple of (headers, path_params, query, body) + + headers: dict, request headers + path_params: dict, parameters that appear in the request path + query: string, query part of the request URI + body: string, the body serialized as JSON + """ + query = self._build_query(query_params) + headers["accept"] = self.accept + headers["accept-encoding"] = "gzip, deflate" + if "user-agent" in headers: + headers["user-agent"] += " " + else: + headers["user-agent"] = "" + headers["user-agent"] += "(gzip)" + if "x-goog-api-client" in headers: + headers["x-goog-api-client"] += " " + else: + headers["x-goog-api-client"] = "" + headers["x-goog-api-client"] += "gdcl/%s gl-python/%s" % ( + _LIBRARY_VERSION, + _PY_VERSION, + ) + + if api_version and HAS_API_VERSION: + headers[API_VERSION_METADATA_KEY] = api_version + elif api_version: + warnings.warn( + "The `api_version` argument is ignored as a newer version of " + "`google-api-core` is required to use this feature." + "Please upgrade `google-api-core` to 2.19.0 or newer." + ) + + if body_value is not None: + headers["content-type"] = self.content_type + body_value = self.serialize(body_value) + self._log_request(headers, path_params, query, body_value) + return (headers, path_params, query, body_value) + + def _build_query(self, params): + """Builds a query string. + + Args: + params: dict, the query parameters + + Returns: + The query parameters properly encoded into an HTTP URI query string. + """ + if self.alt_param is not None: + params.update({"alt": self.alt_param}) + astuples = [] + for key, value in params.items(): + if type(value) == type([]): + for x in value: + x = x.encode("utf-8") + astuples.append((key, x)) + else: + if isinstance(value, str) and callable(value.encode): + value = value.encode("utf-8") + astuples.append((key, value)) + return "?" + urllib.parse.urlencode(astuples) + + def _log_response(self, resp, content): + """Logs debugging information about the response if requested.""" + if dump_request_response: + LOGGER.info("--response-start--") + for h, v in resp.items(): + LOGGER.info("%s: %s", h, v) + if content: + LOGGER.info(content) + LOGGER.info("--response-end--") + + def response(self, resp, content): + """Convert the response wire format into a Python object. + + Args: + resp: httplib2.Response, the HTTP response headers and status + content: string, the body of the HTTP response + + Returns: + The body de-serialized as a Python object. + + Raises: + googleapiclient.errors.HttpError if a non 2xx response is received. + """ + self._log_response(resp, content) + # Error handling is TBD, for example, do we retry + # for some operation/error combinations? + if resp.status < 300: + if resp.status == 204: + # A 204: No Content response should be treated differently + # to all the other success states + return self.no_content_response + return self.deserialize(content) + else: + LOGGER.debug("Content from bad request was: %r" % content) + raise HttpError(resp, content) + + def serialize(self, body_value): + """Perform the actual Python object serialization. + + Args: + body_value: object, the request body as a Python object. + + Returns: + string, the body in serialized form. + """ + _abstract() + + def deserialize(self, content): + """Perform the actual deserialization from response string to Python + object. + + Args: + content: string, the body of the HTTP response + + Returns: + The body de-serialized as a Python object. + """ + _abstract() + + +class JsonModel(BaseModel): + """Model class for JSON. + + Serializes and de-serializes between JSON and the Python + object representation of HTTP request and response bodies. + """ + + accept = "application/json" + content_type = "application/json" + alt_param = "json" + + def __init__(self, data_wrapper=False): + """Construct a JsonModel. + + Args: + data_wrapper: boolean, wrap requests and responses in a data wrapper + """ + self._data_wrapper = data_wrapper + + def serialize(self, body_value): + if ( + isinstance(body_value, dict) + and "data" not in body_value + and self._data_wrapper + ): + body_value = {"data": body_value} + return json.dumps(body_value) + + def deserialize(self, content): + try: + content = content.decode("utf-8") + except AttributeError: + pass + try: + body = json.loads(content) + except json.decoder.JSONDecodeError: + body = content + else: + if self._data_wrapper and "data" in body: + body = body["data"] + return body + + @property + def no_content_response(self): + return {} + + +class RawModel(JsonModel): + """Model class for requests that don't return JSON. + + Serializes and de-serializes between JSON and the Python + object representation of HTTP request, and returns the raw bytes + of the response body. + """ + + accept = "*/*" + content_type = "application/json" + alt_param = None + + def deserialize(self, content): + return content + + @property + def no_content_response(self): + return "" + + +class MediaModel(JsonModel): + """Model class for requests that return Media. + + Serializes and de-serializes between JSON and the Python + object representation of HTTP request, and returns the raw bytes + of the response body. + """ + + accept = "*/*" + content_type = "application/json" + alt_param = "media" + + def deserialize(self, content): + return content + + @property + def no_content_response(self): + return "" + + +class ProtocolBufferModel(BaseModel): + """Model class for protocol buffers. + + Serializes and de-serializes the binary protocol buffer sent in the HTTP + request and response bodies. + """ + + accept = "application/x-protobuf" + content_type = "application/x-protobuf" + alt_param = "proto" + + def __init__(self, protocol_buffer): + """Constructs a ProtocolBufferModel. + + The serialized protocol buffer returned in an HTTP response will be + de-serialized using the given protocol buffer class. + + Args: + protocol_buffer: The protocol buffer class used to de-serialize a + response from the API. + """ + self._protocol_buffer = protocol_buffer + + def serialize(self, body_value): + return body_value.SerializeToString() + + def deserialize(self, content): + return self._protocol_buffer.FromString(content) + + @property + def no_content_response(self): + return self._protocol_buffer() + + +def makepatch(original, modified): + """Create a patch object. + + Some methods support PATCH, an efficient way to send updates to a resource. + This method allows the easy construction of patch bodies by looking at the + differences between a resource before and after it was modified. + + Args: + original: object, the original deserialized resource + modified: object, the modified deserialized resource + Returns: + An object that contains only the changes from original to modified, in a + form suitable to pass to a PATCH method. + + Example usage: + item = service.activities().get(postid=postid, userid=userid).execute() + original = copy.deepcopy(item) + item['object']['content'] = 'This is updated.' + service.activities.patch(postid=postid, userid=userid, + body=makepatch(original, item)).execute() + """ + patch = {} + for key, original_value in original.items(): + modified_value = modified.get(key, None) + if modified_value is None: + # Use None to signal that the element is deleted + patch[key] = None + elif original_value != modified_value: + if type(original_value) == type({}): + # Recursively descend objects + patch[key] = makepatch(original_value, modified_value) + else: + # In the case of simple types or arrays we just replace + patch[key] = modified_value + else: + # Don't add anything to patch if there's no change + pass + for key in modified: + if key not in original: + patch[key] = modified[key] + + return patch diff --git a/python_embeded/Lib/site-packages/googleapiclient/sample_tools.py b/python_embeded/Lib/site-packages/googleapiclient/sample_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..bdad0a2ae878f43627199c5a7dcdd82cad0a8e8e --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/sample_tools.py @@ -0,0 +1,108 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for making samples. + +Consolidates a lot of code commonly repeated in sample applications. +""" +from __future__ import absolute_import + +__author__ = "jcgregorio@google.com (Joe Gregorio)" +__all__ = ["init"] + + +import argparse +import os + +from googleapiclient import discovery +from googleapiclient.http import build_http + + +def init( + argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None +): + """A common initialization routine for samples. + + Many of the sample applications do the same initialization, which has now + been consolidated into this function. This function uses common idioms found + in almost all the samples, i.e. for an API with name 'apiname', the + credentials are stored in a file named apiname.dat, and the + client_secrets.json file is stored in the same directory as the application + main file. + + Args: + argv: list of string, the command-line parameters of the application. + name: string, name of the API. + version: string, version of the API. + doc: string, description of the application. Usually set to __doc__. + file: string, filename of the application. Usually set to __file__. + parents: list of argparse.ArgumentParser, additional command-line flags. + scope: string, The OAuth scope used. + discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL. + + Returns: + A tuple of (service, flags), where service is the service object and flags + is the parsed command-line flags. + """ + try: + from oauth2client import client, file, tools + except ImportError: + raise ImportError( + "googleapiclient.sample_tools requires oauth2client. Please install oauth2client and try again." + ) + + if scope is None: + scope = "https://www.googleapis.com/auth/" + name + + # Parser command-line arguments. + parent_parsers = [tools.argparser] + parent_parsers.extend(parents) + parser = argparse.ArgumentParser( + description=doc, + formatter_class=argparse.RawDescriptionHelpFormatter, + parents=parent_parsers, + ) + flags = parser.parse_args(argv[1:]) + + # Name of a file containing the OAuth 2.0 information for this + # application, including client_id and client_secret, which are found + # on the API Access tab on the Google APIs + # Console . + client_secrets = os.path.join(os.path.dirname(filename), "client_secrets.json") + + # Set up a Flow object to be used if we need to authenticate. + flow = client.flow_from_clientsecrets( + client_secrets, scope=scope, message=tools.message_if_missing(client_secrets) + ) + + # Prepare credentials, and authorize HTTP object with them. + # If the credentials don't exist or are invalid run through the native client + # flow. The Storage object will ensure that if successful the good + # credentials will get written back to a file. + storage = file.Storage(name + ".dat") + credentials = storage.get() + if credentials is None or credentials.invalid: + credentials = tools.run_flow(flow, storage, flags) + http = credentials.authorize(http=build_http()) + + if discovery_filename is None: + # Construct a service object via the discovery service. + service = discovery.build(name, version, http=http) + else: + # Construct a service object using a local discovery document file. + with open(discovery_filename) as discovery_file: + service = discovery.build_from_document( + discovery_file.read(), base="https://www.googleapis.com/", http=http + ) + return (service, flags) diff --git a/python_embeded/Lib/site-packages/googleapiclient/schema.py b/python_embeded/Lib/site-packages/googleapiclient/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..93b07df44ac6cb3ddf47a23218801de2ecdc6614 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/schema.py @@ -0,0 +1,317 @@ +# Copyright 2014 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Schema processing for discovery based APIs + +Schemas holds an APIs discovery schemas. It can return those schema as +deserialized JSON objects, or pretty print them as prototype objects that +conform to the schema. + +For example, given the schema: + + schema = \"\"\"{ + "Foo": { + "type": "object", + "properties": { + "etag": { + "type": "string", + "description": "ETag of the collection." + }, + "kind": { + "type": "string", + "description": "Type of the collection ('calendar#acl').", + "default": "calendar#acl" + }, + "nextPageToken": { + "type": "string", + "description": "Token used to access the next + page of this result. Omitted if no further results are available." + } + } + } + }\"\"\" + + s = Schemas(schema) + print s.prettyPrintByName('Foo') + + Produces the following output: + + { + "nextPageToken": "A String", # Token used to access the + # next page of this result. Omitted if no further results are available. + "kind": "A String", # Type of the collection ('calendar#acl'). + "etag": "A String", # ETag of the collection. + }, + +The constructor takes a discovery document in which to look up named schema. +""" +from __future__ import absolute_import + +# TODO(jcgregorio) support format, enum, minimum, maximum + +__author__ = "jcgregorio@google.com (Joe Gregorio)" + + +from collections import OrderedDict + +from googleapiclient import _helpers as util + + +class Schemas(object): + """Schemas for an API.""" + + def __init__(self, discovery): + """Constructor. + + Args: + discovery: object, Deserialized discovery document from which we pull + out the named schema. + """ + self.schemas = discovery.get("schemas", {}) + + # Cache of pretty printed schemas. + self.pretty = {} + + @util.positional(2) + def _prettyPrintByName(self, name, seen=None, dent=0): + """Get pretty printed object prototype from the schema name. + + Args: + name: string, Name of schema in the discovery document. + seen: list of string, Names of schema already seen. Used to handle + recursive definitions. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + if seen is None: + seen = [] + + if name in seen: + # Do not fall into an infinite loop over recursive definitions. + return "# Object with schema name: %s" % name + seen.append(name) + + if name not in self.pretty: + self.pretty[name] = _SchemaToStruct( + self.schemas[name], seen, dent=dent + ).to_str(self._prettyPrintByName) + + seen.pop() + + return self.pretty[name] + + def prettyPrintByName(self, name): + """Get pretty printed object prototype from the schema name. + + Args: + name: string, Name of schema in the discovery document. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + # Return with trailing comma and newline removed. + return self._prettyPrintByName(name, seen=[], dent=0)[:-2] + + @util.positional(2) + def _prettyPrintSchema(self, schema, seen=None, dent=0): + """Get pretty printed object prototype of schema. + + Args: + schema: object, Parsed JSON schema. + seen: list of string, Names of schema already seen. Used to handle + recursive definitions. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + if seen is None: + seen = [] + + return _SchemaToStruct(schema, seen, dent=dent).to_str(self._prettyPrintByName) + + def prettyPrintSchema(self, schema): + """Get pretty printed object prototype of schema. + + Args: + schema: object, Parsed JSON schema. + + Returns: + string, A string that contains a prototype object with + comments that conforms to the given schema. + """ + # Return with trailing comma and newline removed. + return self._prettyPrintSchema(schema, dent=0)[:-2] + + def get(self, name, default=None): + """Get deserialized JSON schema from the schema name. + + Args: + name: string, Schema name. + default: object, return value if name not found. + """ + return self.schemas.get(name, default) + + +class _SchemaToStruct(object): + """Convert schema to a prototype object.""" + + @util.positional(3) + def __init__(self, schema, seen, dent=0): + """Constructor. + + Args: + schema: object, Parsed JSON schema. + seen: list, List of names of schema already seen while parsing. Used to + handle recursive definitions. + dent: int, Initial indentation depth. + """ + # The result of this parsing kept as list of strings. + self.value = [] + + # The final value of the parsing. + self.string = None + + # The parsed JSON schema. + self.schema = schema + + # Indentation level. + self.dent = dent + + # Method that when called returns a prototype object for the schema with + # the given name. + self.from_cache = None + + # List of names of schema already seen while parsing. + self.seen = seen + + def emit(self, text): + """Add text as a line to the output. + + Args: + text: string, Text to output. + """ + self.value.extend([" " * self.dent, text, "\n"]) + + def emitBegin(self, text): + """Add text to the output, but with no line terminator. + + Args: + text: string, Text to output. + """ + self.value.extend([" " * self.dent, text]) + + def emitEnd(self, text, comment): + """Add text and comment to the output with line terminator. + + Args: + text: string, Text to output. + comment: string, Python comment. + """ + if comment: + divider = "\n" + " " * (self.dent + 2) + "# " + lines = comment.splitlines() + lines = [x.rstrip() for x in lines] + comment = divider.join(lines) + self.value.extend([text, " # ", comment, "\n"]) + else: + self.value.extend([text, "\n"]) + + def indent(self): + """Increase indentation level.""" + self.dent += 1 + + def undent(self): + """Decrease indentation level.""" + self.dent -= 1 + + def _to_str_impl(self, schema): + """Prototype object based on the schema, in Python code with comments. + + Args: + schema: object, Parsed JSON schema file. + + Returns: + Prototype object based on the schema, in Python code with comments. + """ + stype = schema.get("type") + if stype == "object": + self.emitEnd("{", schema.get("description", "")) + self.indent() + if "properties" in schema: + properties = schema.get("properties", {}) + sorted_properties = OrderedDict(sorted(properties.items())) + for pname, pschema in sorted_properties.items(): + self.emitBegin('"%s": ' % pname) + self._to_str_impl(pschema) + elif "additionalProperties" in schema: + self.emitBegin('"a_key": ') + self._to_str_impl(schema["additionalProperties"]) + self.undent() + self.emit("},") + elif "$ref" in schema: + schemaName = schema["$ref"] + description = schema.get("description", "") + s = self.from_cache(schemaName, seen=self.seen) + parts = s.splitlines() + self.emitEnd(parts[0], description) + for line in parts[1:]: + self.emit(line.rstrip()) + elif stype == "boolean": + value = schema.get("default", "True or False") + self.emitEnd("%s," % str(value), schema.get("description", "")) + elif stype == "string": + value = schema.get("default", "A String") + self.emitEnd('"%s",' % str(value), schema.get("description", "")) + elif stype == "integer": + value = schema.get("default", "42") + self.emitEnd("%s," % str(value), schema.get("description", "")) + elif stype == "number": + value = schema.get("default", "3.14") + self.emitEnd("%s," % str(value), schema.get("description", "")) + elif stype == "null": + self.emitEnd("None,", schema.get("description", "")) + elif stype == "any": + self.emitEnd('"",', schema.get("description", "")) + elif stype == "array": + self.emitEnd("[", schema.get("description")) + self.indent() + self.emitBegin("") + self._to_str_impl(schema["items"]) + self.undent() + self.emit("],") + else: + self.emit("Unknown type! %s" % stype) + self.emitEnd("", "") + + self.string = "".join(self.value) + return self.string + + def to_str(self, from_cache): + """Prototype object based on the schema, in Python code with comments. + + Args: + from_cache: callable(name, seen), Callable that retrieves an object + prototype for a schema with the given name. Seen is a list of schema + names already seen as we recursively descend the schema definition. + + Returns: + Prototype object based on the schema, in Python code with comments. + The lines of the code will all be properly indented. + """ + self.from_cache = from_cache + return self._to_str_impl(self.schema) diff --git a/python_embeded/Lib/site-packages/googleapiclient/version.py b/python_embeded/Lib/site-packages/googleapiclient/version.py new file mode 100644 index 0000000000000000000000000000000000000000..aec02f6a348f50d05c033a244e226269de184387 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapiclient/version.py @@ -0,0 +1,15 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "2.174.0" diff --git a/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/METADATA b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..7868f72693bf8a3a37b83eeb3e2535b7037ef61f --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/METADATA @@ -0,0 +1,225 @@ +Metadata-Version: 2.1 +Name: googleapis-common-protos +Version: 1.70.0 +Summary: Common protobufs used in Google APIs +Author-email: Google LLC +License: Apache 2.0 +Project-URL: Repository, https://github.com/googleapis/google-cloud-python/tree/main/packages/googleapis-common-protos +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Internet +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: protobuf!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<7.0.0,>=3.20.2 +Provides-Extra: grpc +Requires-Dist: grpcio<2.0.0,>=1.44.0; extra == "grpc" + +Python Client for Google APIs Common Protos +=========================================== + +|stable| |pypi| |versions| + +`Google APIs Common Protos`_: + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |stable| image:: https://img.shields.io/badge/support-stable-gold.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/googleapis-common-protos.svg + :target: https://pypi.org/project/googleapis-common-protos/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/googleapis-common-protos.svg + :target: https://pypi.org/project/googleapis-common-protos/ +.. _Google APIs Common Protos: https://github.com/googleapis/googleapis/tree/master/google +.. _Client Library Documentation: https://github.com/googleapis/google-cloud-python/tree/main/packages/googleapis-common-protos/summary_overview +.. _Product Documentation: https://github.com/googleapis/googleapis/tree/master/google + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Google APIs Common Protos.`_ +4. `Set up Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Google APIs Common Protos.: https://github.com/googleapis/googleapis/tree/master/google +.. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/googleapis-common-protos/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + pip install googleapis-common-protos + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv + .\\Scripts\activate + pip install googleapis-common-protos + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Google APIs Common Protos + to see other available methods on the client. +- Read the `Google APIs Common Protos Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Google APIs Common Protos Product documentation: https://github.com/googleapis/googleapis/tree/master/google +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + +Environment-Based Examples +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + +Code-Based Examples +^^^^^^^^^^^^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/RECORD b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0eb1cfbb584cf7470aa521e77d2a36fadbb1bbe9 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/RECORD @@ -0,0 +1,264 @@ +google/api/__pycache__/annotations_pb2.cpython-312.pyc,, +google/api/__pycache__/auth_pb2.cpython-312.pyc,, +google/api/__pycache__/backend_pb2.cpython-312.pyc,, +google/api/__pycache__/billing_pb2.cpython-312.pyc,, +google/api/__pycache__/client_pb2.cpython-312.pyc,, +google/api/__pycache__/config_change_pb2.cpython-312.pyc,, +google/api/__pycache__/consumer_pb2.cpython-312.pyc,, +google/api/__pycache__/context_pb2.cpython-312.pyc,, +google/api/__pycache__/control_pb2.cpython-312.pyc,, +google/api/__pycache__/distribution_pb2.cpython-312.pyc,, +google/api/__pycache__/documentation_pb2.cpython-312.pyc,, +google/api/__pycache__/endpoint_pb2.cpython-312.pyc,, +google/api/__pycache__/error_reason_pb2.cpython-312.pyc,, +google/api/__pycache__/field_behavior_pb2.cpython-312.pyc,, +google/api/__pycache__/field_info_pb2.cpython-312.pyc,, +google/api/__pycache__/http_pb2.cpython-312.pyc,, +google/api/__pycache__/httpbody_pb2.cpython-312.pyc,, +google/api/__pycache__/label_pb2.cpython-312.pyc,, +google/api/__pycache__/launch_stage_pb2.cpython-312.pyc,, +google/api/__pycache__/log_pb2.cpython-312.pyc,, +google/api/__pycache__/logging_pb2.cpython-312.pyc,, +google/api/__pycache__/metric_pb2.cpython-312.pyc,, +google/api/__pycache__/monitored_resource_pb2.cpython-312.pyc,, +google/api/__pycache__/monitoring_pb2.cpython-312.pyc,, +google/api/__pycache__/policy_pb2.cpython-312.pyc,, +google/api/__pycache__/quota_pb2.cpython-312.pyc,, +google/api/__pycache__/resource_pb2.cpython-312.pyc,, +google/api/__pycache__/routing_pb2.cpython-312.pyc,, +google/api/__pycache__/service_pb2.cpython-312.pyc,, +google/api/__pycache__/source_info_pb2.cpython-312.pyc,, +google/api/__pycache__/system_parameter_pb2.cpython-312.pyc,, +google/api/__pycache__/usage_pb2.cpython-312.pyc,, +google/api/__pycache__/visibility_pb2.cpython-312.pyc,, +google/api/annotations.proto,sha256=556nQctgWmXnjKMiF0dkpK-f3hliwWMeErhMSTS6mmw,1045 +google/api/annotations_pb2.py,sha256=N4cPaBC9BCIlQOPWOQdASPi2eD3e4d6TkfdFtLYKW1M,2182 +google/api/annotations_pb2.pyi,sha256=yAsaRnQFljG5TZeFT1y3gcvYhelrdgf0CBVQ7FymxEg,887 +google/api/auth.proto,sha256=2e4DOCXOD0k3KkUtyn4P86IpT3W46lDCRYH3Ree9LTk,9257 +google/api/auth_pb2.py,sha256=0M9Gb8InDi8Q07RSMmUtvVyTkaijVkhyj8Vga2XjsOQ,3601 +google/api/auth_pb2.pyi,sha256=jvybOkHuFGQQufvANL2hqhmsAnKrQk5L8AFUkWO-fgQ,4324 +google/api/backend.proto,sha256=PxHGHR5ufQfbBSITPV5ad_lI0g1SHDQ9UODhYTFtYtE,7014 +google/api/backend_pb2.py,sha256=pxhfZZJJM9NOtv1aLVYbtYAqrMzgUkD4GCMopWmOh9M,3774 +google/api/backend_pb2.pyi,sha256=4dYVn1pGUVmg6PqcA-jYvISKmrJlzvRsTTVc_hSgG-U,3855 +google/api/billing.proto,sha256=OFKr2YTZXYV8_eGnirw25raNlklSe74ZxuuJOhuOWaw,3062 +google/api/billing_pb2.py,sha256=tzPooX7-Uo7D6NnBLRI5k3pg86xFJEHNfBpXePsbgVU,2314 +google/api/billing_pb2.pyi,sha256=F3m-KV8Eb3fZTzJViZSGelMUEWt0b9EoiHzbadm1isk,1871 +google/api/client.proto,sha256=paE-qFP8tYCVxkVQba3BdPwgAYWXOygEr2ecMOz3OZ0,17312 +google/api/client_pb2.py,sha256=RId46Qgi8HYhI_PPPi4T8zTRHoI-kCbdC3eZOvLzaNs,11033 +google/api/client_pb2.pyi,sha256=fGULcO3Qd90xDWJBIQ0omzwR6A5ock8cM6bXKTVY2Xs,16046 +google/api/config_change.proto,sha256=I8eQ9Y5nmdiKb0hfbNvFl7Ifpq7gcCrsfSvql9cdcgM,3166 +google/api/config_change_pb2.py,sha256=1IQ5en3nLlKUlfvI81EF4aVc_laFGwEj8dS9uxPdSZQ,2693 +google/api/config_change_pb2.pyi,sha256=ww6_F3S0QX06FRdhEJXEZ23vM_YNO5TGqCSP_jpzWIg,2384 +google/api/consumer.proto,sha256=mZrLMRYo2cKUHQz9qr3xgEe-LuBh3aLZVD15qm3v7IQ,2717 +google/api/consumer_pb2.py,sha256=du9G8qgDNzm4x6QFoyUVhdrmG1IWayveHe74b-mexKQ,2574 +google/api/consumer_pb2.pyi,sha256=2deC66k-qml4DPxRbaOpPJRMRa8wg1WSKnE3qtxn0JY,2349 +google/api/context.proto,sha256=ZV_qmbzU2AUPw7QjzsD1hcKmGrpuwODocKvhvYaDkdc,3229 +google/api/context_pb2.py,sha256=7OE8Ys1Ul4SkyHZeGSqopTOVri8B61hHxhDgQTGax2M,2376 +google/api/context_pb2.pyi,sha256=nsrPLW7YXomSXEQ7M0raTPX4xHXukgrjgZn8P9rUzzg,2339 +google/api/control.proto,sha256=P85ehiAbvPKKxgNwfh8xG-qbNXiJgoJw_tpXyxefUaE,1436 +google/api/control_pb2.py,sha256=esG8pu59PUpemOz7NrCWr6fKCLCV1nvOR3TQ703JvhM,2177 +google/api/control_pb2.pyi,sha256=A_7VMDxGo-3rxWiCnF_ZxdnpBQqwoR06E80EQp5CMAQ,1546 +google/api/distribution.proto,sha256=bsFR7S8Az7v2ujJBEWhHrVxubtTlk_ZqIeMmbqn2Ocg,8660 +google/api/distribution_pb2.py,sha256=Foe8SmWC4Fu40Ttk9-xLLKZHw-7GK82XrLBrajzEWQ0,4484 +google/api/distribution_pb2.pyi,sha256=AMsYyPqZbwMf1MUa1PayiPA0F47NZtFO9bxudHoTWMw,5768 +google/api/documentation.proto,sha256=7lFnpByFg9Tt9zrbDjS9MjK5enoT7lrDmUH2vQVjHXs,6925 +google/api/documentation_pb2.py,sha256=TqGyUrqvxRP0lrWweAZjD3mq9uJMV0aSjUhgloj4TBc,2843 +google/api/documentation_pb2.pyi,sha256=SeGxZ44uoF0owOlV2x7902jwd_Qa_QoMebkntxme588,3062 +google/api/endpoint.proto,sha256=4rtmT7wVRtqaoSKRuFETHeLbvP3OHv5EXfXZreXG4Ec,2891 +google/api/endpoint_pb2.py,sha256=vz1NV3ZhzpkDwwT_PfOq4YinvXl61OFC8Jl1fBigGbw,2108 +google/api/endpoint_pb2.pyi,sha256=O6_2RdBfzfiS1Hx0-_XCDmEPiI7XNZ2177Q11SbCnYA,1479 +google/api/error_reason.proto,sha256=exczRSdpYN70oXhtg9FykGjh4roga_RKUMPuz4xh2vI,23628 +google/api/error_reason_pb2.py,sha256=pPEcOh8xvuP0D3Kh8FPV1-H0wjmu6yt0tQO0MBQDnsQ,3509 +google/api/error_reason_pb2.pyi,sha256=F79LjP9wnfclzQ0F2WBaC6cgbKGMsn4ZsqUr5mN7Ego,3784 +google/api/field_behavior.proto,sha256=BEun_AW90WGCvik0h5S6FVkZw7d9b-SS7GO57q6aLFw,4306 +google/api/field_behavior_pb2.py,sha256=8L_u76wGMf6yTsB2vWoidY6Nj55fwqtiZNtCbWVYZPc,2680 +google/api/field_behavior_pb2.pyi,sha256=HKVTIpHfvh2KJaaJnyqqzVBgmN_8oyputJVIcil5nSA,1680 +google/api/field_info.proto,sha256=srMQ8mSl_qTLnLtgc8e-9wI6B6oWrA4-Bqvqp1w8uJM,4456 +google/api/field_info_pb2.py,sha256=ZuUWp8UjJ6U54z-oM5jgZEUduS0UOEgagXZzTgbTH7E,2817 +google/api/field_info_pb2.pyi,sha256=7AFgq0JXzhlYZySWXj8UAs3dQp3IE0YNxJuVOb_cnkg,2368 +google/api/http.proto,sha256=Sk2b5qXH8Zick8JccbSP8bQBZFeQuLl4rTTVeeKcSio,15059 +google/api/http_pb2.py,sha256=qR_cOrhHFJmuGU7Keziemltih5T1iAtfilIZG56bTSU,2869 +google/api/http_pb2.pyi,sha256=ZatZQGFKlxDoLD56bgoFlzyxwKicySxa7gHqefPh6aA,3147 +google/api/httpbody.proto,sha256=O8hGOGWVMdO9YVTkqGfudjtBxq0V0dcH4KrPQd-PGQE,2661 +google/api/httpbody_pb2.py,sha256=l3lkNH_Klr1Lk3CJGpw6q5xbdyiaXmzawoR8vrgRBF4,2190 +google/api/httpbody_pb2.pyi,sha256=pu0vnjKqz3IYCvnBGtKAPmoBOWtHoFh3c5hTMTiyKbI,1569 +google/api/label.proto,sha256=PKepBECO1OlPifcmm0snQ3UKZoFUl-NDZNPB9jNhjis,1357 +google/api/label_pb2.py,sha256=r8q69IjSEhRAvwj70sBrMG_4RTWKCxfekgjfCRNV76E,2326 +google/api/label_pb2.pyi,sha256=vP8MIgmP7J05nYL4O_RzoLJUZvgQQdY3qdXuAZ4XMTk,1778 +google/api/launch_stage.proto,sha256=b_2A1p-UQwtHBLQPypoznhCIfzFe-masnDx9VYfWq6U,3083 +google/api/launch_stage_pb2.py,sha256=tccfkF9-iyEL7juvbyydjqOU-fCA7G1QbkG2AOv_uZI,2211 +google/api/launch_stage_pb2.pyi,sha256=EtU16uO1pQYSj4cm1CJAzgA-NTBFLnd2q2YC1otGpfc,1381 +google/api/log.proto,sha256=3IWk8lUNqBhbp7hc7ZLAoDJJmLKqy9CwBpHoXWR01T4,2043 +google/api/log_pb2.py,sha256=UPFyG1wPzDnJ6s0zKtRrAe5EOSdj289JM1t6dWA59Ic,2237 +google/api/log_pb2.pyi,sha256=HxEOSCZAjaZCqs6I3Q4oX23qjH3INyZKEbdS1YanSAU,1728 +google/api/logging.proto,sha256=sVIekQJhPtOpZpK8wtLnOl4Iy--1ZDpGtxrM4w99wzs,3174 +google/api/logging_pb2.py,sha256=Cu8Zr9svy7FFVVEv7BSXD4vRP32x92hl6tUbbCutgIQ,2395 +google/api/logging_pb2.pyi,sha256=0_UHF0exyA0Pi_S5PX_K8tmUxfLWwCa9HMXxKZrcXjw,2178 +google/api/metric.proto,sha256=iHOuTKsgogijIOrL94_ubiVAAmH6EmUAc2MYl5gBX5U,11166 +google/api/metric_pb2.py,sha256=wyFEUaGsR3YFrK125oYfwg4nadRxMKzkaJOmIzEraqo,5467 +google/api/metric_pb2.pyi,sha256=imNbq_jR33F4mT4MDaXqLapU53IUda_FGPP9hJurqIY,7729 +google/api/monitored_resource.proto,sha256=it3XqOY2YavpGJ_ENkF0dNkaBRcCmCRDbfXpQftq-y8,5888 +google/api/monitored_resource_pb2.py,sha256=AcbJY3seE1YqWutdfa_MmWCYeKluB1Yp7Hj8NGZ1YJ0,4146 +google/api/monitored_resource_pb2.pyi,sha256=BCemAlAZZ-DXfOiS2yB0h1UU8e5ana2qXSes5JfptXc,3644 +google/api/monitoring.proto,sha256=RSMvm0HLEKVfFSiC4IBZ65jeS-v7OvCM2pZXPpysRCY,4457 +google/api/monitoring_pb2.py,sha256=MbTpq9Cq2eP8zDVZRzFYcXG5hQXFdlFyFV0QhJRTzcI,2450 +google/api/monitoring_pb2.pyi,sha256=JOuU9dKJSTjev_zSU_cYl3naZqYJRiIw8joJP1Y9T_w,2220 +google/api/policy.proto,sha256=fQtYLa7_ejkzILClsGPyDJ8AP14-4c1X-P8O3MeB7zA,3110 +google/api/policy_pb2.py,sha256=phc-a2WEKc9ScjFQJ5Vn7eLl6AUrVIkEtpHm7UWHBfY,2685 +google/api/policy_pb2.pyi,sha256=N9FSJUBlyqQrSVFubEtnJxxT2LMPeXp-jVJtVKPaO2M,2169 +google/api/quota.proto,sha256=Rb3vETT8RHuWBwWq3i2MpKuvSaI7qDWzs9Xvfcu02bg,7180 +google/api/quota_pb2.py,sha256=4dlPOea85uY2LHTgMPM3sAEzAdq_laGkc29G7wmXm80,3612 +google/api/quota_pb2.pyi,sha256=ZFCjQUYm39fQG5O0bWJpThAU-EY2YVNBFHSsdg4gdqc,3876 +google/api/resource.proto,sha256=xmt3Wu8slcx7bwc_uI0U-HQW36d7H6dq2udMCko5No0,8994 +google/api/resource_pb2.py,sha256=o_VDQ6dFD2vDkWFVoATqd3kQn2lqbBrL2czsC0bFDt8,3534 +google/api/resource_pb2.pyi,sha256=qP5Y1250smP5TlO6oMvy2i5iEFQTjZqqXlxUPIh482g,3588 +google/api/routing.proto,sha256=2rJ-NJBhrzLGXR_wIZ6xl-dg8IweU9W0STxOf5DtIgM,14918 +google/api/routing_pb2.py,sha256=TeiGe55yzpa2nTKFb5vR8MkafVvz12glRydXlnyiZAY,2488 +google/api/routing_pb2.pyi,sha256=z7nFx78IfmaruAPgltVWo21QSa6g75rAVoAA4T89mIE,1821 +google/api/service.proto,sha256=Kz2yc9tG9g1C4OOU47AsFU5nOubTOqlpvfuThHg_1Ts,6762 +google/api/service_pb2.py,sha256=xBXDaVarbX3OJZtL243-sINSw-5vncRnKNmiryn_TVE,5857 +google/api/service_pb2.pyi,sha256=Ipz86MPZ3FXYyNqDq2X6P5GeJf5ePF7c2HnOX9kZo_E,7164 +google/api/source_info.proto,sha256=_eMTPgmMDJL5iFz8eSDRrfHYEbgqsVq6u4Eyj6Q1Seg,1091 +google/api/source_info_pb2.py,sha256=6JMwSfeho5eTK42fRpFj4PRa5zlxP9sFRUrI-__Y53M,2154 +google/api/source_info_pb2.pyi,sha256=65e7q_WYVA6Db1a1srDBkMTxErD6gp_Vq-oOIfGoJzc,1343 +google/api/system_parameter.proto,sha256=5cbh24sY6LbeS-vq3CRF-LJrRy_m-vBmQf6owbzYXZ4,3475 +google/api/system_parameter_pb2.py,sha256=bdWsFRs9C-JgUjA1cmg3ziN6HiuVYG7-gyv_ZbObcvk,2610 +google/api/system_parameter_pb2.pyi,sha256=_kZoYlhbvOzWBha-Xok9Yb4kQu-BOSXF7G5GW8tW-PY,2217 +google/api/usage.proto,sha256=ULlxQFu8N83Oe2OFFgJxjT9EZXkEs8t7vsvzxVTDpIQ,3787 +google/api/usage_pb2.py,sha256=VkRdoxqbm62zZ9-i3ba5RCXKVWFp1poSce84WlGOXB4,2353 +google/api/usage_pb2.pyi,sha256=pe0wm3i9Zyg0E1Xr9h_MhRXVS8gtkfjW4KTG_UH5iik,2175 +google/api/visibility.proto,sha256=78T35teJphbPXtEBmZy5lG76Lppb1lb-AWQaIeq-_EA,3767 +google/api/visibility_pb2.py,sha256=6rmDppleUZ9WEtnLyXGJhhkOeYOLl1sC5BmZ2g1tfV4,3113 +google/api/visibility_pb2.pyi,sha256=A_h87gi4Z60MvmeZfO7KWO3e7ijb2D5iRigIWIncMHI,2213 +google/cloud/__pycache__/extended_operations_pb2.cpython-312.pyc,, +google/cloud/extended_operations.proto,sha256=gI4lL58QZw4JOL01_j5Rirk5A00f6MG0P0m5eX9ytSM,6307 +google/cloud/extended_operations_pb2.py,sha256=QJR2kjmka8_-DuAw39vNK48YJr7cj3QONqtNOyqxPCc,2815 +google/cloud/extended_operations_pb2.pyi,sha256=7OLGIjrs7vyd0YZRbbF1bml4JF9hSdolMCEnR3XSE90,1889 +google/cloud/location/__pycache__/locations_pb2.cpython-312.pyc,, +google/cloud/location/locations.proto,sha256=QPoDwHP-htlXfOl9mtm2XzWOmXMHzbxX1fYIvfAeAs4,3604 +google/cloud/location/locations_pb2.py,sha256=eNNhDPgQOPmC8GxKji-mc02uuF8OHXx_QMygu5kFkl0,5076 +google/cloud/location/locations_pb2.pyi,sha256=PFsMJx4ezSaATaJoKcCklfM4ClxK0KpxEFCWfNO6yBs,3392 +google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-312.pyc,, +google/gapic/metadata/gapic_metadata.proto,sha256=qA0S83aZDPFroSiQklzeqXRL0RZpH73clCIfmviCz5M,3393 +google/gapic/metadata/gapic_metadata_pb2.py,sha256=nA0vVAPz-iq86t6RiLaIdMWcko821NugnwzXUJarr4s,4770 +google/gapic/metadata/gapic_metadata_pb2.pyi,sha256=0HeHzue5iOSf9QHXiZ-Ak8afbwoemNpjUPa2kk_O6Wo,4350 +google/logging/type/__pycache__/http_request_pb2.cpython-312.pyc,, +google/logging/type/__pycache__/log_severity_pb2.cpython-312.pyc,, +google/logging/type/http_request.proto,sha256=zxYFInPIcyFDrWQYwN4FmqSaOy9AL2Lmp8Y0kUNsxGU,3601 +google/logging/type/http_request_pb2.py,sha256=piQn43w_HdIZks6P0hY0fvCb1JlOL5ppbEUaLHThnqU,3022 +google/logging/type/http_request_pb2.pyi,sha256=Ar76mTRYKUJwcp22VO6BqwRBQ_AtejqK6kP2dpMwdVg,3102 +google/logging/type/log_severity.proto,sha256=zqnBXSkSV3PGG0sBjdvJs9fwiKL3N9anTjjxtgfdpR4,2555 +google/logging/type/log_severity_pb2.py,sha256=upDt6IutB1_pQv7EmY8JA0E62GNJWY0gwahQQxiWTVo,2567 +google/logging/type/log_severity_pb2.pyi,sha256=47i081SvX-t7hqlZzmzy8NZj7OK3myeoNeupVCHWi_0,1378 +google/longrunning/__pycache__/operations_grpc.cpython-312.pyc,, +google/longrunning/__pycache__/operations_grpc_pb2.cpython-312.pyc,, +google/longrunning/__pycache__/operations_pb2.cpython-312.pyc,, +google/longrunning/__pycache__/operations_pb2_grpc.cpython-312.pyc,, +google/longrunning/__pycache__/operations_proto.cpython-312.pyc,, +google/longrunning/__pycache__/operations_proto_pb2.cpython-312.pyc,, +google/longrunning/operations_grpc.py,sha256=ZtTe_7HJsDWG4OZol8Qi0qoV7HkK4BAxt8Vh0Vh_-xs,818 +google/longrunning/operations_grpc_pb2.py,sha256=wke5BQbTHeJdOp7yrHkxZEQ9PbFsylmBHvlQy4bMJks,531 +google/longrunning/operations_pb2.py,sha256=yl_cw1pTXrWgDzQhL00ec_OtpwrehOjkFONBbp-SjxY,1569 +google/longrunning/operations_pb2_grpc.py,sha256=RSz_oLtcDUyNPSpMUAgcKeTdicEDY5FwR1VoXnTD8YU,14463 +google/longrunning/operations_proto.proto,sha256=_PVg87i50b3agoAwJqyMqmFrDuGdD1VOjrnvey8gH8I,10041 +google/longrunning/operations_proto.py,sha256=vIe7RoVZfjsS7MSZB487GGMIB_5_7--sT_cyt8coGCk,243 +google/longrunning/operations_proto_pb2.py,sha256=_OHoYECsEw-3oRoJ93tVa3XR0LnspFPgoAavh_1qLBk,7231 +google/longrunning/operations_proto_pb2.pyi,sha256=5_V9vvbdpSXXdEyn1ZoBNpPjWa0bFX3CV6wtGeVD3u8,4490 +google/rpc/__pycache__/code_pb2.cpython-312.pyc,, +google/rpc/__pycache__/error_details_pb2.cpython-312.pyc,, +google/rpc/__pycache__/http_pb2.cpython-312.pyc,, +google/rpc/__pycache__/status_pb2.cpython-312.pyc,, +google/rpc/code.proto,sha256=mZO-ZeBQwwztJGlRZZ2-ChNmO3fPV7yqTA7UJISA-4A,7138 +google/rpc/code_pb2.py,sha256=Eq_wIEwpez471XG98qRFzh9HfH9WqJO34nNqVq2pfqU,2479 +google/rpc/code_pb2.pyi,sha256=S0tVsFZr7_QXpLUhRkRCqDj3EoaNAO0Rn5FV7SXIaqs,1771 +google/rpc/context/__pycache__/attribute_context_pb2.cpython-312.pyc,, +google/rpc/context/__pycache__/audit_context_pb2.cpython-312.pyc,, +google/rpc/context/attribute_context.proto,sha256=N1ep-oYDKN17blsZ0Tm94EBQjNCF6RTDn-1ISCvZf2M,14888 +google/rpc/context/attribute_context_pb2.py,sha256=Prgv8s1MX5OYQQG6IiHs-xgaEH2jST-vvQ2ICyQeWAQ,8476 +google/rpc/context/attribute_context_pb2.pyi,sha256=BSNNTFwtxVhGYcIDUFIFEHnT7oTDZQ-TVfuFbgGm6mk,11467 +google/rpc/context/audit_context.proto,sha256=VtSqp3dOiyq8vcBeqt3hmrf2lTLjL0zWy_hHzFDY-dI,1829 +google/rpc/context/audit_context_pb2.py,sha256=ExXBm8u9WtIAyNbwcEqfbOOR0kr-ujZNnXCol2JrimE,2416 +google/rpc/context/audit_context_pb2.pyi,sha256=G3mCF1BRTuDkWmskAJlS2mtNWvkwgCbkI5MAlF4winA,1922 +google/rpc/error_details.proto,sha256=2j9awTBKv9arL5WbSsPmywdYtS_KOIwia_O5KvleB-0,14599 +google/rpc/error_details_pb2.py,sha256=YHYw73kEHgtFY1Fj2H9uVlXKXUymlRvfWp-NRVCxJFI,6457 +google/rpc/error_details_pb2.pyi,sha256=nKJmFDweBR5hB6RrBPtQphwGaArve0jSUUn58F9icKg,8436 +google/rpc/http.proto,sha256=Y_VGMfkjQQsZcEJGvGg1WZyRli_4pQKMjigGdtmnpKM,1940 +google/rpc/http_pb2.py,sha256=EP1gtpeBAkkepAogsKjN-01PTxZmF9_D_Rf0B3Xxxb4,2568 +google/rpc/http_pb2.pyi,sha256=XakmiDuqsd36SU1F1F-83EPLYVrjTdBeYX0-iNXhfdc,2467 +google/rpc/status.proto,sha256=O1xxJFVXCsQ0LdPFIcTBEBFlKumg-8p1uiL8xFxuGZE,1934 +google/rpc/status_pb2.py,sha256=COt5Svr-fTOgVdaQn2ad_NJnerEG8LF64_HQxSQPCx4,2186 +google/rpc/status_pb2.pyi,sha256=t6HXKXT0R6KoNoDacgCv1JNZqT6U2XCvr4J3QejgZsU,1531 +google/type/__pycache__/calendar_period_pb2.cpython-312.pyc,, +google/type/__pycache__/color_pb2.cpython-312.pyc,, +google/type/__pycache__/date_pb2.cpython-312.pyc,, +google/type/__pycache__/datetime_pb2.cpython-312.pyc,, +google/type/__pycache__/dayofweek_pb2.cpython-312.pyc,, +google/type/__pycache__/decimal_pb2.cpython-312.pyc,, +google/type/__pycache__/expr_pb2.cpython-312.pyc,, +google/type/__pycache__/fraction_pb2.cpython-312.pyc,, +google/type/__pycache__/interval_pb2.cpython-312.pyc,, +google/type/__pycache__/latlng_pb2.cpython-312.pyc,, +google/type/__pycache__/localized_text_pb2.cpython-312.pyc,, +google/type/__pycache__/money_pb2.cpython-312.pyc,, +google/type/__pycache__/month_pb2.cpython-312.pyc,, +google/type/__pycache__/phone_number_pb2.cpython-312.pyc,, +google/type/__pycache__/postal_address_pb2.cpython-312.pyc,, +google/type/__pycache__/quaternion_pb2.cpython-312.pyc,, +google/type/__pycache__/timeofday_pb2.cpython-312.pyc,, +google/type/calendar_period.proto,sha256=OAXB5eqDicGI9pm801iKPoNzo46TAsiLbgrk8Ni4ZMQ,1762 +google/type/calendar_period_pb2.py,sha256=pW8k2WCxY7w9i9NEnxsF4o4SUhIfZ-Eh8lZBrF3zeiM,2285 +google/type/calendar_period_pb2.pyi,sha256=sVo812wLSg28VeC_oZHNSNbvxWgbbw-FWyWDA1IK_xg,1400 +google/type/color.proto,sha256=XIdgtG2bqDiYUYO6EViIDMSxBNX_Bc_HFKd2gI4olCs,6376 +google/type/color_pb2.py,sha256=BHazOofpTJ7g3qIqnGJ3vj7XrnUU8GelAQA4LbIRipw,2233 +google/type/color_pb2.pyi,sha256=40iw29SFgBeB0OlAnvTkr9c_2ODa73BAiokAmzpGZOo,1492 +google/type/date.proto,sha256=69oyw_O0XTnkItK4sf8BKPl5JZo5JtDjD5yqnxLDaXY,1955 +google/type/date_pb2.py,sha256=x22mullNBqVTf4KLYb5Ya81HG4_PC0QW3FDyHr_8xf4,2036 +google/type/date_pb2.pyi,sha256=bhco_u3qTskpSxPthxrNYoafvupno3P7D0PDOfiw8KU,1187 +google/type/datetime.proto,sha256=jOmz3PTZV8Sw6XgxJrNsNmaqDyP2b3Du6jGdpg0b2Yc,3905 +google/type/datetime_pb2.py,sha256=eBRCOl4yxxKLUMS14danF4Y5qRbFImphC0wjwCyWRzY,2712 +google/type/datetime_pb2.pyi,sha256=lpcUmSY0MQjnrj8f3wrjBdvrVNUXoAy6nilNaas6Msk,2420 +google/type/dayofweek.proto,sha256=cC8e6Jea90WL2Inoqr0kaa_WtVV9Pk9u6jyVoadvsFI,1204 +google/type/dayofweek_pb2.py,sha256=_5TI05lKJi-hcsjpwW1BIMvgkFdyEOJ2IYTLUe3s0Sk,2224 +google/type/dayofweek_pb2.pyi,sha256=RbF1ibri8xloSPPHR25zNuzBTzpwbzn6u_FGsT_P4iE,1335 +google/type/decimal.proto,sha256=Cj28BcCpaIs6DYJF7sIwwh95CUNfg3b-eOapyhjzPyM,4213 +google/type/decimal_pb2.py,sha256=ewihkKVH_IK8g_z6_euwCRkytv0PSsNa2TJamGSNGy8,2009 +google/type/decimal_pb2.pyi,sha256=ETMNgbDSMkwbwVzF1dy1iYv5F1vfSZVrZTacBiqw4MQ,980 +google/type/expr.proto,sha256=JWLcgHPkx4-pj9FqTG7_DLZ0lc1eg91rqdhq8bMRPtg,2730 +google/type/expr_pb2.py,sha256=1DGnypBaqJ-Bh1u49FbUHYzgVp6ecbMT8oGhHElO5qw,2051 +google/type/expr_pb2.pyi,sha256=8pRxBNy6-l60abONgar3wsRFxhNO17AXXXbZkv1-aHc,1355 +google/type/fraction.proto,sha256=-ptSvXZFwJxewNAE50EbgsmL6dzINhbsxWFlLkRQfNo,1156 +google/type/fraction_pb2.py,sha256=IdO2Pnaxpp8EvMOpGevxem76pW9l0iSnrwcQwuevWaY,2042 +google/type/fraction_pb2.pyi,sha256=xxowlWmKi9jiqpTxJPJVuUW4-OqpmT_7Jp-D1liGaSY,1126 +google/type/interval.proto,sha256=5oGq4zYaofvPJEYEX3u9LN_ELGv7IBhmbUnjex3wwmM,1667 +google/type/interval_pb2.py,sha256=3Cg2YoKtn7IjCksaFizONvt-dQJwVKclS8p-ttQ1sv8,2239 +google/type/interval_pb2.pyi,sha256=madlH1_IMGBMoFfLY5RWpIyFVVzKuofwxngaHcEzOf4,1389 +google/type/latlng.proto,sha256=yjtnGUXCu7uCmBLi2HtR0-9HyJg-f7jLG3jzCQu6CTU,1447 +google/type/latlng_pb2.py,sha256=XKy0WRgnCBFCvAOYzFyYomZloEjroYtsg1igsfNILs8,2028 +google/type/latlng_pb2.pyi,sha256=H1_dd3GUfw-M3Cro2VoyUQTN44XDXKTWaYrp_Kt_nek,1120 +google/type/localized_text.proto,sha256=n-jVp6nFv3cUP-EBvx8k0ByhwSxKieTR50V4Tvfd4P4,1303 +google/type/localized_text_pb2.py,sha256=YjdRGfXKqAU-pJzbNfd0kK42ONOtPXj3nB-hgiRRM28,2111 +google/type/localized_text_pb2.pyi,sha256=lHUdsojwSWDYMNBDzSy4_9OKyflCBdA91wZ0TAR5d-A,1119 +google/type/money.proto,sha256=G25nFBn5nzFqwt2oubvWY0C2o0ALVzyzKmbl-jlRQ4Q,1603 +google/type/money_pb2.py,sha256=Pd_jpuEU2bh50bsqMMcqkISAQmn4Kn7dFvTUj9oJxdM,2042 +google/type/money_pb2.pyi,sha256=dTUleurCYBGl3UsFgEL-AIGerrPd6-HUAX02kLmXZ4Y,1232 +google/type/month.proto,sha256=eV-_zptOPtecuZKAeEBh1v6pR-TCk1El6O51ib3BPSY,1479 +google/type/month_pb2.py,sha256=9mxuKSZkDEjZCNVoUWLqAt4zsj8XCiPQJy_8dfnERlQ,2304 +google/type/month_pb2.pyi,sha256=CP_EBA3rCkhfHRqOQDQMKl8sv3gvQjpW69kQ7T5Mdss,1458 +google/type/phone_number.proto,sha256=iU54bBbuZE6rr8MkeYGk_a4vMZlmum0iKH5lNeDswWo,4744 +google/type/phone_number_pb2.py,sha256=EsKshTlAFZvGvp5P96tJkQ8gAETMjto9UgluJBCpsJc,2440 +google/type/phone_number_pb2.pyi,sha256=9WRpktB1Izwhudosa_Vn9dAuTRXLfZ1gcFfyL5kDn6o,1745 +google/type/postal_address.proto,sha256=Qq00XgJS4be_TQvjEPPMp6Mh3Nxb5UgZcNivhZqu_N8,6235 +google/type/postal_address_pb2.py,sha256=vJaDXgkvp_gWwHyCCBon6sfbfh0vgN0DcsQTQ9VgWic,2495 +google/type/postal_address_pb2.pyi,sha256=STB5j1C7kWT4arbDBmhG2gEA0fdOKcRol-QAd3JMv6U,2605 +google/type/quaternion.proto,sha256=XWOdCa1H4PVZtnODi3u8xP3yhXJXbaOpjdPMYdteWdg,3791 +google/type/quaternion_pb2.py,sha256=67r5JEckZ7IxdLysefpDVqujQWNEC27vZUAa4gZaMqo,2123 +google/type/quaternion_pb2.pyi,sha256=78kj_z0GXrulbyoCcbon2tzlWsYHwwoTPVnWOWl1aOk,1257 +google/type/timeofday.proto,sha256=PDCWTz-sDVulKoUYE-gZqB50T6hGG8kNWFkxovpSo0I,1667 +google/type/timeofday_pb2.py,sha256=6F_QiHtrRB7kpb_2osC73OfVi2O6fy8Ed7RKDEjgUt8,2135 +google/type/timeofday_pb2.pyi,sha256=B9mzMCS_LEgqUGrvb_0fNDY0AnKcduAuN5mJe7xjn1s,1320 +googleapis_common_protos-1.70.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +googleapis_common_protos-1.70.0.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +googleapis_common_protos-1.70.0.dist-info/METADATA,sha256=-uM1fX8pRq2Hbq7SSV24141IFYzHwF26TI7xzpWx_T8,9293 +googleapis_common_protos-1.70.0.dist-info/RECORD,, +googleapis_common_protos-1.70.0.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91 +googleapis_common_protos-1.70.0.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7 diff --git a/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9b78c44519d450e4036a1ea44361a2ac7b1ee300 --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.3.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb429113e0f9a73019fd799e8052093fea7f0c8b --- /dev/null +++ b/python_embeded/Lib/site-packages/googleapis_common_protos-1.70.0.dist-info/top_level.txt @@ -0,0 +1 @@ +google diff --git a/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/INSTALLER b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/METADATA b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..16d8f6c1149a937e08f49374ac1961662fb12238 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/METADATA @@ -0,0 +1,116 @@ +Metadata-Version: 2.4 +Name: greenlet +Version: 3.2.3 +Summary: Lightweight in-process concurrent programming +Home-page: https://greenlet.readthedocs.io/ +Author: Alexey Borzenkov +Author-email: snaury@gmail.com +Maintainer: Jason Madden +Maintainer-email: jason@seecoresoftware.com +License: MIT AND Python-2.0 +Project-URL: Bug Tracker, https://github.com/python-greenlet/greenlet/issues +Project-URL: Source Code, https://github.com/python-greenlet/greenlet/ +Project-URL: Documentation, https://greenlet.readthedocs.io/ +Project-URL: Changes, https://greenlet.readthedocs.io/en/latest/changes.html +Keywords: greenlet coroutine concurrency threads cooperative +Platform: any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: LICENSE.PSF +Provides-Extra: docs +Requires-Dist: Sphinx; extra == "docs" +Requires-Dist: furo; extra == "docs" +Provides-Extra: test +Requires-Dist: objgraph; extra == "test" +Requires-Dist: psutil; extra == "test" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: maintainer +Dynamic: maintainer-email +Dynamic: platform +Dynamic: project-url +Dynamic: provides-extra +Dynamic: requires-python +Dynamic: summary + +.. This file is included into docs/history.rst + + +Greenlets are lightweight coroutines for in-process concurrent +programming. + +The "greenlet" package is a spin-off of `Stackless`_, a version of +CPython that supports micro-threads called "tasklets". Tasklets run +pseudo-concurrently (typically in a single or a few OS-level threads) +and are synchronized with data exchanges on "channels". + +A "greenlet", on the other hand, is a still more primitive notion of +micro-thread with no implicit scheduling; coroutines, in other words. +This is useful when you want to control exactly when your code runs. +You can build custom scheduled micro-threads on top of greenlet; +however, it seems that greenlets are useful on their own as a way to +make advanced control flow structures. For example, we can recreate +generators; the difference with Python's own generators is that our +generators can call nested functions and the nested functions can +yield values too. (Additionally, you don't need a "yield" keyword. See +the example in `test_generator.py +`_). + +Greenlets are provided as a C extension module for the regular unmodified +interpreter. + +.. _`Stackless`: http://www.stackless.com + + +Who is using Greenlet? +====================== + +There are several libraries that use Greenlet as a more flexible +alternative to Python's built in coroutine support: + + - `Concurrence`_ + - `Eventlet`_ + - `Gevent`_ + +.. _Concurrence: http://opensource.hyves.org/concurrence/ +.. _Eventlet: http://eventlet.net/ +.. _Gevent: http://www.gevent.org/ + +Getting Greenlet +================ + +The easiest way to get Greenlet is to install it with pip:: + + pip install greenlet + + +Source code archives and binary distributions are available on the +python package index at https://pypi.org/project/greenlet + +The source code repository is hosted on github: +https://github.com/python-greenlet/greenlet + +Documentation is available on readthedocs.org: +https://greenlet.readthedocs.io diff --git a/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/RECORD b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..113799c39f6fc71b94fa2e66123f424ccaf0c99e --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/RECORD @@ -0,0 +1,123 @@ +../../Include/greenlet/greenlet.h,sha256=sz5pYRSQqedgOt2AMgxLZdTjO-qcr_JMvgiEJR9IAJ8,4755 +greenlet-3.2.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +greenlet-3.2.3.dist-info/METADATA,sha256=Z76Mmf-WlSsB5QvlJgOhzQsUocuJHWaBGGesXcu3ZtE,4193 +greenlet-3.2.3.dist-info/RECORD,, +greenlet-3.2.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +greenlet-3.2.3.dist-info/WHEEL,sha256=8UP9x9puWI0P1V_d7K2oMTBqfeLNm21CTzZ_Ptr0NXU,101 +greenlet-3.2.3.dist-info/direct_url.json,sha256=LkWNy0p6cmW7yxtbTAZ05SbreP3B0-4uH2IePpQ3XYQ,281 +greenlet-3.2.3.dist-info/licenses/LICENSE,sha256=dpgx1uXfrywggC-sz_H6-0wgJd2PYlPfpH_K1Z1NCXk,1434 +greenlet-3.2.3.dist-info/licenses/LICENSE.PSF,sha256=5f88I8EQ5JTNfXNsEP2W1GJFe6_soxCEDbZScpjH1Gs,2424 +greenlet-3.2.3.dist-info/top_level.txt,sha256=YSnRsCRoO61JGlP57o8iKL6rdLWDWuiyKD8ekpWUsDc,9 +greenlet/CObjects.cpp,sha256=OPej1bWBgc4sRrTRQ2aFFML9pzDYKlKhlJSjsI0X_eU,3508 +greenlet/PyGreenlet.cpp,sha256=ogWsQ5VhSdItWRLLpWOgSuqYuM3QwQ4cVCxOQIgHx6E,23441 +greenlet/PyGreenlet.hpp,sha256=2ZQlOxYNoy7QwD7mppFoOXe_At56NIsJ0eNsE_hoSsw,1463 +greenlet/PyGreenletUnswitchable.cpp,sha256=PQE0fSZa_IOyUM44IESHkJoD2KtGW3dkhkmZSYY3WHs,4375 +greenlet/PyModule.cpp,sha256=J2TH06dGcNEarioS6NbWXkdME8hJY05XVbdqLrfO5w4,8587 +greenlet/TBrokenGreenlet.cpp,sha256=smN26uC7ahAbNYiS10rtWPjCeTG4jevM8siA2sjJiXg,1021 +greenlet/TExceptionState.cpp,sha256=U7Ctw9fBdNraS0d174MoQW7bN-ae209Ta0JuiKpcpVI,1359 +greenlet/TGreenlet.cpp,sha256=HGYGKpmKYqQ842tASW-QaaV8wua4a5XV_quYKPDsV_Y,25731 +greenlet/TGreenlet.hpp,sha256=zMakwTJ30onkLiAq5h1WR7ewEkiJXKM0N9AR6BnXQMI,28141 +greenlet/TGreenletGlobals.cpp,sha256=YyEmDjKf1g32bsL-unIUScFLnnA1fzLWf2gOMd-D0Zw,3264 +greenlet/TMainGreenlet.cpp,sha256=fvgb8HHB-FVTPEKjR1s_ifCZSpp5D5YQByik0CnIABg,3276 +greenlet/TPythonState.cpp,sha256=vBMJT9qScTSIqhnOTVJqsGug3WbKv9dDt0cOqyhUk8w,15779 +greenlet/TStackState.cpp,sha256=V444I8Jj9DhQz-9leVW_9dtiSRjaE1NMlgDG02Xxq-Y,7381 +greenlet/TThreadState.hpp,sha256=2Jgg7DtGggMYR_x3CLAvAFf1mIdIDtQvSSItcdmX4ZQ,19131 +greenlet/TThreadStateCreator.hpp,sha256=uYTexDWooXSSgUc5uh-Mhm5BQi3-kR6CqpizvNynBFQ,2610 +greenlet/TThreadStateDestroy.cpp,sha256=36yBCAMq3beXTZd-XnFA7DwaHVSOx2vc28-nf0spysU,8169 +greenlet/TUserGreenlet.cpp,sha256=uemg0lwKXtYB0yzmvyYdIIAsKnNkifXM1OJ2OlrFP1A,23553 +greenlet/__init__.py,sha256=1zAfqzVVnBnQhxOL6UZ0t9jrNJUNJRgPEFvzW1qss9k,1723 +greenlet/__pycache__/__init__.cpython-312.pyc,, +greenlet/_greenlet.cp312-win_amd64.pyd,sha256=MpVz1lA-ermllxJVWE_cG5RV7cc6RfrfpoJJTFjZlqI,219136 +greenlet/greenlet.cpp,sha256=WdItb1yWL9WNsTqJNf0Iw8ZwDHD49pkDP0rIRGBg2pw,10996 +greenlet/greenlet.h,sha256=sz5pYRSQqedgOt2AMgxLZdTjO-qcr_JMvgiEJR9IAJ8,4755 +greenlet/greenlet_allocator.hpp,sha256=kxyWW4Qdwlrc7ufgdb5vd6Y7jhauQ699Kod0mqiO1iM,1582 +greenlet/greenlet_compiler_compat.hpp,sha256=nRxpLN9iNbnLVyFDeVmOwyeeNm6scQrOed1l7JQYMCM,4346 +greenlet/greenlet_cpython_compat.hpp,sha256=XrsoFv8nKavrdxly5_-q9lqGeE8d3wKt1YtldsAHAT8,4068 +greenlet/greenlet_exceptions.hpp,sha256=06Bx81DtVaJTa6RtiMcV141b-XHv4ppEgVItkblcLWY,4503 +greenlet/greenlet_internal.hpp,sha256=Ajc-_09W4xWzm9XfyXHAeQAFUgKGKsnJwYsTCoNy3ns,2709 +greenlet/greenlet_msvc_compat.hpp,sha256=0MyaiyoCE_A6UROXZlMQRxRS17gfyh0d7NUppU3EVFc,2978 +greenlet/greenlet_refs.hpp,sha256=OnbA91yZf3QHH6-eJccvoNDAaN-pQBMMrclFU1Ot3J4,34436 +greenlet/greenlet_slp_switch.hpp,sha256=kM1QHA2iV-gH4cFyN6lfIagHQxvJZjWOVJdIxRE3TlQ,3198 +greenlet/greenlet_thread_support.hpp,sha256=XUJ6ljWjf9OYyuOILiz8e_yHvT3fbaUiHdhiPNQUV4s,867 +greenlet/platform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +greenlet/platform/__pycache__/__init__.cpython-312.pyc,, +greenlet/platform/setup_switch_x64_masm.cmd,sha256=ZpClUJeU0ujEPSTWNSepP0W2f9XiYQKA8QKSoVou8EU,143 +greenlet/platform/switch_aarch64_gcc.h,sha256=GKC0yWNXnbK2X--X6aguRCMj2Tg7hDU1Zkl3RljDvC8,4307 +greenlet/platform/switch_alpha_unix.h,sha256=Z-SvF8JQV3oxWT8JRbL9RFu4gRFxPdJ7cviM8YayMmw,671 +greenlet/platform/switch_amd64_unix.h,sha256=EcSFCBlodEBhqhKjcJqY_5Dn_jn7pKpkJlOvp7gFXLI,2748 +greenlet/platform/switch_arm32_gcc.h,sha256=Z3KkHszdgq6uU4YN3BxvKMG2AdDnovwCCNrqGWZ1Lyo,2479 +greenlet/platform/switch_arm32_ios.h,sha256=mm5_R9aXB92hyxzFRwB71M60H6AlvHjrpTrc72Pz3l8,1892 +greenlet/platform/switch_arm64_masm.asm,sha256=4kpTtfy7rfcr8j1CpJLAK21EtZpGDAJXWRU68HEy5A8,1245 +greenlet/platform/switch_arm64_masm.obj,sha256=DmLnIB_icoEHAz1naue_pJPTZgR9ElM7-Nmztr-o9_U,746 +greenlet/platform/switch_arm64_msvc.h,sha256=RqK5MHLmXI3Q-FQ7tm32KWnbDNZKnkJdq8CR89cz640,398 +greenlet/platform/switch_csky_gcc.h,sha256=kDikyiPpewP71KoBZQO_MukDTXTXBiC7x-hF0_2DL0w,1331 +greenlet/platform/switch_loongarch64_linux.h,sha256=7M-Dhc4Q8tRbJCJhalDLwU6S9Mx8MjmN1RbTDgIvQTM,779 +greenlet/platform/switch_m68k_gcc.h,sha256=VSa6NpZhvyyvF-Q58CTIWSpEDo4FKygOyTz00whctlw,928 +greenlet/platform/switch_mips_unix.h,sha256=E0tYsqc5anDY1BhenU1l8DW-nVHC_BElzLgJw3TGtPk,1426 +greenlet/platform/switch_ppc64_aix.h,sha256=_BL0iyRr3ZA5iPlr3uk9SJ5sNRWGYLrXcZ5z-CE9anE,3860 +greenlet/platform/switch_ppc64_linux.h,sha256=0rriT5XyxPb0GqsSSn_bP9iQsnjsPbBmu0yqo5goSyQ,3815 +greenlet/platform/switch_ppc_aix.h,sha256=pHA4slEjUFP3J3SYm1TAlNPhgb2G_PAtax5cO8BEe1A,2941 +greenlet/platform/switch_ppc_linux.h,sha256=YwrlKUzxlXuiKMQqr6MFAV1bPzWnmvk6X1AqJZEpOWU,2759 +greenlet/platform/switch_ppc_macosx.h,sha256=Z6KN_ud0n6nC3ltJrNz2qtvER6vnRAVRNH9mdIDpMxY,2624 +greenlet/platform/switch_ppc_unix.h,sha256=-ZG7MSSPEA5N4qO9PQChtyEJ-Fm6qInhyZm_ZBHTtMg,2652 +greenlet/platform/switch_riscv_unix.h,sha256=606V6ACDf79Fz_WGItnkgbjIJ0pGg_sHmPyDxQYKK58,949 +greenlet/platform/switch_s390_unix.h,sha256=RRlGu957ybmq95qNNY4Qw1mcaoT3eBnW5KbVwu48KX8,2763 +greenlet/platform/switch_sh_gcc.h,sha256=mcRJBTu-2UBf4kZtX601qofwuDuy-Y-hnxJtrcaB7do,901 +greenlet/platform/switch_sparc_sun_gcc.h,sha256=xZish9GsMHBienUbUMsX1-ZZ-as7hs36sVhYIE3ew8Y,2797 +greenlet/platform/switch_x32_unix.h,sha256=nM98PKtzTWc1lcM7TRMUZJzskVdR1C69U1UqZRWX0GE,1509 +greenlet/platform/switch_x64_masm.asm,sha256=nu6n2sWyXuXfpPx40d9YmLfHXUc1sHgeTvX1kUzuvEM,1841 +greenlet/platform/switch_x64_masm.obj,sha256=GNtTNxYdo7idFUYsQv-mrXWgyT5EJ93-9q90lN6svtQ,1078 +greenlet/platform/switch_x64_msvc.h,sha256=LIeasyKo_vHzspdMzMHbosRhrBfKI4BkQOh4qcTHyJw,1805 +greenlet/platform/switch_x86_msvc.h,sha256=TtGOwinbFfnn6clxMNkCz8i6OmgB6kVRrShoF5iT9to,12838 +greenlet/platform/switch_x86_unix.h,sha256=VplW9H0FF0cZHw1DhJdIUs5q6YLS4cwb2nYwjF83R1s,3059 +greenlet/slp_platformselect.h,sha256=hTb3GFdcPUYJTuu1MY93js7MZEax1_e5E-gflpi0RzI,3959 +greenlet/tests/__init__.py,sha256=sqxm7-dZuGBwmNI0n6xrcQJGoHHjoXUGyUTnvHidcYM,9361 +greenlet/tests/__pycache__/__init__.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_clearing_run_switches.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_cpp_exception.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_initialstub_already_started.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_slp_switch.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_switch_three_greenlets.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_switch_three_greenlets2.cpython-312.pyc,, +greenlet/tests/__pycache__/fail_switch_two_greenlets.cpython-312.pyc,, +greenlet/tests/__pycache__/leakcheck.cpython-312.pyc,, +greenlet/tests/__pycache__/test_contextvars.cpython-312.pyc,, +greenlet/tests/__pycache__/test_cpp.cpython-312.pyc,, +greenlet/tests/__pycache__/test_extension_interface.cpython-312.pyc,, +greenlet/tests/__pycache__/test_gc.cpython-312.pyc,, +greenlet/tests/__pycache__/test_generator.cpython-312.pyc,, +greenlet/tests/__pycache__/test_generator_nested.cpython-312.pyc,, +greenlet/tests/__pycache__/test_greenlet.cpython-312.pyc,, +greenlet/tests/__pycache__/test_greenlet_trash.cpython-312.pyc,, +greenlet/tests/__pycache__/test_leaks.cpython-312.pyc,, +greenlet/tests/__pycache__/test_stack_saved.cpython-312.pyc,, +greenlet/tests/__pycache__/test_throw.cpython-312.pyc,, +greenlet/tests/__pycache__/test_tracing.cpython-312.pyc,, +greenlet/tests/__pycache__/test_version.cpython-312.pyc,, +greenlet/tests/__pycache__/test_weakref.cpython-312.pyc,, +greenlet/tests/_test_extension.c,sha256=vkeGA-6oeJcGILsD7oIrT1qZop2GaTOHXiNT7mcSl-0,5773 +greenlet/tests/_test_extension.cp312-win_amd64.pyd,sha256=uIVTvonMeyz30aZ3IKnN5HfC9-gAK1o2fnwTKAZfpEw,14336 +greenlet/tests/_test_extension_cpp.cp312-win_amd64.pyd,sha256=VVx6lmPR9RYZD1EirjB00jezXP-s2OgEuUYK93e4HGA,15872 +greenlet/tests/_test_extension_cpp.cpp,sha256=e0kVnaB8CCaEhE9yHtNyfqTjevsPDKKx-zgxk7PPK48,6565 +greenlet/tests/fail_clearing_run_switches.py,sha256=o433oA_nUCtOPaMEGc8VEhZIKa71imVHXFw7TsXaP8M,1263 +greenlet/tests/fail_cpp_exception.py,sha256=o_ZbipWikok8Bjc-vjiQvcb5FHh2nVW-McGKMLcMzh0,985 +greenlet/tests/fail_initialstub_already_started.py,sha256=txENn5IyzGx2p-XR1XB7qXmC8JX_4mKDEA8kYBXUQKc,1961 +greenlet/tests/fail_slp_switch.py,sha256=rJBZcZfTWR3e2ERQtPAud6YKShiDsP84PmwOJbp4ey0,524 +greenlet/tests/fail_switch_three_greenlets.py,sha256=zSitV7rkNnaoHYVzAGGLnxz-yPtohXJJzaE8ehFDQ0M,956 +greenlet/tests/fail_switch_three_greenlets2.py,sha256=FPJensn2EJxoropl03JSTVP3kgP33k04h6aDWWozrOk,1285 +greenlet/tests/fail_switch_two_greenlets.py,sha256=1CaI8s3504VbbF1vj1uBYuy-zxBHVzHPIAd1LIc8ONg,817 +greenlet/tests/leakcheck.py,sha256=inbfM7_oVzd8jIKGxCgo4JqpFZaDAnWPkSULJ8vIE1s,11964 +greenlet/tests/test_contextvars.py,sha256=xutO-qZgKTwKsA9lAqTjIcTBEiQV4RpNKM-vO2_YCVU,10541 +greenlet/tests/test_cpp.py,sha256=hpxhFAdKJTpAVZP8CBGs1ZcrKdscI9BaDZk4btkI5d4,2736 +greenlet/tests/test_extension_interface.py,sha256=eJ3cwLacdK2WbsrC-4DgeyHdwLRcG4zx7rrkRtqSzC4,3829 +greenlet/tests/test_gc.py,sha256=PCOaRpIyjNnNlDogGL3FZU_lrdXuM-pv1rxeE5TP5mc,2923 +greenlet/tests/test_generator.py,sha256=tONXiTf98VGm347o1b-810daPiwdla5cbpFg6QI1R1g,1240 +greenlet/tests/test_generator_nested.py,sha256=7v4HOYrf1XZP39dk5IUMubdZ8yc3ynwZcqj9GUJyMSA,3718 +greenlet/tests/test_greenlet.py,sha256=rYWDvMx7ZpMlQju9KRxsBR61ela7HSJCg98JtR7RPOQ,46251 +greenlet/tests/test_greenlet_trash.py,sha256=n2dBlQfOoEO1ODatFi8QdhboH3fB86YtqzcYMYOXxbw,7947 +greenlet/tests/test_leaks.py,sha256=Qeso_qH9MCWJOkk2I3VcTh7UhaNvWxrzAmNBta-fUyY,17714 +greenlet/tests/test_stack_saved.py,sha256=eyzqNY2VCGuGlxhT_In6TvZ6Okb0AXFZVyBEnK1jDwA,446 +greenlet/tests/test_throw.py,sha256=u2TQ_WvvCd6N6JdXWIxVEcXkKu5fepDlz9dktYdmtng,3712 +greenlet/tests/test_tracing.py,sha256=VlwzMU0C1noospZhuUMyB7MHw200emIvGCN_6G2p2ZU,8250 +greenlet/tests/test_version.py,sha256=O9DpAITsOFgiRcjd4odQ7ejmwx_N9Q1zQENVcbtFHIc,1339 +greenlet/tests/test_weakref.py,sha256=F8M23btEF87bIbpptLNBORosbQqNZGiYeKMqYjWrsak,883 diff --git a/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/REQUESTED b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/WHEEL b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..10ac2c23843796b65786bc9aba179a906c8bcc88 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/direct_url.json b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..7a774c5e2f54c0657f783122fd9b2791f226fd6a --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/direct_url.json @@ -0,0 +1 @@ +{"archive_info": {"hash": "sha256=7454d37c740bb27bdeddfc3f358f26956a07d5220818ceb467a483197d84f849", "hashes": {"sha256": "7454d37c740bb27bdeddfc3f358f26956a07d5220818ceb467a483197d84f849"}}, "url": "file:///C:/a/ComfyUI/cu128_python_deps/greenlet-3.2.3-cp312-cp312-win_amd64.whl"} \ No newline at end of file diff --git a/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/top_level.txt b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..46725be4fd5ff62893d8def5f9e356d4d096328a --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet-3.2.3.dist-info/top_level.txt @@ -0,0 +1 @@ +greenlet diff --git a/python_embeded/Lib/site-packages/greenlet/CObjects.cpp b/python_embeded/Lib/site-packages/greenlet/CObjects.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c135995b690d85696fafe25401e8eed7635100ea --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/CObjects.cpp @@ -0,0 +1,157 @@ +#ifndef COBJECTS_CPP +#define COBJECTS_CPP +/***************************************************************************** + * C interface + * + * These are exported using the CObject API + */ +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +#endif + +#include "greenlet_exceptions.hpp" + +#include "greenlet_internal.hpp" +#include "greenlet_refs.hpp" + + +#include "TThreadStateDestroy.cpp" + +#include "PyGreenlet.hpp" + +using greenlet::PyErrOccurred; +using greenlet::Require; + + + +extern "C" { +static PyGreenlet* +PyGreenlet_GetCurrent(void) +{ + return GET_THREAD_STATE().state().get_current().relinquish_ownership(); +} + +static int +PyGreenlet_SetParent(PyGreenlet* g, PyGreenlet* nparent) +{ + return green_setparent((PyGreenlet*)g, (PyObject*)nparent, NULL); +} + +static PyGreenlet* +PyGreenlet_New(PyObject* run, PyGreenlet* parent) +{ + using greenlet::refs::NewDictReference; + // In the past, we didn't use green_new and green_init, but that + // was a maintenance issue because we duplicated code. This way is + // much safer, but slightly slower. If that's a problem, we could + // refactor green_init to separate argument parsing from initialization. + OwnedGreenlet g = OwnedGreenlet::consuming(green_new(&PyGreenlet_Type, nullptr, nullptr)); + if (!g) { + return NULL; + } + + try { + NewDictReference kwargs; + if (run) { + kwargs.SetItem(mod_globs->str_run, run); + } + if (parent) { + kwargs.SetItem("parent", (PyObject*)parent); + } + + Require(green_init(g.borrow(), mod_globs->empty_tuple, kwargs.borrow())); + } + catch (const PyErrOccurred&) { + return nullptr; + } + + return g.relinquish_ownership(); +} + +static PyObject* +PyGreenlet_Switch(PyGreenlet* self, PyObject* args, PyObject* kwargs) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return NULL; + } + + if (args == NULL) { + args = mod_globs->empty_tuple; + } + + if (kwargs == NULL || !PyDict_Check(kwargs)) { + kwargs = NULL; + } + + return green_switch(self, args, kwargs); +} + +static PyObject* +PyGreenlet_Throw(PyGreenlet* self, PyObject* typ, PyObject* val, PyObject* tb) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return nullptr; + } + try { + PyErrPieces err_pieces(typ, val, tb); + return internal_green_throw(self, err_pieces).relinquish_ownership(); + } + catch (const PyErrOccurred&) { + return nullptr; + } +} + + + +static int +Extern_PyGreenlet_MAIN(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return -1; + } + return self->pimpl->main(); +} + +static int +Extern_PyGreenlet_ACTIVE(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return -1; + } + return self->pimpl->active(); +} + +static int +Extern_PyGreenlet_STARTED(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return -1; + } + return self->pimpl->started(); +} + +static PyGreenlet* +Extern_PyGreenlet_GET_PARENT(PyGreenlet* self) +{ + if (!PyGreenlet_Check(self)) { + PyErr_BadArgument(); + return NULL; + } + // This can return NULL even if there is no exception + return self->pimpl->parent().acquire(); +} +} // extern C. + +/** End C API ****************************************************************/ +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/PyGreenlet.cpp b/python_embeded/Lib/site-packages/greenlet/PyGreenlet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29c0bba0b1045da0d4421e3f1e6e373d432348c4 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/PyGreenlet.cpp @@ -0,0 +1,738 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef PYGREENLET_CPP +#define PYGREENLET_CPP +/***************** +The Python slot functions for TGreenlet. + */ + + +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" // PyMemberDef + +#include "greenlet_internal.hpp" +#include "TThreadStateDestroy.cpp" +#include "TGreenlet.hpp" +// #include "TUserGreenlet.cpp" +// #include "TMainGreenlet.cpp" +// #include "TBrokenGreenlet.cpp" + + +#include "greenlet_refs.hpp" +#include "greenlet_slp_switch.hpp" + +#include "greenlet_thread_support.hpp" +#include "TGreenlet.hpp" + +#include "TGreenletGlobals.cpp" +#include "TThreadStateDestroy.cpp" +#include "PyGreenlet.hpp" +// #include "TGreenlet.cpp" + +// #include "TExceptionState.cpp" +// #include "TPythonState.cpp" +// #include "TStackState.cpp" + +using greenlet::LockGuard; +using greenlet::LockInitError; +using greenlet::PyErrOccurred; +using greenlet::Require; + +using greenlet::g_handle_exit; +using greenlet::single_result; + +using greenlet::Greenlet; +using greenlet::UserGreenlet; +using greenlet::MainGreenlet; +using greenlet::BrokenGreenlet; +using greenlet::ThreadState; +using greenlet::PythonState; + + + +static PyGreenlet* +green_new(PyTypeObject* type, PyObject* UNUSED(args), PyObject* UNUSED(kwds)) +{ + PyGreenlet* o = + (PyGreenlet*)PyBaseObject_Type.tp_new(type, mod_globs->empty_tuple, mod_globs->empty_dict); + if (o) { + new UserGreenlet(o, GET_THREAD_STATE().state().borrow_current()); + assert(Py_REFCNT(o) == 1); + } + return o; +} + + +// green_init is used in the tp_init slot. So it's important that +// it can be called directly from CPython. Thus, we don't use +// BorrowedGreenlet and BorrowedObject --- although in theory +// these should be binary layout compatible, that may not be +// guaranteed to be the case (32-bit linux ppc possibly). +static int +green_init(PyGreenlet* self, PyObject* args, PyObject* kwargs) +{ + PyArgParseParam run; + PyArgParseParam nparent; + static const char* kwlist[] = { + "run", + "parent", + NULL + }; + + // recall: The O specifier does NOT increase the reference count. + if (!PyArg_ParseTupleAndKeywords( + args, kwargs, "|OO:green", (char**)kwlist, &run, &nparent)) { + return -1; + } + + if (run) { + if (green_setrun(self, run, NULL)) { + return -1; + } + } + if (nparent && !nparent.is_None()) { + return green_setparent(self, nparent, NULL); + } + return 0; +} + + + +static int +green_traverse(PyGreenlet* self, visitproc visit, void* arg) +{ + // We must only visit referenced objects, i.e. only objects + // Py_INCREF'ed by this greenlet (directly or indirectly): + // + // - stack_prev is not visited: holds previous stack pointer, but it's not + // referenced + // - frames are not visited as we don't strongly reference them; + // alive greenlets are not garbage collected + // anyway. This can be a problem, however, if this greenlet is + // never allowed to finish, and is referenced from the frame: we + // have an uncollectible cycle in that case. Note that the + // frame object itself is also frequently not even tracked by the GC + // starting with Python 3.7 (frames are allocated by the + // interpreter untracked, and only become tracked when their + // evaluation is finished if they have a refcount > 1). All of + // this is to say that we should probably strongly reference + // the frame object. Doing so, while always allowing GC on a + // greenlet, solves several leaks for us. + + Py_VISIT(self->dict); + if (!self->pimpl) { + // Hmm. I have seen this at interpreter shutdown time, + // I think. That's very odd because this doesn't go away until + // we're ``green_dealloc()``, at which point we shouldn't be + // traversed anymore. + return 0; + } + + return self->pimpl->tp_traverse(visit, arg); +} + +static int +green_is_gc(PyObject* _self) +{ + BorrowedGreenlet self(_self); + int result = 0; + /* Main greenlet can be garbage collected since it can only + become unreachable if the underlying thread exited. + Active greenlets --- including those that are suspended --- + cannot be garbage collected, however. + */ + if (self->main() || !self->active()) { + result = 1; + } + // The main greenlet pointer will eventually go away after the thread dies. + if (self->was_running_in_dead_thread()) { + // Our thread is dead! We can never run again. Might as well + // GC us. Note that if a tuple containing only us and other + // immutable objects had been scanned before this, when we + // would have returned 0, the tuple will take itself out of GC + // tracking and never be investigated again. So that could + // result in both us and the tuple leaking due to an + // unreachable/uncollectible reference. The same goes for + // dictionaries. + // + // It's not a great idea to be changing our GC state on the + // fly. + result = 1; + } + return result; +} + + +static int +green_clear(PyGreenlet* self) +{ + /* Greenlet is only cleared if it is about to be collected. + Since active greenlets are not garbage collectable, we can + be sure that, even if they are deallocated during clear, + nothing they reference is in unreachable or finalizers, + so even if it switches we are relatively safe. */ + // XXX: Are we responsible for clearing weakrefs here? + Py_CLEAR(self->dict); + return self->pimpl->tp_clear(); +} + +/** + * Returns 0 on failure (the object was resurrected) or 1 on success. + **/ +static int +_green_dealloc_kill_started_non_main_greenlet(BorrowedGreenlet self) +{ + /* Hacks hacks hacks copied from instance_dealloc() */ + /* Temporarily resurrect the greenlet. */ + assert(self.REFCNT() == 0); + Py_SET_REFCNT(self.borrow(), 1); + /* Save the current exception, if any. */ + PyErrPieces saved_err; + try { + // BY THE TIME WE GET HERE, the state may actually be going + // away + // if we're shutting down the interpreter and freeing thread + // entries, + // this could result in freeing greenlets that were leaked. So + // we can't try to read the state. + self->deallocing_greenlet_in_thread( + self->thread_state() + ? static_cast(GET_THREAD_STATE()) + : nullptr); + } + catch (const PyErrOccurred&) { + PyErr_WriteUnraisable(self.borrow_o()); + /* XXX what else should we do? */ + } + /* Check for no resurrection must be done while we keep + * our internal reference, otherwise PyFile_WriteObject + * causes recursion if using Py_INCREF/Py_DECREF + */ + if (self.REFCNT() == 1 && self->active()) { + /* Not resurrected, but still not dead! + XXX what else should we do? we complain. */ + PyObject* f = PySys_GetObject("stderr"); + Py_INCREF(self.borrow_o()); /* leak! */ + if (f != NULL) { + PyFile_WriteString("GreenletExit did not kill ", f); + PyFile_WriteObject(self.borrow_o(), f, 0); + PyFile_WriteString("\n", f); + } + } + /* Restore the saved exception. */ + saved_err.PyErrRestore(); + /* Undo the temporary resurrection; can't use DECREF here, + * it would cause a recursive call. + */ + assert(self.REFCNT() > 0); + + Py_ssize_t refcnt = self.REFCNT() - 1; + Py_SET_REFCNT(self.borrow_o(), refcnt); + if (refcnt != 0) { + /* Resurrected! */ + _Py_NewReference(self.borrow_o()); + Py_SET_REFCNT(self.borrow_o(), refcnt); + /* Better to use tp_finalizer slot (PEP 442) + * and call ``PyObject_CallFinalizerFromDealloc``, + * but that's only supported in Python 3.4+; see + * Modules/_io/iobase.c for an example. + * + * The following approach is copied from iobase.c in CPython 2.7. + * (along with much of this function in general). Here's their + * comment: + * + * When called from a heap type's dealloc, the type will be + * decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */ + if (PyType_HasFeature(self.TYPE(), Py_TPFLAGS_HEAPTYPE)) { + Py_INCREF(self.TYPE()); + } + + PyObject_GC_Track((PyObject*)self); + + _Py_DEC_REFTOTAL; +#ifdef COUNT_ALLOCS + --Py_TYPE(self)->tp_frees; + --Py_TYPE(self)->tp_allocs; +#endif /* COUNT_ALLOCS */ + return 0; + } + return 1; +} + + +static void +green_dealloc(PyGreenlet* self) +{ + PyObject_GC_UnTrack(self); + BorrowedGreenlet me(self); + if (me->active() + && me->started() + && !me->main()) { + if (!_green_dealloc_kill_started_non_main_greenlet(me)) { + return; + } + } + + if (self->weakreflist != NULL) { + PyObject_ClearWeakRefs((PyObject*)self); + } + Py_CLEAR(self->dict); + + if (self->pimpl) { + // In case deleting this, which frees some memory, + // somehow winds up calling back into us. That's usually a + //bug in our code. + Greenlet* p = self->pimpl; + self->pimpl = nullptr; + delete p; + } + // and finally we're done. self is now invalid. + Py_TYPE(self)->tp_free((PyObject*)self); +} + + + +static OwnedObject +internal_green_throw(BorrowedGreenlet self, PyErrPieces& err_pieces) +{ + PyObject* result = nullptr; + err_pieces.PyErrRestore(); + assert(PyErr_Occurred()); + if (self->started() && !self->active()) { + /* dead greenlet: turn GreenletExit into a regular return */ + result = g_handle_exit(OwnedObject()).relinquish_ownership(); + } + self->args() <<= result; + + return single_result(self->g_switch()); +} + + + +PyDoc_STRVAR( + green_switch_doc, + "switch(*args, **kwargs)\n" + "\n" + "Switch execution to this greenlet.\n" + "\n" + "If this greenlet has never been run, then this greenlet\n" + "will be switched to using the body of ``self.run(*args, **kwargs)``.\n" + "\n" + "If the greenlet is active (has been run, but was switch()'ed\n" + "out before leaving its run function), then this greenlet will\n" + "be resumed and the return value to its switch call will be\n" + "None if no arguments are given, the given argument if one\n" + "argument is given, or the args tuple and keyword args dict if\n" + "multiple arguments are given.\n" + "\n" + "If the greenlet is dead, or is the current greenlet then this\n" + "function will simply return the arguments using the same rules as\n" + "above.\n"); + +static PyObject* +green_switch(PyGreenlet* self, PyObject* args, PyObject* kwargs) +{ + using greenlet::SwitchingArgs; + SwitchingArgs switch_args(OwnedObject::owning(args), OwnedObject::owning(kwargs)); + self->pimpl->may_switch_away(); + self->pimpl->args() <<= switch_args; + + // If we're switching out of a greenlet, and that switch is the + // last thing the greenlet does, the greenlet ought to be able to + // go ahead and die at that point. Currently, someone else must + // manually switch back to the greenlet so that we "fall off the + // end" and can perform cleanup. You'd think we'd be able to + // figure out that this is happening using the frame's ``f_lasti`` + // member, which is supposed to be an index into + // ``frame->f_code->co_code``, the bytecode string. However, in + // recent interpreters, ``f_lasti`` tends not to be updated thanks + // to things like the PREDICT() macros in ceval.c. So it doesn't + // really work to do that in many cases. For example, the Python + // code: + // def run(): + // greenlet.getcurrent().parent.switch() + // produces bytecode of len 16, with the actual call to switch() + // being at index 10 (in Python 3.10). However, the reported + // ``f_lasti`` we actually see is...5! (Which happens to be the + // second byte of the CALL_METHOD op for ``getcurrent()``). + + try { + //OwnedObject result = single_result(self->pimpl->g_switch()); + OwnedObject result(single_result(self->pimpl->g_switch())); +#ifndef NDEBUG + // Note that the current greenlet isn't necessarily self. If self + // finished, we went to one of its parents. + assert(!self->pimpl->args()); + + const BorrowedGreenlet& current = GET_THREAD_STATE().state().borrow_current(); + // It's possible it's never been switched to. + assert(!current->args()); +#endif + PyObject* p = result.relinquish_ownership(); + + if (!p && !PyErr_Occurred()) { + // This shouldn't be happening anymore, so the asserts + // are there for debug builds. Non-debug builds + // crash "gracefully" in this case, although there is an + // argument to be made for killing the process in all + // cases --- for this to be the case, our switches + // probably nested in an incorrect way, so the state is + // suspicious. Nothing should be corrupt though, just + // confused at the Python level. Letting this propagate is + // probably good enough. + assert(p || PyErr_Occurred()); + throw PyErrOccurred( + mod_globs->PyExc_GreenletError, + "Greenlet.switch() returned NULL without an exception set." + ); + } + return p; + } + catch(const PyErrOccurred&) { + return nullptr; + } +} + +PyDoc_STRVAR( + green_throw_doc, + "Switches execution to this greenlet, but immediately raises the\n" + "given exception in this greenlet. If no argument is provided, the " + "exception\n" + "defaults to `greenlet.GreenletExit`. The normal exception\n" + "propagation rules apply, as described for `switch`. Note that calling " + "this\n" + "method is almost equivalent to the following::\n" + "\n" + " def raiser():\n" + " raise typ, val, tb\n" + " g_raiser = greenlet(raiser, parent=g)\n" + " g_raiser.switch()\n" + "\n" + "except that this trick does not work for the\n" + "`greenlet.GreenletExit` exception, which would not propagate\n" + "from ``g_raiser`` to ``g``.\n"); + +static PyObject* +green_throw(PyGreenlet* self, PyObject* args) +{ + PyArgParseParam typ(mod_globs->PyExc_GreenletExit); + PyArgParseParam val; + PyArgParseParam tb; + + if (!PyArg_ParseTuple(args, "|OOO:throw", &typ, &val, &tb)) { + return nullptr; + } + + assert(typ.borrow() || val.borrow()); + + self->pimpl->may_switch_away(); + try { + // Both normalizing the error and the actual throw_greenlet + // could throw PyErrOccurred. + PyErrPieces err_pieces(typ.borrow(), val.borrow(), tb.borrow()); + + return internal_green_throw(self, err_pieces).relinquish_ownership(); + } + catch (const PyErrOccurred&) { + return nullptr; + } +} + +static int +green_bool(PyGreenlet* self) +{ + return self->pimpl->active(); +} + +/** + * CAUTION: Allocates memory, may run GC and arbitrary Python code. + */ +static PyObject* +green_getdict(PyGreenlet* self, void* UNUSED(context)) +{ + if (self->dict == NULL) { + self->dict = PyDict_New(); + if (self->dict == NULL) { + return NULL; + } + } + Py_INCREF(self->dict); + return self->dict; +} + +static int +green_setdict(PyGreenlet* self, PyObject* val, void* UNUSED(context)) +{ + PyObject* tmp; + + if (val == NULL) { + PyErr_SetString(PyExc_TypeError, "__dict__ may not be deleted"); + return -1; + } + if (!PyDict_Check(val)) { + PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary"); + return -1; + } + tmp = self->dict; + Py_INCREF(val); + self->dict = val; + Py_XDECREF(tmp); + return 0; +} + +static bool +_green_not_dead(BorrowedGreenlet self) +{ + // XXX: Where else should we do this? + // Probably on entry to most Python-facing functions? + if (self->was_running_in_dead_thread()) { + self->deactivate_and_free(); + return false; + } + return self->active() || !self->started(); +} + + +static PyObject* +green_getdead(PyGreenlet* self, void* UNUSED(context)) +{ + if (_green_not_dead(self)) { + Py_RETURN_FALSE; + } + else { + Py_RETURN_TRUE; + } +} + +static PyObject* +green_get_stack_saved(PyGreenlet* self, void* UNUSED(context)) +{ + return PyLong_FromSsize_t(self->pimpl->stack_saved()); +} + + +static PyObject* +green_getrun(PyGreenlet* self, void* UNUSED(context)) +{ + try { + OwnedObject result(BorrowedGreenlet(self)->run()); + return result.relinquish_ownership(); + } + catch(const PyErrOccurred&) { + return nullptr; + } +} + + +static int +green_setrun(PyGreenlet* self, PyObject* nrun, void* UNUSED(context)) +{ + try { + BorrowedGreenlet(self)->run(nrun); + return 0; + } + catch(const PyErrOccurred&) { + return -1; + } +} + +static PyObject* +green_getparent(PyGreenlet* self, void* UNUSED(context)) +{ + return BorrowedGreenlet(self)->parent().acquire_or_None(); +} + + +static int +green_setparent(PyGreenlet* self, PyObject* nparent, void* UNUSED(context)) +{ + try { + BorrowedGreenlet(self)->parent(nparent); + } + catch(const PyErrOccurred&) { + return -1; + } + return 0; +} + + +static PyObject* +green_getcontext(const PyGreenlet* self, void* UNUSED(context)) +{ + const Greenlet *const g = self->pimpl; + try { + OwnedObject result(g->context()); + return result.relinquish_ownership(); + } + catch(const PyErrOccurred&) { + return nullptr; + } +} + +static int +green_setcontext(PyGreenlet* self, PyObject* nctx, void* UNUSED(context)) +{ + try { + BorrowedGreenlet(self)->context(nctx); + return 0; + } + catch(const PyErrOccurred&) { + return -1; + } +} + + +static PyObject* +green_getframe(PyGreenlet* self, void* UNUSED(context)) +{ + const PythonState::OwnedFrame& top_frame = BorrowedGreenlet(self)->top_frame(); + return top_frame.acquire_or_None(); +} + + +static PyObject* +green_getstate(PyGreenlet* self) +{ + PyErr_Format(PyExc_TypeError, + "cannot serialize '%s' object", + Py_TYPE(self)->tp_name); + return nullptr; +} + +static PyObject* +green_repr(PyGreenlet* _self) +{ + BorrowedGreenlet self(_self); + /* + Return a string like + + + The handling of greenlets across threads is not super good. + We mostly use the internal definitions of these terms, but they + generally should make sense to users as well. + */ + PyObject* result; + int never_started = !self->started() && !self->active(); + + const char* const tp_name = Py_TYPE(self)->tp_name; + + if (_green_not_dead(self)) { + /* XXX: The otid= is almost useless because you can't correlate it to + any thread identifier exposed to Python. We could use + PyThreadState_GET()->thread_id, but we'd need to save that in the + greenlet, or save the whole PyThreadState object itself. + + As it stands, its only useful for identifying greenlets from the same thread. + */ + const char* state_in_thread; + if (self->was_running_in_dead_thread()) { + // The thread it was running in is dead! + // This can happen, especially at interpreter shut down. + // It complicates debugging output because it may be + // impossible to access the current thread state at that + // time. Thus, don't access the current thread state. + state_in_thread = " (thread exited)"; + } + else { + state_in_thread = GET_THREAD_STATE().state().is_current(self) + ? " current" + : (self->started() ? " suspended" : ""); + } + result = PyUnicode_FromFormat( + "<%s object at %p (otid=%p)%s%s%s%s>", + tp_name, + self.borrow_o(), + self->thread_state(), + state_in_thread, + self->active() ? " active" : "", + never_started ? " pending" : " started", + self->main() ? " main" : "" + ); + } + else { + result = PyUnicode_FromFormat( + "<%s object at %p (otid=%p) %sdead>", + tp_name, + self.borrow_o(), + self->thread_state(), + self->was_running_in_dead_thread() + ? "(thread exited) " + : "" + ); + } + + return result; +} + + +static PyMethodDef green_methods[] = { + { + .ml_name="switch", + .ml_meth=reinterpret_cast(green_switch), + .ml_flags=METH_VARARGS | METH_KEYWORDS, + .ml_doc=green_switch_doc + }, + {.ml_name="throw", .ml_meth=(PyCFunction)green_throw, .ml_flags=METH_VARARGS, .ml_doc=green_throw_doc}, + {.ml_name="__getstate__", .ml_meth=(PyCFunction)green_getstate, .ml_flags=METH_NOARGS, .ml_doc=NULL}, + {.ml_name=NULL, .ml_meth=NULL} /* sentinel */ +}; + +static PyGetSetDef green_getsets[] = { + /* name, getter, setter, doc, context pointer */ + {.name="__dict__", .get=(getter)green_getdict, .set=(setter)green_setdict}, + {.name="run", .get=(getter)green_getrun, .set=(setter)green_setrun}, + {.name="parent", .get=(getter)green_getparent, .set=(setter)green_setparent}, + {.name="gr_frame", .get=(getter)green_getframe }, + { + .name="gr_context", + .get=(getter)green_getcontext, + .set=(setter)green_setcontext + }, + {.name="dead", .get=(getter)green_getdead}, + {.name="_stack_saved", .get=(getter)green_get_stack_saved}, + {.name=NULL} +}; + +static PyMemberDef green_members[] = { + {.name=NULL} +}; + +static PyNumberMethods green_as_number = { + .nb_bool=(inquiry)green_bool, +}; + + +PyTypeObject PyGreenlet_Type = { + .ob_base=PyVarObject_HEAD_INIT(NULL, 0) + .tp_name="greenlet.greenlet", /* tp_name */ + .tp_basicsize=sizeof(PyGreenlet), /* tp_basicsize */ + /* methods */ + .tp_dealloc=(destructor)green_dealloc, /* tp_dealloc */ + .tp_repr=(reprfunc)green_repr, /* tp_repr */ + .tp_as_number=&green_as_number, /* tp_as _number*/ + .tp_flags=G_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + .tp_doc="greenlet(run=None, parent=None) -> greenlet\n\n" + "Creates a new greenlet object (without running it).\n\n" + " - *run* -- The callable to invoke.\n" + " - *parent* -- The parent greenlet. The default is the current " + "greenlet.", /* tp_doc */ + .tp_traverse=(traverseproc)green_traverse, /* tp_traverse */ + .tp_clear=(inquiry)green_clear, /* tp_clear */ + .tp_weaklistoffset=offsetof(PyGreenlet, weakreflist), /* tp_weaklistoffset */ + + .tp_methods=green_methods, /* tp_methods */ + .tp_members=green_members, /* tp_members */ + .tp_getset=green_getsets, /* tp_getset */ + .tp_dictoffset=offsetof(PyGreenlet, dict), /* tp_dictoffset */ + .tp_init=(initproc)green_init, /* tp_init */ + .tp_alloc=PyType_GenericAlloc, /* tp_alloc */ + .tp_new=(newfunc)green_new, /* tp_new */ + .tp_free=PyObject_GC_Del, /* tp_free */ + .tp_is_gc=(inquiry)green_is_gc, /* tp_is_gc */ +}; + +#endif + +// Local Variables: +// flycheck-clang-include-path: ("/opt/local/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8") +// End: diff --git a/python_embeded/Lib/site-packages/greenlet/PyGreenlet.hpp b/python_embeded/Lib/site-packages/greenlet/PyGreenlet.hpp new file mode 100644 index 0000000000000000000000000000000000000000..df6cd805b497cfd1fecf0310f6baff46181e08cb --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/PyGreenlet.hpp @@ -0,0 +1,35 @@ +#ifndef PYGREENLET_HPP +#define PYGREENLET_HPP + + +#include "greenlet.h" +#include "greenlet_compiler_compat.hpp" +#include "greenlet_refs.hpp" + + +using greenlet::refs::OwnedGreenlet; +using greenlet::refs::BorrowedGreenlet; +using greenlet::refs::BorrowedObject;; +using greenlet::refs::OwnedObject; +using greenlet::refs::PyErrPieces; + + +// XXX: These doesn't really belong here, it's not a Python slot. +static OwnedObject internal_green_throw(BorrowedGreenlet self, PyErrPieces& err_pieces); + +static PyGreenlet* green_new(PyTypeObject* type, PyObject* UNUSED(args), PyObject* UNUSED(kwds)); +static int green_clear(PyGreenlet* self); +static int green_init(PyGreenlet* self, PyObject* args, PyObject* kwargs); +static int green_setparent(PyGreenlet* self, PyObject* nparent, void* UNUSED(context)); +static int green_setrun(PyGreenlet* self, PyObject* nrun, void* UNUSED(context)); +static int green_traverse(PyGreenlet* self, visitproc visit, void* arg); +static void green_dealloc(PyGreenlet* self); +static PyObject* green_getparent(PyGreenlet* self, void* UNUSED(context)); + +static int green_is_gc(PyObject* self); +static PyObject* green_getdead(PyGreenlet* self, void* UNUSED(context)); +static PyObject* green_getrun(PyGreenlet* self, void* UNUSED(context)); +static int green_setcontext(PyGreenlet* self, PyObject* nctx, void* UNUSED(context)); +static PyObject* green_getframe(PyGreenlet* self, void* UNUSED(context)); +static PyObject* green_repr(PyGreenlet* self); +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/PyGreenletUnswitchable.cpp b/python_embeded/Lib/site-packages/greenlet/PyGreenletUnswitchable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b768ee349b6c2672abc70bf2e3dbcc3163f885f --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/PyGreenletUnswitchable.cpp @@ -0,0 +1,147 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + Implementation of the Python slots for PyGreenletUnswitchable_Type +*/ +#ifndef PY_GREENLET_UNSWITCHABLE_CPP +#define PY_GREENLET_UNSWITCHABLE_CPP + + + +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" // PyMemberDef + +#include "greenlet_internal.hpp" +// Code after this point can assume access to things declared in stdint.h, +// including the fixed-width types. This goes for the platform-specific switch functions +// as well. +#include "greenlet_refs.hpp" +#include "greenlet_slp_switch.hpp" + +#include "greenlet_thread_support.hpp" +#include "TGreenlet.hpp" + +#include "TGreenlet.cpp" +#include "TGreenletGlobals.cpp" +#include "TThreadStateDestroy.cpp" + + +using greenlet::LockGuard; +using greenlet::LockInitError; +using greenlet::PyErrOccurred; +using greenlet::Require; + +using greenlet::g_handle_exit; +using greenlet::single_result; + +using greenlet::Greenlet; +using greenlet::UserGreenlet; +using greenlet::MainGreenlet; +using greenlet::BrokenGreenlet; +using greenlet::ThreadState; +using greenlet::PythonState; + + +#include "PyGreenlet.hpp" + +static PyGreenlet* +green_unswitchable_new(PyTypeObject* type, PyObject* UNUSED(args), PyObject* UNUSED(kwds)) +{ + PyGreenlet* o = + (PyGreenlet*)PyBaseObject_Type.tp_new(type, mod_globs->empty_tuple, mod_globs->empty_dict); + if (o) { + new BrokenGreenlet(o, GET_THREAD_STATE().state().borrow_current()); + assert(Py_REFCNT(o) == 1); + } + return o; +} + +static PyObject* +green_unswitchable_getforce(PyGreenlet* self, void* UNUSED(context)) +{ + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + return PyBool_FromLong(broken->_force_switch_error); +} + +static int +green_unswitchable_setforce(PyGreenlet* self, PyObject* nforce, void* UNUSED(context)) +{ + if (!nforce) { + PyErr_SetString( + PyExc_AttributeError, + "Cannot delete force_switch_error" + ); + return -1; + } + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + int is_true = PyObject_IsTrue(nforce); + if (is_true == -1) { + return -1; + } + broken->_force_switch_error = is_true; + return 0; +} + +static PyObject* +green_unswitchable_getforceslp(PyGreenlet* self, void* UNUSED(context)) +{ + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + return PyBool_FromLong(broken->_force_slp_switch_error); +} + +static int +green_unswitchable_setforceslp(PyGreenlet* self, PyObject* nforce, void* UNUSED(context)) +{ + if (!nforce) { + PyErr_SetString( + PyExc_AttributeError, + "Cannot delete force_slp_switch_error" + ); + return -1; + } + BrokenGreenlet* broken = dynamic_cast(self->pimpl); + int is_true = PyObject_IsTrue(nforce); + if (is_true == -1) { + return -1; + } + broken->_force_slp_switch_error = is_true; + return 0; +} + +static PyGetSetDef green_unswitchable_getsets[] = { + /* name, getter, setter, doc, closure (context pointer) */ + { + .name="force_switch_error", + .get=(getter)green_unswitchable_getforce, + .set=(setter)green_unswitchable_setforce, + .doc=NULL + }, + { + .name="force_slp_switch_error", + .get=(getter)green_unswitchable_getforceslp, + .set=(setter)green_unswitchable_setforceslp, + .doc=nullptr + }, + {.name=nullptr} +}; + +PyTypeObject PyGreenletUnswitchable_Type = { + .ob_base=PyVarObject_HEAD_INIT(NULL, 0) + .tp_name="greenlet._greenlet.UnswitchableGreenlet", + .tp_dealloc= (destructor)green_dealloc, /* tp_dealloc */ + .tp_flags=G_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + .tp_doc="Undocumented internal class", /* tp_doc */ + .tp_traverse=(traverseproc)green_traverse, /* tp_traverse */ + .tp_clear=(inquiry)green_clear, /* tp_clear */ + + .tp_getset=green_unswitchable_getsets, /* tp_getset */ + .tp_base=&PyGreenlet_Type, /* tp_base */ + .tp_init=(initproc)green_init, /* tp_init */ + .tp_alloc=PyType_GenericAlloc, /* tp_alloc */ + .tp_new=(newfunc)green_unswitchable_new, /* tp_new */ + .tp_free=PyObject_GC_Del, /* tp_free */ + .tp_is_gc=(inquiry)green_is_gc, /* tp_is_gc */ +}; + + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/PyModule.cpp b/python_embeded/Lib/site-packages/greenlet/PyModule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6adcb5c3d4b04773997c311e724af07bbb361052 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/PyModule.cpp @@ -0,0 +1,292 @@ +#ifndef PY_MODULE_CPP +#define PY_MODULE_CPP + +#include "greenlet_internal.hpp" + + +#include "TGreenletGlobals.cpp" +#include "TMainGreenlet.cpp" +#include "TThreadStateDestroy.cpp" + +using greenlet::LockGuard; +using greenlet::ThreadState; + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +# pragma clang diagnostic ignored "-Wunused-variable" +#endif + +PyDoc_STRVAR(mod_getcurrent_doc, + "getcurrent() -> greenlet\n" + "\n" + "Returns the current greenlet (i.e. the one which called this " + "function).\n"); + +static PyObject* +mod_getcurrent(PyObject* UNUSED(module)) +{ + return GET_THREAD_STATE().state().get_current().relinquish_ownership_o(); +} + +PyDoc_STRVAR(mod_settrace_doc, + "settrace(callback) -> object\n" + "\n" + "Sets a new tracing function and returns the previous one.\n"); +static PyObject* +mod_settrace(PyObject* UNUSED(module), PyObject* args) +{ + PyArgParseParam tracefunc; + if (!PyArg_ParseTuple(args, "O", &tracefunc)) { + return NULL; + } + ThreadState& state = GET_THREAD_STATE(); + OwnedObject previous = state.get_tracefunc(); + if (!previous) { + previous = Py_None; + } + + state.set_tracefunc(tracefunc); + + return previous.relinquish_ownership(); +} + +PyDoc_STRVAR(mod_gettrace_doc, + "gettrace() -> object\n" + "\n" + "Returns the currently set tracing function, or None.\n"); + +static PyObject* +mod_gettrace(PyObject* UNUSED(module)) +{ + OwnedObject tracefunc = GET_THREAD_STATE().state().get_tracefunc(); + if (!tracefunc) { + tracefunc = Py_None; + } + return tracefunc.relinquish_ownership(); +} + + + +PyDoc_STRVAR(mod_set_thread_local_doc, + "set_thread_local(key, value) -> None\n" + "\n" + "Set a value in the current thread-local dictionary. Debugging only.\n"); + +static PyObject* +mod_set_thread_local(PyObject* UNUSED(module), PyObject* args) +{ + PyArgParseParam key; + PyArgParseParam value; + PyObject* result = NULL; + + if (PyArg_UnpackTuple(args, "set_thread_local", 2, 2, &key, &value)) { + if(PyDict_SetItem( + PyThreadState_GetDict(), // borrow + key, + value) == 0 ) { + // success + Py_INCREF(Py_None); + result = Py_None; + } + } + return result; +} + +PyDoc_STRVAR(mod_get_pending_cleanup_count_doc, + "get_pending_cleanup_count() -> Integer\n" + "\n" + "Get the number of greenlet cleanup operations pending. Testing only.\n"); + + +static PyObject* +mod_get_pending_cleanup_count(PyObject* UNUSED(module)) +{ + LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); + return PyLong_FromSize_t(mod_globs->thread_states_to_destroy.size()); +} + +PyDoc_STRVAR(mod_get_total_main_greenlets_doc, + "get_total_main_greenlets() -> Integer\n" + "\n" + "Quickly return the number of main greenlets that exist. Testing only.\n"); + +static PyObject* +mod_get_total_main_greenlets(PyObject* UNUSED(module)) +{ + return PyLong_FromSize_t(G_TOTAL_MAIN_GREENLETS); +} + + + +PyDoc_STRVAR(mod_get_clocks_used_doing_optional_cleanup_doc, + "get_clocks_used_doing_optional_cleanup() -> Integer\n" + "\n" + "Get the number of clock ticks the program has used doing optional " + "greenlet cleanup.\n" + "Beginning in greenlet 2.0, greenlet tries to find and dispose of greenlets\n" + "that leaked after a thread exited. This requires invoking Python's garbage collector,\n" + "which may have a performance cost proportional to the number of live objects.\n" + "This function returns the amount of processor time\n" + "greenlet has used to do this. In programs that run with very large amounts of live\n" + "objects, this metric can be used to decide whether the cost of doing this cleanup\n" + "is worth the memory leak being corrected. If not, you can disable the cleanup\n" + "using ``enable_optional_cleanup(False)``.\n" + "The units are arbitrary and can only be compared to themselves (similarly to ``time.clock()``);\n" + "for example, to see how it scales with your heap. You can attempt to convert them into seconds\n" + "by dividing by the value of CLOCKS_PER_SEC." + "If cleanup has been disabled, returns None." + "\n" + "This is an implementation specific, provisional API. It may be changed or removed\n" + "in the future.\n" + ".. versionadded:: 2.0" + ); +static PyObject* +mod_get_clocks_used_doing_optional_cleanup(PyObject* UNUSED(module)) +{ + std::clock_t& clocks = ThreadState::clocks_used_doing_gc(); + + if (clocks == std::clock_t(-1)) { + Py_RETURN_NONE; + } + // This might not actually work on some implementations; clock_t + // is an opaque type. + return PyLong_FromSsize_t(clocks); +} + +PyDoc_STRVAR(mod_enable_optional_cleanup_doc, + "mod_enable_optional_cleanup(bool) -> None\n" + "\n" + "Enable or disable optional cleanup operations.\n" + "See ``get_clocks_used_doing_optional_cleanup()`` for details.\n" + ); +static PyObject* +mod_enable_optional_cleanup(PyObject* UNUSED(module), PyObject* flag) +{ + int is_true = PyObject_IsTrue(flag); + if (is_true == -1) { + return nullptr; + } + + std::clock_t& clocks = ThreadState::clocks_used_doing_gc(); + if (is_true) { + // If we already have a value, we don't want to lose it. + if (clocks == std::clock_t(-1)) { + clocks = 0; + } + } + else { + clocks = std::clock_t(-1); + } + Py_RETURN_NONE; +} + + + + +#if !GREENLET_PY313 +PyDoc_STRVAR(mod_get_tstate_trash_delete_nesting_doc, + "get_tstate_trash_delete_nesting() -> Integer\n" + "\n" + "Return the 'trash can' nesting level. Testing only.\n"); +static PyObject* +mod_get_tstate_trash_delete_nesting(PyObject* UNUSED(module)) +{ + PyThreadState* tstate = PyThreadState_GET(); + +#if GREENLET_PY312 + return PyLong_FromLong(tstate->trash.delete_nesting); +#else + return PyLong_FromLong(tstate->trash_delete_nesting); +#endif +} +#endif + + + + +static PyMethodDef GreenMethods[] = { + { + .ml_name="getcurrent", + .ml_meth=(PyCFunction)mod_getcurrent, + .ml_flags=METH_NOARGS, + .ml_doc=mod_getcurrent_doc + }, + { + .ml_name="settrace", + .ml_meth=(PyCFunction)mod_settrace, + .ml_flags=METH_VARARGS, + .ml_doc=mod_settrace_doc + }, + { + .ml_name="gettrace", + .ml_meth=(PyCFunction)mod_gettrace, + .ml_flags=METH_NOARGS, + .ml_doc=mod_gettrace_doc + }, + { + .ml_name="set_thread_local", + .ml_meth=(PyCFunction)mod_set_thread_local, + .ml_flags=METH_VARARGS, + .ml_doc=mod_set_thread_local_doc + }, + { + .ml_name="get_pending_cleanup_count", + .ml_meth=(PyCFunction)mod_get_pending_cleanup_count, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_pending_cleanup_count_doc + }, + { + .ml_name="get_total_main_greenlets", + .ml_meth=(PyCFunction)mod_get_total_main_greenlets, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_total_main_greenlets_doc + }, + { + .ml_name="get_clocks_used_doing_optional_cleanup", + .ml_meth=(PyCFunction)mod_get_clocks_used_doing_optional_cleanup, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_clocks_used_doing_optional_cleanup_doc + }, + { + .ml_name="enable_optional_cleanup", + .ml_meth=(PyCFunction)mod_enable_optional_cleanup, + .ml_flags=METH_O, + .ml_doc=mod_enable_optional_cleanup_doc + }, +#if !GREENLET_PY313 + { + .ml_name="get_tstate_trash_delete_nesting", + .ml_meth=(PyCFunction)mod_get_tstate_trash_delete_nesting, + .ml_flags=METH_NOARGS, + .ml_doc=mod_get_tstate_trash_delete_nesting_doc + }, +#endif + {.ml_name=NULL, .ml_meth=NULL} /* Sentinel */ +}; + +static const char* const copy_on_greentype[] = { + "getcurrent", + "error", + "GreenletExit", + "settrace", + "gettrace", + NULL +}; + +static struct PyModuleDef greenlet_module_def = { + .m_base=PyModuleDef_HEAD_INIT, + .m_name="greenlet._greenlet", + .m_doc=NULL, + .m_size=-1, + .m_methods=GreenMethods, +}; + + +#endif + +#ifdef __clang__ +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/TBrokenGreenlet.cpp b/python_embeded/Lib/site-packages/greenlet/TBrokenGreenlet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e9ab5be9a58c8ccbcc0529dc21b3b857efa4cd9 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TBrokenGreenlet.cpp @@ -0,0 +1,45 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::UserGreenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ + +#include "TGreenlet.hpp" + +namespace greenlet { + +void* BrokenGreenlet::operator new(size_t UNUSED(count)) +{ + return allocator.allocate(1); +} + + +void BrokenGreenlet::operator delete(void* ptr) +{ + return allocator.deallocate(static_cast(ptr), + 1); +} + +greenlet::PythonAllocator greenlet::BrokenGreenlet::allocator; + +bool +BrokenGreenlet::force_slp_switch_error() const noexcept +{ + return this->_force_slp_switch_error; +} + +UserGreenlet::switchstack_result_t BrokenGreenlet::g_switchstack(void) +{ + if (this->_force_switch_error) { + return switchstack_result_t(-1); + } + return UserGreenlet::g_switchstack(); +} + +}; //namespace greenlet diff --git a/python_embeded/Lib/site-packages/greenlet/TExceptionState.cpp b/python_embeded/Lib/site-packages/greenlet/TExceptionState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..08a94ae83e67fa7884bc8b8fd64ed815a1a4c0ae --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TExceptionState.cpp @@ -0,0 +1,62 @@ +#ifndef GREENLET_EXCEPTION_STATE_CPP +#define GREENLET_EXCEPTION_STATE_CPP + +#include +#include "TGreenlet.hpp" + +namespace greenlet { + + +ExceptionState::ExceptionState() +{ + this->clear(); +} + +void ExceptionState::operator<<(const PyThreadState *const tstate) noexcept +{ + this->exc_info = tstate->exc_info; + this->exc_state = tstate->exc_state; +} + +void ExceptionState::operator>>(PyThreadState *const tstate) noexcept +{ + tstate->exc_state = this->exc_state; + tstate->exc_info = + this->exc_info ? this->exc_info : &tstate->exc_state; + this->clear(); +} + +void ExceptionState::clear() noexcept +{ + this->exc_info = nullptr; + this->exc_state.exc_value = nullptr; +#if !GREENLET_PY311 + this->exc_state.exc_type = nullptr; + this->exc_state.exc_traceback = nullptr; +#endif + this->exc_state.previous_item = nullptr; +} + +int ExceptionState::tp_traverse(visitproc visit, void* arg) noexcept +{ + Py_VISIT(this->exc_state.exc_value); +#if !GREENLET_PY311 + Py_VISIT(this->exc_state.exc_type); + Py_VISIT(this->exc_state.exc_traceback); +#endif + return 0; +} + +void ExceptionState::tp_clear() noexcept +{ + Py_CLEAR(this->exc_state.exc_value); +#if !GREENLET_PY311 + Py_CLEAR(this->exc_state.exc_type); + Py_CLEAR(this->exc_state.exc_traceback); +#endif +} + + +}; // namespace greenlet + +#endif // GREENLET_EXCEPTION_STATE_CPP diff --git a/python_embeded/Lib/site-packages/greenlet/TGreenlet.cpp b/python_embeded/Lib/site-packages/greenlet/TGreenlet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4698a1784faae52289c9e9904ca4bc218da485ff --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TGreenlet.cpp @@ -0,0 +1,718 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::Greenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef TGREENLET_CPP +#define TGREENLET_CPP +#include "greenlet_internal.hpp" +#include "TGreenlet.hpp" + + +#include "TGreenletGlobals.cpp" +#include "TThreadStateDestroy.cpp" + +namespace greenlet { + +Greenlet::Greenlet(PyGreenlet* p) + : Greenlet(p, StackState()) +{ +} + +Greenlet::Greenlet(PyGreenlet* p, const StackState& initial_stack) + : _self(p), stack_state(initial_stack) +{ + assert(p->pimpl == nullptr); + p->pimpl = this; +} + +Greenlet::~Greenlet() +{ + // XXX: Can't do this. tp_clear is a virtual function, and by the + // time we're here, we've sliced off our child classes. + //this->tp_clear(); + this->_self->pimpl = nullptr; +} + +bool +Greenlet::force_slp_switch_error() const noexcept +{ + return false; +} + +void +Greenlet::release_args() +{ + this->switch_args.CLEAR(); +} + +/** + * CAUTION: This will allocate memory and may trigger garbage + * collection and arbitrary Python code. + */ +OwnedObject +Greenlet::throw_GreenletExit_during_dealloc(const ThreadState& UNUSED(current_thread_state)) +{ + // If we're killed because we lost all references in the + // middle of a switch, that's ok. Don't reset the args/kwargs, + // we still want to pass them to the parent. + PyErr_SetString(mod_globs->PyExc_GreenletExit, + "Killing the greenlet because all references have vanished."); + // To get here it had to have run before + return this->g_switch(); +} + +inline void +Greenlet::slp_restore_state() noexcept +{ +#ifdef SLP_BEFORE_RESTORE_STATE + SLP_BEFORE_RESTORE_STATE(); +#endif + this->stack_state.copy_heap_to_stack( + this->thread_state()->borrow_current()->stack_state); +} + + +inline int +Greenlet::slp_save_state(char *const stackref) noexcept +{ + // XXX: This used to happen in the middle, before saving, but + // after finding the next owner. Does that matter? This is + // only defined for Sparc/GCC where it flushes register + // windows to the stack (I think) +#ifdef SLP_BEFORE_SAVE_STATE + SLP_BEFORE_SAVE_STATE(); +#endif + return this->stack_state.copy_stack_to_heap(stackref, + this->thread_state()->borrow_current()->stack_state); +} + +/** + * CAUTION: This will allocate memory and may trigger garbage + * collection and arbitrary Python code. + */ +OwnedObject +Greenlet::on_switchstack_or_initialstub_failure( + Greenlet* target, + const Greenlet::switchstack_result_t& err, + const bool target_was_me, + const bool was_initial_stub) +{ + // If we get here, either g_initialstub() + // failed, or g_switchstack() failed. Either one of those + // cases SHOULD leave us in the original greenlet with a valid stack. + if (!PyErr_Occurred()) { + PyErr_SetString( + PyExc_SystemError, + was_initial_stub + ? "Failed to switch stacks into a greenlet for the first time." + : "Failed to switch stacks into a running greenlet."); + } + this->release_args(); + + if (target && !target_was_me) { + target->murder_in_place(); + } + + assert(!err.the_new_current_greenlet); + assert(!err.origin_greenlet); + return OwnedObject(); + +} + +OwnedGreenlet +Greenlet::g_switchstack_success() noexcept +{ + PyThreadState* tstate = PyThreadState_GET(); + // restore the saved state + this->python_state >> tstate; + this->exception_state >> tstate; + + // The thread state hasn't been changed yet. + ThreadState* thread_state = this->thread_state(); + OwnedGreenlet result(thread_state->get_current()); + thread_state->set_current(this->self()); + //assert(thread_state->borrow_current().borrow() == this->_self); + return result; +} + +Greenlet::switchstack_result_t +Greenlet::g_switchstack(void) +{ + // if any of these assertions fail, it's likely because we + // switched away and tried to switch back to us. Early stages of + // switching are not reentrant because we re-use ``this->args()``. + // Switching away would happen if we trigger a garbage collection + // (by just using some Python APIs that happen to allocate Python + // objects) and some garbage had weakref callbacks or __del__ that + // switches (people don't write code like that by hand, but with + // gevent it's possible without realizing it) + assert(this->args() || PyErr_Occurred()); + { /* save state */ + if (this->thread_state()->is_current(this->self())) { + // Hmm, nothing to do. + // TODO: Does this bypass trace events that are + // important? + return switchstack_result_t(0, + this, this->thread_state()->borrow_current()); + } + BorrowedGreenlet current = this->thread_state()->borrow_current(); + PyThreadState* tstate = PyThreadState_GET(); + + current->python_state << tstate; + current->exception_state << tstate; + this->python_state.will_switch_from(tstate); + switching_thread_state = this; + current->expose_frames(); + } + assert(this->args() || PyErr_Occurred()); + // If this is the first switch into a greenlet, this will + // return twice, once with 1 in the new greenlet, once with 0 + // in the origin. + int err; + if (this->force_slp_switch_error()) { + err = -1; + } + else { + err = slp_switch(); + } + + if (err < 0) { /* error */ + // Tested by + // test_greenlet.TestBrokenGreenlets.test_failed_to_slp_switch_into_running + // + // It's not clear if it's worth trying to clean up and + // continue here. Failing to switch stacks is a big deal which + // may not be recoverable (who knows what state the stack is in). + // Also, we've stolen references in preparation for calling + // ``g_switchstack_success()`` and we don't have a clean + // mechanism for backing that all out. + Py_FatalError("greenlet: Failed low-level slp_switch(). The stack is probably corrupt."); + } + + // No stack-based variables are valid anymore. + + // But the global is volatile so we can reload it without the + // compiler caching it from earlier. + Greenlet* greenlet_that_switched_in = switching_thread_state; // aka this + switching_thread_state = nullptr; + // except that no stack variables are valid, we would: + // assert(this == greenlet_that_switched_in); + + // switchstack success is where we restore the exception state, + // etc. It returns the origin greenlet because its convenient. + + OwnedGreenlet origin = greenlet_that_switched_in->g_switchstack_success(); + assert(greenlet_that_switched_in->args() || PyErr_Occurred()); + return switchstack_result_t(err, greenlet_that_switched_in, origin); +} + + +inline void +Greenlet::check_switch_allowed() const +{ + // TODO: Make this take a parameter of the current greenlet, + // or current main greenlet, to make the check for + // cross-thread switching cheaper. Surely somewhere up the + // call stack we've already accessed the thread local variable. + + // We expect to always have a main greenlet now; accessing the thread state + // created it. However, if we get here and cleanup has already + // begun because we're a greenlet that was running in a + // (now dead) thread, these invariants will not hold true. In + // fact, accessing `this->thread_state` may not even be possible. + + // If the thread this greenlet was running in is dead, + // we'll still have a reference to a main greenlet, but the + // thread state pointer we have is bogus. + // TODO: Give the objects an API to determine if they belong + // to a dead thread. + + const BorrowedMainGreenlet main_greenlet = this->find_main_greenlet_in_lineage(); + + if (!main_greenlet) { + throw PyErrOccurred(mod_globs->PyExc_GreenletError, + "cannot switch to a garbage collected greenlet"); + } + + if (!main_greenlet->thread_state()) { + throw PyErrOccurred(mod_globs->PyExc_GreenletError, + "cannot switch to a different thread (which happens to have exited)"); + } + + // The main greenlet we found was from the .parent lineage. + // That may or may not have any relationship to the main + // greenlet of the running thread. We can't actually access + // our this->thread_state members to try to check that, + // because it could be in the process of getting destroyed, + // but setting the main_greenlet->thread_state member to NULL + // may not be visible yet. So we need to check against the + // current thread state (once the cheaper checks are out of + // the way) + const BorrowedMainGreenlet current_main_greenlet = GET_THREAD_STATE().state().borrow_main_greenlet(); + if ( + // lineage main greenlet is not this thread's greenlet + current_main_greenlet != main_greenlet + || ( + // atteched to some thread + this->main_greenlet() + // XXX: Same condition as above. Was this supposed to be + // this->main_greenlet()? + && current_main_greenlet != main_greenlet) + // switching into a known dead thread (XXX: which, if we get here, + // is bad, because we just accessed the thread state, which is + // gone!) + || (!current_main_greenlet->thread_state())) { + // CAUTION: This may trigger memory allocations, gc, and + // arbitrary Python code. + throw PyErrOccurred( + mod_globs->PyExc_GreenletError, + "Cannot switch to a different thread\n\tCurrent: %R\n\tExpected: %R", + current_main_greenlet, main_greenlet); + } +} + +const OwnedObject +Greenlet::context() const +{ + using greenlet::PythonStateContext; + OwnedObject result; + + if (this->is_currently_running_in_some_thread()) { + /* Currently running greenlet: context is stored in the thread state, + not the greenlet object. */ + if (GET_THREAD_STATE().state().is_current(this->self())) { + result = PythonStateContext::context(PyThreadState_GET()); + } + else { + throw ValueError( + "cannot get context of a " + "greenlet that is running in a different thread"); + } + } + else { + /* Greenlet is not running: just return context. */ + result = this->python_state.context(); + } + if (!result) { + result = OwnedObject::None(); + } + return result; +} + + +void +Greenlet::context(BorrowedObject given) +{ + using greenlet::PythonStateContext; + if (!given) { + throw AttributeError("can't delete context attribute"); + } + if (given.is_None()) { + /* "Empty context" is stored as NULL, not None. */ + given = nullptr; + } + + //checks type, incrs refcnt + greenlet::refs::OwnedContext context(given); + PyThreadState* tstate = PyThreadState_GET(); + + if (this->is_currently_running_in_some_thread()) { + if (!GET_THREAD_STATE().state().is_current(this->self())) { + throw ValueError("cannot set context of a greenlet" + " that is running in a different thread"); + } + + /* Currently running greenlet: context is stored in the thread state, + not the greenlet object. */ + OwnedObject octx = OwnedObject::consuming(PythonStateContext::context(tstate)); + PythonStateContext::context(tstate, context.relinquish_ownership()); + } + else { + /* Greenlet is not running: just set context. Note that the + greenlet may be dead.*/ + this->python_state.context() = context; + } +} + +/** + * CAUTION: May invoke arbitrary Python code. + * + * Figure out what the result of ``greenlet.switch(arg, kwargs)`` + * should be and transfers ownership of it to the left-hand-side. + * + * If switch() was just passed an arg tuple, then we'll just return that. + * If only keyword arguments were passed, then we'll pass the keyword + * argument dict. Otherwise, we'll create a tuple of (args, kwargs) and + * return both. + * + * CAUTION: This may allocate a new tuple object, which may + * cause the Python garbage collector to run, which in turn may + * run arbitrary Python code that switches. + */ +OwnedObject& operator<<=(OwnedObject& lhs, greenlet::SwitchingArgs& rhs) noexcept +{ + // Because this may invoke arbitrary Python code, which could + // result in switching back to us, we need to get the + // arguments locally on the stack. + assert(rhs); + OwnedObject args = rhs.args(); + OwnedObject kwargs = rhs.kwargs(); + rhs.CLEAR(); + // We shouldn't be called twice for the same switch. + assert(args || kwargs); + assert(!rhs); + + if (!kwargs) { + lhs = args; + } + else if (!PyDict_Size(kwargs.borrow())) { + lhs = args; + } + else if (!PySequence_Length(args.borrow())) { + lhs = kwargs; + } + else { + // PyTuple_Pack allocates memory, may GC, may run arbitrary + // Python code. + lhs = OwnedObject::consuming(PyTuple_Pack(2, args.borrow(), kwargs.borrow())); + } + return lhs; +} + +static OwnedObject +g_handle_exit(const OwnedObject& greenlet_result) +{ + if (!greenlet_result && mod_globs->PyExc_GreenletExit.PyExceptionMatches()) { + /* catch and ignore GreenletExit */ + PyErrFetchParam val; + PyErr_Fetch(PyErrFetchParam(), val, PyErrFetchParam()); + if (!val) { + return OwnedObject::None(); + } + return OwnedObject(val); + } + + if (greenlet_result) { + // package the result into a 1-tuple + // PyTuple_Pack increments the reference of its arguments, + // so we always need to decref the greenlet result; + // the owner will do that. + return OwnedObject::consuming(PyTuple_Pack(1, greenlet_result.borrow())); + } + + return OwnedObject(); +} + + + +/** + * May run arbitrary Python code. + */ +OwnedObject +Greenlet::g_switch_finish(const switchstack_result_t& err) +{ + assert(err.the_new_current_greenlet == this); + + ThreadState& state = *this->thread_state(); + // Because calling the trace function could do arbitrary things, + // including switching away from this greenlet and then maybe + // switching back, we need to capture the arguments now so that + // they don't change. + OwnedObject result; + if (this->args()) { + result <<= this->args(); + } + else { + assert(PyErr_Occurred()); + } + assert(!this->args()); + try { + // Our only caller handles the bad error case + assert(err.status >= 0); + assert(state.borrow_current() == this->self()); + if (OwnedObject tracefunc = state.get_tracefunc()) { + assert(result || PyErr_Occurred()); + g_calltrace(tracefunc, + result ? mod_globs->event_switch : mod_globs->event_throw, + err.origin_greenlet, + this->self()); + } + // The above could have invoked arbitrary Python code, but + // it couldn't switch back to this object and *also* + // throw an exception, so the args won't have changed. + + if (PyErr_Occurred()) { + // We get here if we fell of the end of the run() function + // raising an exception. The switch itself was + // successful, but the function raised. + // valgrind reports that memory allocated here can still + // be reached after a test run. + throw PyErrOccurred::from_current(); + } + return result; + } + catch (const PyErrOccurred&) { + /* Turn switch errors into switch throws */ + /* Turn trace errors into switch throws */ + this->release_args(); + throw; + } +} + +void +Greenlet::g_calltrace(const OwnedObject& tracefunc, + const greenlet::refs::ImmortalEventName& event, + const BorrowedGreenlet& origin, + const BorrowedGreenlet& target) +{ + PyErrPieces saved_exc; + try { + TracingGuard tracing_guard; + // TODO: We have saved the active exception (if any) that's + // about to be raised. In the 'throw' case, we could provide + // the exception to the tracefunction, which seems very helpful. + tracing_guard.CallTraceFunction(tracefunc, event, origin, target); + } + catch (const PyErrOccurred&) { + // In case of exceptions trace function is removed, + // and any existing exception is replaced with the tracing + // exception. + GET_THREAD_STATE().state().set_tracefunc(Py_None); + throw; + } + + saved_exc.PyErrRestore(); + assert( + (event == mod_globs->event_throw && PyErr_Occurred()) + || (event == mod_globs->event_switch && !PyErr_Occurred()) + ); +} + +void +Greenlet::murder_in_place() +{ + if (this->active()) { + assert(!this->is_currently_running_in_some_thread()); + this->deactivate_and_free(); + } +} + +inline void +Greenlet::deactivate_and_free() +{ + if (!this->active()) { + return; + } + // Throw away any saved stack. + this->stack_state = StackState(); + assert(!this->stack_state.active()); + // Throw away any Python references. + // We're holding a borrowed reference to the last + // frame we executed. Since we borrowed it, the + // normal traversal, clear, and dealloc functions + // ignore it, meaning it leaks. (The thread state + // object can't find it to clear it when that's + // deallocated either, because by definition if we + // got an object on this list, it wasn't + // running and the thread state doesn't have + // this frame.) + // So here, we *do* clear it. + this->python_state.tp_clear(true); +} + +bool +Greenlet::belongs_to_thread(const ThreadState* thread_state) const +{ + if (!this->thread_state() // not running anywhere, or thread + // exited + || !thread_state) { // same, or there is no thread state. + return false; + } + return true; +} + + +void +Greenlet::deallocing_greenlet_in_thread(const ThreadState* current_thread_state) +{ + /* Cannot raise an exception to kill the greenlet if + it is not running in the same thread! */ + if (this->belongs_to_thread(current_thread_state)) { + assert(current_thread_state); + // To get here it had to have run before + /* Send the greenlet a GreenletExit exception. */ + + // We don't care about the return value, only whether an + // exception happened. + this->throw_GreenletExit_during_dealloc(*current_thread_state); + return; + } + + // Not the same thread! Temporarily save the greenlet + // into its thread's deleteme list, *if* it exists. + // If that thread has already exited, and processed its pending + // cleanup, we'll never be able to clean everything up: we won't + // be able to raise an exception. + // That's mostly OK! Since we can't add it to a list, our refcount + // won't increase, and we'll go ahead with the DECREFs later. + ThreadState *const thread_state = this->thread_state(); + if (thread_state) { + thread_state->delete_when_thread_running(this->self()); + } + else { + // The thread is dead, we can't raise an exception. + // We need to make it look non-active, though, so that dealloc + // finishes killing it. + this->deactivate_and_free(); + } + return; +} + + +int +Greenlet::tp_traverse(visitproc visit, void* arg) +{ + + int result; + if ((result = this->exception_state.tp_traverse(visit, arg)) != 0) { + return result; + } + //XXX: This is ugly. But so is handling everything having to do + //with the top frame. + bool visit_top_frame = this->was_running_in_dead_thread(); + // When true, the thread is dead. Our implicit weak reference to the + // frame is now all that's left; we consider ourselves to + // strongly own it now. + if ((result = this->python_state.tp_traverse(visit, arg, visit_top_frame)) != 0) { + return result; + } + return 0; +} + +int +Greenlet::tp_clear() +{ + bool own_top_frame = this->was_running_in_dead_thread(); + this->exception_state.tp_clear(); + this->python_state.tp_clear(own_top_frame); + return 0; +} + +bool Greenlet::is_currently_running_in_some_thread() const +{ + return this->stack_state.active() && !this->python_state.top_frame(); +} + +#if GREENLET_PY312 +void GREENLET_NOINLINE(Greenlet::expose_frames)() +{ + if (!this->python_state.top_frame()) { + return; + } + + _PyInterpreterFrame* last_complete_iframe = nullptr; + _PyInterpreterFrame* iframe = this->python_state.top_frame()->f_frame; + while (iframe) { + // We must make a copy before looking at the iframe contents, + // since iframe might point to a portion of the greenlet's C stack + // that was spilled when switching greenlets. + _PyInterpreterFrame iframe_copy; + this->stack_state.copy_from_stack(&iframe_copy, iframe, sizeof(*iframe)); + if (!_PyFrame_IsIncomplete(&iframe_copy)) { + // If the iframe were OWNED_BY_CSTACK then it would always be + // incomplete. Since it's not incomplete, it's not on the C stack + // and we can access it through the original `iframe` pointer + // directly. This is important since GetFrameObject might + // lazily _create_ the frame object and we don't want the + // interpreter to lose track of it. + assert(iframe_copy.owner != FRAME_OWNED_BY_CSTACK); + + // We really want to just write: + // PyFrameObject* frame = _PyFrame_GetFrameObject(iframe); + // but _PyFrame_GetFrameObject calls _PyFrame_MakeAndSetFrameObject + // which is not a visible symbol in libpython. The easiest + // way to get a public function to call it is using + // PyFrame_GetBack, which is defined as follows: + // assert(frame != NULL); + // assert(!_PyFrame_IsIncomplete(frame->f_frame)); + // PyFrameObject *back = frame->f_back; + // if (back == NULL) { + // _PyInterpreterFrame *prev = frame->f_frame->previous; + // prev = _PyFrame_GetFirstComplete(prev); + // if (prev) { + // back = _PyFrame_GetFrameObject(prev); + // } + // } + // return (PyFrameObject*)Py_XNewRef(back); + if (!iframe->frame_obj) { + PyFrameObject dummy_frame; + _PyInterpreterFrame dummy_iframe; + dummy_frame.f_back = nullptr; + dummy_frame.f_frame = &dummy_iframe; + // force the iframe to be considered complete without + // needing to check its code object: + dummy_iframe.owner = FRAME_OWNED_BY_GENERATOR; + dummy_iframe.previous = iframe; + assert(!_PyFrame_IsIncomplete(&dummy_iframe)); + // Drop the returned reference immediately; the iframe + // continues to hold a strong reference + Py_XDECREF(PyFrame_GetBack(&dummy_frame)); + assert(iframe->frame_obj); + } + + // This is a complete frame, so make the last one of those we saw + // point at it, bypassing any incomplete frames (which may have + // been on the C stack) in between the two. We're overwriting + // last_complete_iframe->previous and need that to be reversible, + // so we store the original previous ptr in the frame object + // (which we must have created on a previous iteration through + // this loop). The frame object has a bunch of storage that is + // only used when its iframe is OWNED_BY_FRAME_OBJECT, which only + // occurs when the frame object outlives the frame's execution, + // which can't have happened yet because the frame is currently + // executing as far as the interpreter is concerned. So, we can + // reuse it for our own purposes. + assert(iframe->owner == FRAME_OWNED_BY_THREAD + || iframe->owner == FRAME_OWNED_BY_GENERATOR); + if (last_complete_iframe) { + assert(last_complete_iframe->frame_obj); + memcpy(&last_complete_iframe->frame_obj->_f_frame_data[0], + &last_complete_iframe->previous, sizeof(void *)); + last_complete_iframe->previous = iframe; + } + last_complete_iframe = iframe; + } + // Frames that are OWNED_BY_FRAME_OBJECT are linked via the + // frame's f_back while all others are linked via the iframe's + // previous ptr. Since all the frames we traverse are running + // as far as the interpreter is concerned, we don't have to + // worry about the OWNED_BY_FRAME_OBJECT case. + iframe = iframe_copy.previous; + } + + // Give the outermost complete iframe a null previous pointer to + // account for any potential incomplete/C-stack iframes between it + // and the actual top-of-stack + if (last_complete_iframe) { + assert(last_complete_iframe->frame_obj); + memcpy(&last_complete_iframe->frame_obj->_f_frame_data[0], + &last_complete_iframe->previous, sizeof(void *)); + last_complete_iframe->previous = nullptr; + } +} +#else +void Greenlet::expose_frames() +{ + +} +#endif + +}; // namespace greenlet +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/TGreenlet.hpp b/python_embeded/Lib/site-packages/greenlet/TGreenlet.hpp new file mode 100644 index 0000000000000000000000000000000000000000..aa6d6d5adce211e5bb05c3e0e1e30752e5a4770d --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TGreenlet.hpp @@ -0,0 +1,824 @@ +#ifndef GREENLET_GREENLET_HPP +#define GREENLET_GREENLET_HPP +/* + * Declarations of the core data structures. +*/ + +#define PY_SSIZE_T_CLEAN +#include + +#include "greenlet_compiler_compat.hpp" +#include "greenlet_refs.hpp" +#include "greenlet_cpython_compat.hpp" +#include "greenlet_allocator.hpp" + +using greenlet::refs::OwnedObject; +using greenlet::refs::OwnedGreenlet; +using greenlet::refs::OwnedMainGreenlet; +using greenlet::refs::BorrowedGreenlet; + +#if PY_VERSION_HEX < 0x30B00A6 +# define _PyCFrame CFrame +# define _PyInterpreterFrame _interpreter_frame +#endif + +#if GREENLET_PY312 +# define Py_BUILD_CORE +# include "internal/pycore_frame.h" +#endif + +#if GREENLET_PY314 +# include "internal/pycore_interpframe_structs.h" +#if defined(_MSC_VER) || defined(__MINGW64__) +# include "greenlet_msvc_compat.hpp" +#else +# include "internal/pycore_interpframe.h" +#endif +#endif + +// XXX: TODO: Work to remove all virtual functions +// for speed of calling and size of objects (no vtable). +// One pattern is the Curiously Recurring Template +namespace greenlet +{ + class ExceptionState + { + private: + G_NO_COPIES_OF_CLS(ExceptionState); + + // Even though these are borrowed objects, we actually own + // them, when they're not null. + // XXX: Express that in the API. + private: + _PyErr_StackItem* exc_info; + _PyErr_StackItem exc_state; + public: + ExceptionState(); + void operator<<(const PyThreadState *const tstate) noexcept; + void operator>>(PyThreadState* tstate) noexcept; + void clear() noexcept; + + int tp_traverse(visitproc visit, void* arg) noexcept; + void tp_clear() noexcept; + }; + + template + void operator<<(const PyThreadState *const tstate, T& exc); + + class PythonStateContext + { + protected: + greenlet::refs::OwnedContext _context; + public: + inline const greenlet::refs::OwnedContext& context() const + { + return this->_context; + } + inline greenlet::refs::OwnedContext& context() + { + return this->_context; + } + + inline void tp_clear() + { + this->_context.CLEAR(); + } + + template + inline static PyObject* context(T* tstate) + { + return tstate->context; + } + + template + inline static void context(T* tstate, PyObject* new_context) + { + tstate->context = new_context; + tstate->context_ver++; + } + }; + class SwitchingArgs; + class PythonState : public PythonStateContext + { + public: + typedef greenlet::refs::OwnedReference OwnedFrame; + private: + G_NO_COPIES_OF_CLS(PythonState); + // We own this if we're suspended (although currently we don't + // tp_traverse into it; that's a TODO). If we're running, it's + // empty. If we get deallocated and *still* have a frame, it + // won't be reachable from the place that normally decref's + // it, so we need to do it (hence owning it). + OwnedFrame _top_frame; +#if GREENLET_USE_CFRAME + _PyCFrame* cframe; + int use_tracing; +#endif +#if GREENLET_PY314 + int py_recursion_depth; +#elif GREENLET_PY312 + int py_recursion_depth; + int c_recursion_depth; +#else + int recursion_depth; +#endif +#if GREENLET_PY313 + PyObject *delete_later; +#else + int trash_delete_nesting; +#endif +#if GREENLET_PY311 + _PyInterpreterFrame* current_frame; + _PyStackChunk* datastack_chunk; + PyObject** datastack_top; + PyObject** datastack_limit; +#endif + // The PyInterpreterFrame list on 3.12+ contains some entries that are + // on the C stack, which can't be directly accessed while a greenlet is + // suspended. In order to keep greenlet gr_frame introspection working, + // we adjust stack switching to rewrite the interpreter frame list + // to skip these C-stack frames; we call this "exposing" the greenlet's + // frames because it makes them valid to work with in Python. Then when + // the greenlet is resumed we need to remember to reverse the operation + // we did. The C-stack frames are "entry frames" which are a low-level + // interpreter detail; they're not needed for introspection, but do + // need to be present for the eval loop to work. + void unexpose_frames(); + + public: + + PythonState(); + // You can use this for testing whether we have a frame + // or not. It returns const so they can't modify it. + const OwnedFrame& top_frame() const noexcept; + + inline void operator<<(const PyThreadState *const tstate) noexcept; + inline void operator>>(PyThreadState* tstate) noexcept; + void clear() noexcept; + + int tp_traverse(visitproc visit, void* arg, bool visit_top_frame) noexcept; + void tp_clear(bool own_top_frame) noexcept; + void set_initial_state(const PyThreadState* const tstate) noexcept; +#if GREENLET_USE_CFRAME + void set_new_cframe(_PyCFrame& frame) noexcept; +#endif + + void may_switch_away() noexcept; + inline void will_switch_from(PyThreadState *const origin_tstate) noexcept; + void did_finish(PyThreadState* tstate) noexcept; + }; + + class StackState + { + // By having only plain C (POD) members, no virtual functions + // or bases, we get a trivial assignment operator generated + // for us. However, that's not safe since we do manage memory. + // So we declare an assignment operator that only works if we + // don't have any memory allocated. (We don't use + // std::shared_ptr for reference counting just to keep this + // object small) + private: + char* _stack_start; + char* stack_stop; + char* stack_copy; + intptr_t _stack_saved; + StackState* stack_prev; + inline int copy_stack_to_heap_up_to(const char* const stop) noexcept; + inline void free_stack_copy() noexcept; + + public: + /** + * Creates a started, but inactive, state, using *current* + * as the previous. + */ + StackState(void* mark, StackState& current); + /** + * Creates an inactive, unstarted, state. + */ + StackState(); + ~StackState(); + StackState(const StackState& other); + StackState& operator=(const StackState& other); + inline void copy_heap_to_stack(const StackState& current) noexcept; + inline int copy_stack_to_heap(char* const stackref, const StackState& current) noexcept; + inline bool started() const noexcept; + inline bool main() const noexcept; + inline bool active() const noexcept; + inline void set_active() noexcept; + inline void set_inactive() noexcept; + inline intptr_t stack_saved() const noexcept; + inline char* stack_start() const noexcept; + static inline StackState make_main() noexcept; +#ifdef GREENLET_USE_STDIO + friend std::ostream& operator<<(std::ostream& os, const StackState& s); +#endif + + // Fill in [dest, dest + n) with the values that would be at + // [src, src + n) while this greenlet is running. This is like memcpy + // except that if the greenlet is suspended it accounts for the portion + // of the greenlet's stack that was spilled to the heap. `src` may + // be on this greenlet's stack, or on the heap, but not on a different + // greenlet's stack. + void copy_from_stack(void* dest, const void* src, size_t n) const; + }; +#ifdef GREENLET_USE_STDIO + std::ostream& operator<<(std::ostream& os, const StackState& s); +#endif + + class SwitchingArgs + { + private: + G_NO_ASSIGNMENT_OF_CLS(SwitchingArgs); + // If args and kwargs are both false (NULL), this is a *throw*, not a + // switch. PyErr_... must have been called already. + OwnedObject _args; + OwnedObject _kwargs; + public: + + SwitchingArgs() + {} + + SwitchingArgs(const OwnedObject& args, const OwnedObject& kwargs) + : _args(args), + _kwargs(kwargs) + {} + + SwitchingArgs(const SwitchingArgs& other) + : _args(other._args), + _kwargs(other._kwargs) + {} + + const OwnedObject& args() + { + return this->_args; + } + + const OwnedObject& kwargs() + { + return this->_kwargs; + } + + /** + * Moves ownership from the argument to this object. + */ + SwitchingArgs& operator<<=(SwitchingArgs& other) + { + if (this != &other) { + this->_args = other._args; + this->_kwargs = other._kwargs; + other.CLEAR(); + } + return *this; + } + + /** + * Acquires ownership of the argument (consumes the reference). + */ + SwitchingArgs& operator<<=(PyObject* args) + { + this->_args = OwnedObject::consuming(args); + this->_kwargs.CLEAR(); + return *this; + } + + /** + * Acquires ownership of the argument. + * + * Sets the args to be the given value; clears the kwargs. + */ + SwitchingArgs& operator<<=(OwnedObject& args) + { + assert(&args != &this->_args); + this->_args = args; + this->_kwargs.CLEAR(); + args.CLEAR(); + + return *this; + } + + explicit operator bool() const noexcept + { + return this->_args || this->_kwargs; + } + + inline void CLEAR() + { + this->_args.CLEAR(); + this->_kwargs.CLEAR(); + } + + const std::string as_str() const noexcept + { + return PyUnicode_AsUTF8( + OwnedObject::consuming( + PyUnicode_FromFormat( + "SwitchingArgs(args=%R, kwargs=%R)", + this->_args.borrow(), + this->_kwargs.borrow() + ) + ).borrow() + ); + } + }; + + class ThreadState; + + class UserGreenlet; + class MainGreenlet; + + class Greenlet + { + private: + G_NO_COPIES_OF_CLS(Greenlet); + PyGreenlet* const _self; + private: + // XXX: Work to remove these. + friend class ThreadState; + friend class UserGreenlet; + friend class MainGreenlet; + protected: + ExceptionState exception_state; + SwitchingArgs switch_args; + StackState stack_state; + PythonState python_state; + Greenlet(PyGreenlet* p, const StackState& initial_state); + public: + // This constructor takes ownership of the PyGreenlet, by + // setting ``p->pimpl = this;``. + Greenlet(PyGreenlet* p); + virtual ~Greenlet(); + + const OwnedObject context() const; + + // You MUST call this _very_ early in the switching process to + // prepare anything that may need prepared. This might perform + // garbage collections or otherwise run arbitrary Python code. + // + // One specific use of it is for Python 3.11+, preventing + // running arbitrary code at unsafe times. See + // PythonState::may_switch_away(). + inline void may_switch_away() + { + this->python_state.may_switch_away(); + } + + inline void context(refs::BorrowedObject new_context); + + inline SwitchingArgs& args() + { + return this->switch_args; + } + + virtual const refs::BorrowedMainGreenlet main_greenlet() const = 0; + + inline intptr_t stack_saved() const noexcept + { + return this->stack_state.stack_saved(); + } + + // This is used by the macro SLP_SAVE_STATE to compute the + // difference in stack sizes. It might be nice to handle the + // computation ourself, but the type of the result + // varies by platform, so doing it in the macro is the + // simplest way. + inline const char* stack_start() const noexcept + { + return this->stack_state.stack_start(); + } + + virtual OwnedObject throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state); + virtual OwnedObject g_switch() = 0; + /** + * Force the greenlet to appear dead. Used when it's not + * possible to throw an exception into a greenlet anymore. + * + * This losses access to the thread state and the main greenlet. + */ + virtual void murder_in_place(); + + /** + * Called when somebody notices we were running in a dead + * thread to allow cleaning up resources (because we can't + * raise GreenletExit into it anymore). + * This is very similar to ``murder_in_place()``, except that + * it DOES NOT lose the main greenlet or thread state. + */ + inline void deactivate_and_free(); + + + // Called when some thread wants to deallocate a greenlet + // object. + // The thread may or may not be the same thread the greenlet + // was running in. + // The thread state will be null if the thread the greenlet + // was running in was known to have exited. + void deallocing_greenlet_in_thread(const ThreadState* current_state); + + // Must be called on 3.12+ before exposing a suspended greenlet's + // frames to user code. This rewrites the linked list of interpreter + // frames to skip the ones that are being stored on the C stack (which + // can't be safely accessed while the greenlet is suspended because + // that stack space might be hosting a different greenlet), and + // sets PythonState::frames_were_exposed so we remember to restore + // the original list before resuming the greenlet. The C-stack frames + // are a low-level interpreter implementation detail; while they're + // important to the bytecode eval loop, they're superfluous for + // introspection purposes. + void expose_frames(); + + + // TODO: Figure out how to make these non-public. + inline void slp_restore_state() noexcept; + inline int slp_save_state(char *const stackref) noexcept; + + inline bool is_currently_running_in_some_thread() const; + virtual bool belongs_to_thread(const ThreadState* state) const; + + inline bool started() const + { + return this->stack_state.started(); + } + inline bool active() const + { + return this->stack_state.active(); + } + inline bool main() const + { + return this->stack_state.main(); + } + virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const = 0; + + virtual const OwnedGreenlet parent() const = 0; + virtual void parent(const refs::BorrowedObject new_parent) = 0; + + inline const PythonState::OwnedFrame& top_frame() + { + return this->python_state.top_frame(); + } + + virtual const OwnedObject& run() const = 0; + virtual void run(const refs::BorrowedObject nrun) = 0; + + + virtual int tp_traverse(visitproc visit, void* arg); + virtual int tp_clear(); + + + // Return the thread state that the greenlet is running in, or + // null if the greenlet is not running or the thread is known + // to have exited. + virtual ThreadState* thread_state() const noexcept = 0; + + // Return true if the greenlet is known to have been running + // (active) in a thread that has now exited. + virtual bool was_running_in_dead_thread() const noexcept = 0; + + // Return a borrowed greenlet that is the Python object + // this object represents. + inline BorrowedGreenlet self() const noexcept + { + return BorrowedGreenlet(this->_self); + } + + // For testing. If this returns true, we should pretend that + // slp_switch() failed. + virtual bool force_slp_switch_error() const noexcept; + + protected: + inline void release_args(); + + // The functions that must not be inlined are declared virtual. + // We also mark them as protected, not private, so that the + // compiler is forced to call them through a function pointer. + // (A sufficiently smart compiler could directly call a private + // virtual function since it can never be overridden in a + // subclass). + + // Also TODO: Switch away from integer error codes and to enums, + // or throw exceptions when possible. + struct switchstack_result_t + { + int status; + Greenlet* the_new_current_greenlet; + OwnedGreenlet origin_greenlet; + + switchstack_result_t() + : status(0), + the_new_current_greenlet(nullptr) + {} + + switchstack_result_t(int err) + : status(err), + the_new_current_greenlet(nullptr) + {} + + switchstack_result_t(int err, Greenlet* state, OwnedGreenlet& origin) + : status(err), + the_new_current_greenlet(state), + origin_greenlet(origin) + { + } + + switchstack_result_t(int err, Greenlet* state, const BorrowedGreenlet& origin) + : status(err), + the_new_current_greenlet(state), + origin_greenlet(origin) + { + } + + switchstack_result_t(const switchstack_result_t& other) + : status(other.status), + the_new_current_greenlet(other.the_new_current_greenlet), + origin_greenlet(other.origin_greenlet) + {} + + switchstack_result_t& operator=(const switchstack_result_t& other) + { + this->status = other.status; + this->the_new_current_greenlet = other.the_new_current_greenlet; + this->origin_greenlet = other.origin_greenlet; + return *this; + } + }; + + OwnedObject on_switchstack_or_initialstub_failure( + Greenlet* target, + const switchstack_result_t& err, + const bool target_was_me=false, + const bool was_initial_stub=false); + + // Returns the previous greenlet we just switched away from. + virtual OwnedGreenlet g_switchstack_success() noexcept; + + + // Check the preconditions for switching to this greenlet; if they + // aren't met, throws PyErrOccurred. Most callers will want to + // catch this and clear the arguments + inline void check_switch_allowed() const; + class GreenletStartedWhileInPython : public std::runtime_error + { + public: + GreenletStartedWhileInPython() : std::runtime_error("") + {} + }; + + protected: + + + /** + Perform a stack switch into this greenlet. + + This temporarily sets the global variable + ``switching_thread_state`` to this greenlet; as soon as the + call to ``slp_switch`` completes, this is reset to NULL. + Consequently, this depends on the GIL. + + TODO: Adopt the stackman model and pass ``slp_switch`` a + callback function and context pointer; this eliminates the + need for global variables altogether. + + Because the stack switch happens in this function, this + function can't use its own stack (local) variables, set + before the switch, and then accessed after the switch. + + Further, you con't even access ``g_thread_state_global`` + before and after the switch from the global variable. + Because it is thread local some compilers cache it in a + register/on the stack, notably new versions of MSVC; this + breaks with strange crashes sometime later, because writing + to anything in ``g_thread_state_global`` after the switch + is actually writing to random memory. For this reason, we + call a non-inlined function to finish the operation. (XXX: + The ``/GT`` MSVC compiler argument probably fixes that.) + + It is very important that stack switch is 'atomic', i.e. no + calls into other Python code allowed (except very few that + are safe), because global variables are very fragile. (This + should no longer be the case with thread-local variables.) + + */ + // Made virtual to facilitate subclassing UserGreenlet for testing. + virtual switchstack_result_t g_switchstack(void); + +class TracingGuard +{ +private: + PyThreadState* tstate; +public: + TracingGuard() + : tstate(PyThreadState_GET()) + { + PyThreadState_EnterTracing(this->tstate); + } + + ~TracingGuard() + { + PyThreadState_LeaveTracing(this->tstate); + this->tstate = nullptr; + } + + inline void CallTraceFunction(const OwnedObject& tracefunc, + const greenlet::refs::ImmortalEventName& event, + const BorrowedGreenlet& origin, + const BorrowedGreenlet& target) + { + // TODO: This calls tracefunc(event, (origin, target)). Add a shortcut + // function for that that's specialized to avoid the Py_BuildValue + // string parsing, or start with just using "ON" format with PyTuple_Pack(2, + // origin, target). That seems like what the N format is meant + // for. + // XXX: Why does event not automatically cast back to a PyObject? + // It tries to call the "deleted constructor ImmortalEventName + // const" instead. + assert(tracefunc); + assert(event); + assert(origin); + assert(target); + greenlet::refs::NewReference retval( + PyObject_CallFunction( + tracefunc.borrow(), + "O(OO)", + event.borrow(), + origin.borrow(), + target.borrow() + )); + if (!retval) { + throw PyErrOccurred::from_current(); + } + } +}; + + static void + g_calltrace(const OwnedObject& tracefunc, + const greenlet::refs::ImmortalEventName& event, + const greenlet::refs::BorrowedGreenlet& origin, + const BorrowedGreenlet& target); + private: + OwnedObject g_switch_finish(const switchstack_result_t& err); + + }; + + class UserGreenlet : public Greenlet + { + private: + static greenlet::PythonAllocator allocator; + OwnedMainGreenlet _main_greenlet; + OwnedObject _run_callable; + OwnedGreenlet _parent; + public: + static void* operator new(size_t UNUSED(count)); + static void operator delete(void* ptr); + + UserGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent); + virtual ~UserGreenlet(); + + virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const; + virtual bool was_running_in_dead_thread() const noexcept; + virtual ThreadState* thread_state() const noexcept; + virtual OwnedObject g_switch(); + virtual const OwnedObject& run() const + { + if (this->started() || !this->_run_callable) { + throw AttributeError("run"); + } + return this->_run_callable; + } + virtual void run(const refs::BorrowedObject nrun); + + virtual const OwnedGreenlet parent() const; + virtual void parent(const refs::BorrowedObject new_parent); + + virtual const refs::BorrowedMainGreenlet main_greenlet() const; + + virtual void murder_in_place(); + virtual bool belongs_to_thread(const ThreadState* state) const; + virtual int tp_traverse(visitproc visit, void* arg); + virtual int tp_clear(); + class ParentIsCurrentGuard + { + private: + OwnedGreenlet oldparent; + UserGreenlet* greenlet; + G_NO_COPIES_OF_CLS(ParentIsCurrentGuard); + public: + ParentIsCurrentGuard(UserGreenlet* p, const ThreadState& thread_state); + ~ParentIsCurrentGuard(); + }; + virtual OwnedObject throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state); + protected: + virtual switchstack_result_t g_initialstub(void* mark); + private: + // This function isn't meant to return. + // This accepts raw pointers and the ownership of them at the + // same time. The caller should use ``inner_bootstrap(origin.relinquish_ownership())``. + void inner_bootstrap(PyGreenlet* origin_greenlet, PyObject* run); + }; + + class BrokenGreenlet : public UserGreenlet + { + private: + static greenlet::PythonAllocator allocator; + public: + bool _force_switch_error = false; + bool _force_slp_switch_error = false; + + static void* operator new(size_t UNUSED(count)); + static void operator delete(void* ptr); + BrokenGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent) + : UserGreenlet(p, the_parent) + {} + virtual ~BrokenGreenlet() + {} + + virtual switchstack_result_t g_switchstack(void); + virtual bool force_slp_switch_error() const noexcept; + + }; + + class MainGreenlet : public Greenlet + { + private: + static greenlet::PythonAllocator allocator; + refs::BorrowedMainGreenlet _self; + ThreadState* _thread_state; + G_NO_COPIES_OF_CLS(MainGreenlet); + public: + static void* operator new(size_t UNUSED(count)); + static void operator delete(void* ptr); + + MainGreenlet(refs::BorrowedMainGreenlet::PyType*, ThreadState*); + virtual ~MainGreenlet(); + + + virtual const OwnedObject& run() const; + virtual void run(const refs::BorrowedObject nrun); + + virtual const OwnedGreenlet parent() const; + virtual void parent(const refs::BorrowedObject new_parent); + + virtual const refs::BorrowedMainGreenlet main_greenlet() const; + + virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const; + virtual bool was_running_in_dead_thread() const noexcept; + virtual ThreadState* thread_state() const noexcept; + void thread_state(ThreadState*) noexcept; + virtual OwnedObject g_switch(); + virtual int tp_traverse(visitproc visit, void* arg); + }; + + // Instantiate one on the stack to save the GC state, + // and then disable GC. When it goes out of scope, GC will be + // restored to its original state. Sadly, these APIs are only + // available on 3.10+; luckily, we only need them on 3.11+. +#if GREENLET_PY310 + class GCDisabledGuard + { + private: + int was_enabled = 0; + public: + GCDisabledGuard() + : was_enabled(PyGC_IsEnabled()) + { + PyGC_Disable(); + } + + ~GCDisabledGuard() + { + if (this->was_enabled) { + PyGC_Enable(); + } + } + }; +#endif + + OwnedObject& operator<<=(OwnedObject& lhs, greenlet::SwitchingArgs& rhs) noexcept; + + //TODO: Greenlet::g_switch() should call this automatically on its + //return value. As it is, the module code is calling it. + static inline OwnedObject + single_result(const OwnedObject& results) + { + if (results + && PyTuple_Check(results.borrow()) + && PyTuple_GET_SIZE(results.borrow()) == 1) { + PyObject* result = PyTuple_GET_ITEM(results.borrow(), 0); + assert(result); + return OwnedObject::owning(result); + } + return results; + } + + + static OwnedObject + g_handle_exit(const OwnedObject& greenlet_result); + + + template + void operator<<(const PyThreadState *const lhs, T& rhs) + { + rhs.operator<<(lhs); + } + +} // namespace greenlet ; + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/TGreenletGlobals.cpp b/python_embeded/Lib/site-packages/greenlet/TGreenletGlobals.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0087d2ff35ce68b1321371b956115872e661c726 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TGreenletGlobals.cpp @@ -0,0 +1,94 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of GreenletGlobals. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_GREENLET_GLOBALS +#define T_GREENLET_GLOBALS + +#include "greenlet_refs.hpp" +#include "greenlet_exceptions.hpp" +#include "greenlet_thread_support.hpp" +#include "greenlet_internal.hpp" + +namespace greenlet { + +// This encapsulates what were previously module global "constants" +// established at init time. +// This is a step towards Python3 style module state that allows +// reloading. +// +// In an earlier iteration of this code, we used placement new to be +// able to allocate this object statically still, so that references +// to its members don't incur an extra pointer indirection. +// But under some scenarios, that could result in crashes at +// shutdown because apparently the destructor was getting run twice? +class GreenletGlobals +{ + +public: + const greenlet::refs::ImmortalEventName event_switch; + const greenlet::refs::ImmortalEventName event_throw; + const greenlet::refs::ImmortalException PyExc_GreenletError; + const greenlet::refs::ImmortalException PyExc_GreenletExit; + const greenlet::refs::ImmortalObject empty_tuple; + const greenlet::refs::ImmortalObject empty_dict; + const greenlet::refs::ImmortalString str_run; + Mutex* const thread_states_to_destroy_lock; + greenlet::cleanup_queue_t thread_states_to_destroy; + + GreenletGlobals() : + event_switch("switch"), + event_throw("throw"), + PyExc_GreenletError("greenlet.error"), + PyExc_GreenletExit("greenlet.GreenletExit", PyExc_BaseException), + empty_tuple(Require(PyTuple_New(0))), + empty_dict(Require(PyDict_New())), + str_run("run"), + thread_states_to_destroy_lock(new Mutex()) + {} + + ~GreenletGlobals() + { + // This object is (currently) effectively immortal, and not + // just because of those placement new tricks; if we try to + // deallocate the static object we allocated, and overwrote, + // we would be doing so at C++ teardown time, which is after + // the final Python GIL is released, and we can't use the API + // then. + // (The members will still be destructed, but they also don't + // do any deallocation.) + } + + void queue_to_destroy(ThreadState* ts) const + { + // we're currently accessed through a static const object, + // implicitly marking our members as const, so code can't just + // call push_back (or pop_back) without casting away the + // const. + // + // Do that for callers. + greenlet::cleanup_queue_t& q = const_cast(this->thread_states_to_destroy); + q.push_back(ts); + } + + ThreadState* take_next_to_destroy() const + { + greenlet::cleanup_queue_t& q = const_cast(this->thread_states_to_destroy); + ThreadState* result = q.back(); + q.pop_back(); + return result; + } +}; + +}; // namespace greenlet + +static const greenlet::GreenletGlobals* mod_globs; + +#endif // T_GREENLET_GLOBALS diff --git a/python_embeded/Lib/site-packages/greenlet/TMainGreenlet.cpp b/python_embeded/Lib/site-packages/greenlet/TMainGreenlet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2a9cfe4bb08c7417e8cb87edc75cd770b16f4fe --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TMainGreenlet.cpp @@ -0,0 +1,153 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::MainGreenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_MAIN_GREENLET_CPP +#define T_MAIN_GREENLET_CPP + +#include "TGreenlet.hpp" + + + +// Protected by the GIL. Incremented when we create a main greenlet, +// in a new thread, decremented when it is destroyed. +static Py_ssize_t G_TOTAL_MAIN_GREENLETS; + +namespace greenlet { +greenlet::PythonAllocator MainGreenlet::allocator; + +void* MainGreenlet::operator new(size_t UNUSED(count)) +{ + return allocator.allocate(1); +} + + +void MainGreenlet::operator delete(void* ptr) +{ + return allocator.deallocate(static_cast(ptr), + 1); +} + + +MainGreenlet::MainGreenlet(PyGreenlet* p, ThreadState* state) + : Greenlet(p, StackState::make_main()), + _self(p), + _thread_state(state) +{ + G_TOTAL_MAIN_GREENLETS++; +} + +MainGreenlet::~MainGreenlet() +{ + G_TOTAL_MAIN_GREENLETS--; + this->tp_clear(); +} + +ThreadState* +MainGreenlet::thread_state() const noexcept +{ + return this->_thread_state; +} + +void +MainGreenlet::thread_state(ThreadState* t) noexcept +{ + assert(!t); + this->_thread_state = t; +} + + +const BorrowedMainGreenlet +MainGreenlet::main_greenlet() const +{ + return this->_self; +} + +BorrowedMainGreenlet +MainGreenlet::find_main_greenlet_in_lineage() const +{ + return BorrowedMainGreenlet(this->_self); +} + +bool +MainGreenlet::was_running_in_dead_thread() const noexcept +{ + return !this->_thread_state; +} + +OwnedObject +MainGreenlet::g_switch() +{ + try { + this->check_switch_allowed(); + } + catch (const PyErrOccurred&) { + this->release_args(); + throw; + } + + switchstack_result_t err = this->g_switchstack(); + if (err.status < 0) { + // XXX: This code path is untested, but it is shared + // with the UserGreenlet path that is tested. + return this->on_switchstack_or_initialstub_failure( + this, + err, + true, // target was me + false // was initial stub + ); + } + + return err.the_new_current_greenlet->g_switch_finish(err); +} + +int +MainGreenlet::tp_traverse(visitproc visit, void* arg) +{ + if (this->_thread_state) { + // we've already traversed main, (self), don't do it again. + int result = this->_thread_state->tp_traverse(visit, arg, false); + if (result) { + return result; + } + } + return Greenlet::tp_traverse(visit, arg); +} + +const OwnedObject& +MainGreenlet::run() const +{ + throw AttributeError("Main greenlets do not have a run attribute."); +} + +void +MainGreenlet::run(const BorrowedObject UNUSED(nrun)) +{ + throw AttributeError("Main greenlets do not have a run attribute."); +} + +void +MainGreenlet::parent(const BorrowedObject raw_new_parent) +{ + if (!raw_new_parent) { + throw AttributeError("can't delete attribute"); + } + throw AttributeError("cannot set the parent of a main greenlet"); +} + +const OwnedGreenlet +MainGreenlet::parent() const +{ + return OwnedGreenlet(); // null becomes None +} + +}; // namespace greenlet + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/TPythonState.cpp b/python_embeded/Lib/site-packages/greenlet/TPythonState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7f743cfed6ea571c1b027194a56a72eb1ac329d --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TPythonState.cpp @@ -0,0 +1,402 @@ +#ifndef GREENLET_PYTHON_STATE_CPP +#define GREENLET_PYTHON_STATE_CPP + +#include +#include "TGreenlet.hpp" + +namespace greenlet { + +PythonState::PythonState() + : _top_frame() +#if GREENLET_USE_CFRAME + ,cframe(nullptr) + ,use_tracing(0) +#endif +#if GREENLET_PY314 + ,py_recursion_depth(0) +#elif GREENLET_PY312 + ,py_recursion_depth(0) + ,c_recursion_depth(0) +#else + ,recursion_depth(0) +#endif +#if GREENLET_PY313 + ,delete_later(nullptr) +#else + ,trash_delete_nesting(0) +#endif +#if GREENLET_PY311 + ,current_frame(nullptr) + ,datastack_chunk(nullptr) + ,datastack_top(nullptr) + ,datastack_limit(nullptr) +#endif +{ +#if GREENLET_USE_CFRAME + /* + The PyThreadState->cframe pointer usually points to memory on + the stack, alloceted in a call into PyEval_EvalFrameDefault. + + Initially, before any evaluation begins, it points to the + initial PyThreadState object's ``root_cframe`` object, which is + statically allocated for the lifetime of the thread. + + A greenlet can last for longer than a call to + PyEval_EvalFrameDefault, so we can't set its ``cframe`` pointer + to be the current ``PyThreadState->cframe``; nor could we use + one from the greenlet parent for the same reason. Yet a further + no: we can't allocate one scoped to the greenlet and then + destroy it when the greenlet is deallocated, because inside the + interpreter the _PyCFrame objects form a linked list, and that too + can result in accessing memory beyond its dynamic lifetime (if + the greenlet doesn't actually finish before it dies, its entry + could still be in the list). + + Using the ``root_cframe`` is problematic, though, because its + members are never modified by the interpreter and are set to 0, + meaning that its ``use_tracing`` flag is never updated. We don't + want to modify that value in the ``root_cframe`` ourself: it + *shouldn't* matter much because we should probably never get + back to the point where that's the only cframe on the stack; + even if it did matter, the major consequence of an incorrect + value for ``use_tracing`` is that if its true the interpreter + does some extra work --- however, it's just good code hygiene. + + Our solution: before a greenlet runs, after its initial + creation, it uses the ``root_cframe`` just to have something to + put there. However, once the greenlet is actually switched to + for the first time, ``g_initialstub`` (which doesn't actually + "return" while the greenlet is running) stores a new _PyCFrame on + its local stack, and copies the appropriate values from the + currently running _PyCFrame; this is then made the _PyCFrame for the + newly-minted greenlet. ``g_initialstub`` then proceeds to call + ``glet.run()``, which results in ``PyEval_...`` adding the + _PyCFrame to the list. Switches continue as normal. Finally, when + the greenlet finishes, the call to ``glet.run()`` returns and + the _PyCFrame is taken out of the linked list and the stack value + is now unused and free to expire. + + XXX: I think we can do better. If we're deallocing in the same + thread, can't we traverse the list and unlink our frame? + Can we just keep a reference to the thread state in case we + dealloc in another thread? (Is that even possible if we're still + running and haven't returned from g_initialstub?) + */ + this->cframe = &PyThreadState_GET()->root_cframe; +#endif +} + + +inline void PythonState::may_switch_away() noexcept +{ +#if GREENLET_PY311 + // PyThreadState_GetFrame is probably going to have to allocate a + // new frame object. That may trigger garbage collection. Because + // we call this during the early phases of a switch (it doesn't + // matter to which greenlet, as this has a global effect), if a GC + // triggers a switch away, two things can happen, both bad: + // - We might not get switched back to, halting forward progress. + // this is pathological, but possible. + // - We might get switched back to with a different set of + // arguments or a throw instead of a switch. That would corrupt + // our state (specifically, PyErr_Occurred() and this->args() + // would no longer agree). + // + // Thus, when we call this API, we need to have GC disabled. + // This method serves as a bottleneck we call when maybe beginning + // a switch. In this way, it is always safe -- no risk of GC -- to + // use ``_GetFrame()`` whenever we need to, just as it was in + // <=3.10 (because subsequent calls will be cached and not + // allocate memory). + + GCDisabledGuard no_gc; + Py_XDECREF(PyThreadState_GetFrame(PyThreadState_GET())); +#endif +} + +void PythonState::operator<<(const PyThreadState *const tstate) noexcept +{ + this->_context.steal(tstate->context); +#if GREENLET_USE_CFRAME + /* + IMPORTANT: ``cframe`` is a pointer into the STACK. Thus, because + the call to ``slp_switch()`` changes the contents of the stack, + you cannot read from ``ts_current->cframe`` after that call and + necessarily get the same values you get from reading it here. + Anything you need to restore from now to then must be saved in a + global/threadlocal variable (because we can't use stack + variables here either). For things that need to persist across + the switch, use `will_switch_from`. + */ + this->cframe = tstate->cframe; + #if !GREENLET_PY312 + this->use_tracing = tstate->cframe->use_tracing; + #endif +#endif // GREENLET_USE_CFRAME +#if GREENLET_PY311 + #if GREENLET_PY314 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; + #elif GREENLET_PY312 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; + this->c_recursion_depth = Py_C_RECURSION_LIMIT - tstate->c_recursion_remaining; + #else // not 312 + this->recursion_depth = tstate->recursion_limit - tstate->recursion_remaining; + #endif // GREENLET_PY312 + #if GREENLET_PY313 + this->current_frame = tstate->current_frame; + #elif GREENLET_USE_CFRAME + this->current_frame = tstate->cframe->current_frame; + #endif + this->datastack_chunk = tstate->datastack_chunk; + this->datastack_top = tstate->datastack_top; + this->datastack_limit = tstate->datastack_limit; + + PyFrameObject *frame = PyThreadState_GetFrame((PyThreadState *)tstate); + Py_XDECREF(frame); // PyThreadState_GetFrame gives us a new + // reference. + this->_top_frame.steal(frame); + #if GREENLET_PY313 + this->delete_later = Py_XNewRef(tstate->delete_later); + #elif GREENLET_PY312 + this->trash_delete_nesting = tstate->trash.delete_nesting; + #else // not 312 + this->trash_delete_nesting = tstate->trash_delete_nesting; + #endif // GREENLET_PY312 +#else // Not 311 + this->recursion_depth = tstate->recursion_depth; + this->_top_frame.steal(tstate->frame); + this->trash_delete_nesting = tstate->trash_delete_nesting; +#endif // GREENLET_PY311 +} + +#if GREENLET_PY312 +void GREENLET_NOINLINE(PythonState::unexpose_frames)() +{ + if (!this->top_frame()) { + return; + } + + // See GreenletState::expose_frames() and the comment on frames_were_exposed + // for more information about this logic. + _PyInterpreterFrame *iframe = this->_top_frame->f_frame; + while (iframe != nullptr) { + _PyInterpreterFrame *prev_exposed = iframe->previous; + assert(iframe->frame_obj); + memcpy(&iframe->previous, &iframe->frame_obj->_f_frame_data[0], + sizeof(void *)); + iframe = prev_exposed; + } +} +#else +void PythonState::unexpose_frames() +{} +#endif + +void PythonState::operator>>(PyThreadState *const tstate) noexcept +{ + tstate->context = this->_context.relinquish_ownership(); + /* Incrementing this value invalidates the contextvars cache, + which would otherwise remain valid across switches */ + tstate->context_ver++; +#if GREENLET_USE_CFRAME + tstate->cframe = this->cframe; + /* + If we were tracing, we need to keep tracing. + There should never be the possibility of hitting the + root_cframe here. See note above about why we can't + just copy this from ``origin->cframe->use_tracing``. + */ + #if !GREENLET_PY312 + tstate->cframe->use_tracing = this->use_tracing; + #endif +#endif // GREENLET_USE_CFRAME +#if GREENLET_PY311 + #if GREENLET_PY314 + tstate->py_recursion_remaining = tstate->py_recursion_limit - this->py_recursion_depth; + this->unexpose_frames(); + #elif GREENLET_PY312 + tstate->py_recursion_remaining = tstate->py_recursion_limit - this->py_recursion_depth; + tstate->c_recursion_remaining = Py_C_RECURSION_LIMIT - this->c_recursion_depth; + this->unexpose_frames(); + #else // \/ 3.11 + tstate->recursion_remaining = tstate->recursion_limit - this->recursion_depth; + #endif // GREENLET_PY312 + #if GREENLET_PY313 + tstate->current_frame = this->current_frame; + #elif GREENLET_USE_CFRAME + tstate->cframe->current_frame = this->current_frame; + #endif + tstate->datastack_chunk = this->datastack_chunk; + tstate->datastack_top = this->datastack_top; + tstate->datastack_limit = this->datastack_limit; + this->_top_frame.relinquish_ownership(); + #if GREENLET_PY313 + Py_XDECREF(tstate->delete_later); + tstate->delete_later = this->delete_later; + Py_CLEAR(this->delete_later); + #elif GREENLET_PY312 + tstate->trash.delete_nesting = this->trash_delete_nesting; + #else // not 3.12 + tstate->trash_delete_nesting = this->trash_delete_nesting; + #endif // GREENLET_PY312 +#else // not 3.11 + tstate->frame = this->_top_frame.relinquish_ownership(); + tstate->recursion_depth = this->recursion_depth; + tstate->trash_delete_nesting = this->trash_delete_nesting; +#endif // GREENLET_PY311 +} + +inline void PythonState::will_switch_from(PyThreadState *const origin_tstate) noexcept +{ +#if GREENLET_USE_CFRAME && !GREENLET_PY312 + // The weird thing is, we don't actually save this for an + // effect on the current greenlet, it's saved for an + // effect on the target greenlet. That is, we want + // continuity of this setting across the greenlet switch. + this->use_tracing = origin_tstate->cframe->use_tracing; +#endif +} + +void PythonState::set_initial_state(const PyThreadState* const tstate) noexcept +{ + this->_top_frame = nullptr; +#if GREENLET_PY314 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; +#elif GREENLET_PY312 + this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; + // XXX: TODO: Comment from a reviewer: + // Should this be ``Py_C_RECURSION_LIMIT - tstate->c_recursion_remaining``? + // But to me it looks more like that might not be the right + // initialization either? + this->c_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining; +#elif GREENLET_PY311 + this->recursion_depth = tstate->recursion_limit - tstate->recursion_remaining; +#else + this->recursion_depth = tstate->recursion_depth; +#endif +} +// TODO: Better state management about when we own the top frame. +int PythonState::tp_traverse(visitproc visit, void* arg, bool own_top_frame) noexcept +{ + Py_VISIT(this->_context.borrow()); + if (own_top_frame) { + Py_VISIT(this->_top_frame.borrow()); + } + return 0; +} + +void PythonState::tp_clear(bool own_top_frame) noexcept +{ + PythonStateContext::tp_clear(); + // If we get here owning a frame, + // we got dealloc'd without being finished. We may or may not be + // in the same thread. + if (own_top_frame) { + this->_top_frame.CLEAR(); + } +} + +#if GREENLET_USE_CFRAME +void PythonState::set_new_cframe(_PyCFrame& frame) noexcept +{ + frame = *PyThreadState_GET()->cframe; + /* Make the target greenlet refer to the stack value. */ + this->cframe = &frame; + /* + And restore the link to the previous frame so this one gets + unliked appropriately. + */ + this->cframe->previous = &PyThreadState_GET()->root_cframe; +} +#endif + +const PythonState::OwnedFrame& PythonState::top_frame() const noexcept +{ + return this->_top_frame; +} + +void PythonState::did_finish(PyThreadState* tstate) noexcept +{ +#if GREENLET_PY311 + // See https://github.com/gevent/gevent/issues/1924 and + // https://github.com/python-greenlet/greenlet/issues/328. In + // short, Python 3.11 allocates memory for frames as a sort of + // linked list that's kept as part of PyThreadState in the + // ``datastack_chunk`` member and friends. These are saved and + // restored as part of switching greenlets. + // + // When we initially switch to a greenlet, we set those to NULL. + // That causes the frame management code to treat this like a + // brand new thread and start a fresh list of chunks, beginning + // with a new "root" chunk. As we make calls in this greenlet, + // those chunks get added, and as calls return, they get popped. + // But the frame code (pystate.c) is careful to make sure that the + // root chunk never gets popped. + // + // Thus, when a greenlet exits for the last time, there will be at + // least a single root chunk that we must be responsible for + // deallocating. + // + // The complex part is that these chunks are allocated and freed + // using ``_PyObject_VirtualAlloc``/``Free``. Those aren't public + // functions, and they aren't exported for linking. It so happens + // that we know they are just thin wrappers around the Arena + // allocator, so we can use that directly to deallocate in a + // compatible way. + // + // CAUTION: Check this implementation detail on every major version. + // + // It might be nice to be able to do this in our destructor, but + // can we be sure that no one else is using that memory? Plus, as + // described below, our pointers may not even be valid anymore. As + // a special case, there is one time that we know we can do this, + // and that's from the destructor of the associated UserGreenlet + // (NOT main greenlet) + PyObjectArenaAllocator alloc; + _PyStackChunk* chunk = nullptr; + if (tstate) { + // We really did finish, we can never be switched to again. + chunk = tstate->datastack_chunk; + // Unfortunately, we can't do much sanity checking. Our + // this->datastack_chunk pointer is out of date (evaluation may + // have popped down through it already) so we can't verify that + // we deallocate it. I don't think we can even check datastack_top + // for the same reason. + + PyObject_GetArenaAllocator(&alloc); + tstate->datastack_chunk = nullptr; + tstate->datastack_limit = nullptr; + tstate->datastack_top = nullptr; + + } + else if (this->datastack_chunk) { + // The UserGreenlet (NOT the main greenlet!) is being deallocated. If we're + // still holding a stack chunk, it's garbage because we know + // we can never switch back to let cPython clean it up. + // Because the last time we got switched away from, and we + // haven't run since then, we know our chain is valid and can + // be dealloced. + chunk = this->datastack_chunk; + PyObject_GetArenaAllocator(&alloc); + } + + if (alloc.free && chunk) { + // In case the arena mechanism has been torn down already. + while (chunk) { + _PyStackChunk *prev = chunk->previous; + chunk->previous = nullptr; + alloc.free(alloc.ctx, chunk, chunk->size); + chunk = prev; + } + } + + this->datastack_chunk = nullptr; + this->datastack_limit = nullptr; + this->datastack_top = nullptr; +#endif +} + + +}; // namespace greenlet + +#endif // GREENLET_PYTHON_STATE_CPP diff --git a/python_embeded/Lib/site-packages/greenlet/TStackState.cpp b/python_embeded/Lib/site-packages/greenlet/TStackState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9743ab51b56738e20d1bcaa70ea1e01c599299dd --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TStackState.cpp @@ -0,0 +1,265 @@ +#ifndef GREENLET_STACK_STATE_CPP +#define GREENLET_STACK_STATE_CPP + +#include "TGreenlet.hpp" + +namespace greenlet { + +#ifdef GREENLET_USE_STDIO +#include +using std::cerr; +using std::endl; + +std::ostream& operator<<(std::ostream& os, const StackState& s) +{ + os << "StackState(stack_start=" << (void*)s._stack_start + << ", stack_stop=" << (void*)s.stack_stop + << ", stack_copy=" << (void*)s.stack_copy + << ", stack_saved=" << s._stack_saved + << ", stack_prev=" << s.stack_prev + << ", addr=" << &s + << ")"; + return os; +} +#endif + +StackState::StackState(void* mark, StackState& current) + : _stack_start(nullptr), + stack_stop((char*)mark), + stack_copy(nullptr), + _stack_saved(0), + /* Skip a dying greenlet */ + stack_prev(current._stack_start + ? ¤t + : current.stack_prev) +{ +} + +StackState::StackState() + : _stack_start(nullptr), + stack_stop(nullptr), + stack_copy(nullptr), + _stack_saved(0), + stack_prev(nullptr) +{ +} + +StackState::StackState(const StackState& other) +// can't use a delegating constructor because of +// MSVC for Python 2.7 + : _stack_start(nullptr), + stack_stop(nullptr), + stack_copy(nullptr), + _stack_saved(0), + stack_prev(nullptr) +{ + this->operator=(other); +} + +StackState& StackState::operator=(const StackState& other) +{ + if (&other == this) { + return *this; + } + if (other._stack_saved) { + throw std::runtime_error("Refusing to steal memory."); + } + + //If we have memory allocated, dispose of it + this->free_stack_copy(); + + this->_stack_start = other._stack_start; + this->stack_stop = other.stack_stop; + this->stack_copy = other.stack_copy; + this->_stack_saved = other._stack_saved; + this->stack_prev = other.stack_prev; + return *this; +} + +inline void StackState::free_stack_copy() noexcept +{ + PyMem_Free(this->stack_copy); + this->stack_copy = nullptr; + this->_stack_saved = 0; +} + +inline void StackState::copy_heap_to_stack(const StackState& current) noexcept +{ + + /* Restore the heap copy back into the C stack */ + if (this->_stack_saved != 0) { + memcpy(this->_stack_start, this->stack_copy, this->_stack_saved); + this->free_stack_copy(); + } + StackState* owner = const_cast(¤t); + if (!owner->_stack_start) { + owner = owner->stack_prev; /* greenlet is dying, skip it */ + } + while (owner && owner->stack_stop <= this->stack_stop) { + // cerr << "\tOwner: " << owner << endl; + owner = owner->stack_prev; /* find greenlet with more stack */ + } + this->stack_prev = owner; + // cerr << "\tFinished with: " << *this << endl; +} + +inline int StackState::copy_stack_to_heap_up_to(const char* const stop) noexcept +{ + /* Save more of g's stack into the heap -- at least up to 'stop' + g->stack_stop |________| + | | + | __ stop . . . . . + | | ==> . . + |________| _______ + | | | | + | | | | + g->stack_start | | |_______| g->stack_copy + */ + intptr_t sz1 = this->_stack_saved; + intptr_t sz2 = stop - this->_stack_start; + assert(this->_stack_start); + if (sz2 > sz1) { + char* c = (char*)PyMem_Realloc(this->stack_copy, sz2); + if (!c) { + PyErr_NoMemory(); + return -1; + } + memcpy(c + sz1, this->_stack_start + sz1, sz2 - sz1); + this->stack_copy = c; + this->_stack_saved = sz2; + } + return 0; +} + +inline int StackState::copy_stack_to_heap(char* const stackref, + const StackState& current) noexcept +{ + /* must free all the C stack up to target_stop */ + const char* const target_stop = this->stack_stop; + + StackState* owner = const_cast(¤t); + assert(owner->_stack_saved == 0); // everything is present on the stack + if (!owner->_stack_start) { + owner = owner->stack_prev; /* not saved if dying */ + } + else { + owner->_stack_start = stackref; + } + + while (owner->stack_stop < target_stop) { + /* ts_current is entierely within the area to free */ + if (owner->copy_stack_to_heap_up_to(owner->stack_stop)) { + return -1; /* XXX */ + } + owner = owner->stack_prev; + } + if (owner != this) { + if (owner->copy_stack_to_heap_up_to(target_stop)) { + return -1; /* XXX */ + } + } + return 0; +} + +inline bool StackState::started() const noexcept +{ + return this->stack_stop != nullptr; +} + +inline bool StackState::main() const noexcept +{ + return this->stack_stop == (char*)-1; +} + +inline bool StackState::active() const noexcept +{ + return this->_stack_start != nullptr; +} + +inline void StackState::set_active() noexcept +{ + assert(this->_stack_start == nullptr); + this->_stack_start = (char*)1; +} + +inline void StackState::set_inactive() noexcept +{ + this->_stack_start = nullptr; + // XXX: What if we still have memory out there? + // That case is actually triggered by + // test_issue251_issue252_explicit_reference_not_collectable (greenlet.tests.test_leaks.TestLeaks) + // and + // test_issue251_issue252_need_to_collect_in_background + // (greenlet.tests.test_leaks.TestLeaks) + // + // Those objects never get deallocated, so the destructor never + // runs. + // It *seems* safe to clean up the memory here? + if (this->_stack_saved) { + this->free_stack_copy(); + } +} + +inline intptr_t StackState::stack_saved() const noexcept +{ + return this->_stack_saved; +} + +inline char* StackState::stack_start() const noexcept +{ + return this->_stack_start; +} + + +inline StackState StackState::make_main() noexcept +{ + StackState s; + s._stack_start = (char*)1; + s.stack_stop = (char*)-1; + return s; +} + +StackState::~StackState() +{ + if (this->_stack_saved != 0) { + this->free_stack_copy(); + } +} + +void StackState::copy_from_stack(void* vdest, const void* vsrc, size_t n) const +{ + char* dest = static_cast(vdest); + const char* src = static_cast(vsrc); + if (src + n <= this->_stack_start + || src >= this->_stack_start + this->_stack_saved + || this->_stack_saved == 0) { + // Nothing we're copying was spilled from the stack + memcpy(dest, src, n); + return; + } + + if (src < this->_stack_start) { + // Copy the part before the saved stack. + // We know src + n > _stack_start due to the test above. + const size_t nbefore = this->_stack_start - src; + memcpy(dest, src, nbefore); + dest += nbefore; + src += nbefore; + n -= nbefore; + } + // We know src >= _stack_start after the before-copy, and + // src < _stack_start + _stack_saved due to the first if condition + size_t nspilled = std::min(n, this->_stack_start + this->_stack_saved - src); + memcpy(dest, this->stack_copy + (src - this->_stack_start), nspilled); + dest += nspilled; + src += nspilled; + n -= nspilled; + if (n > 0) { + // Copy the part after the saved stack + memcpy(dest, src, n); + } +} + +}; // namespace greenlet + +#endif // GREENLET_STACK_STATE_CPP diff --git a/python_embeded/Lib/site-packages/greenlet/TThreadState.hpp b/python_embeded/Lib/site-packages/greenlet/TThreadState.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e4e6f6cba952a277b6321d84c9688eaebc34d38d --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TThreadState.hpp @@ -0,0 +1,497 @@ +#ifndef GREENLET_THREAD_STATE_HPP +#define GREENLET_THREAD_STATE_HPP + +#include +#include + +#include "greenlet_internal.hpp" +#include "greenlet_refs.hpp" +#include "greenlet_thread_support.hpp" + +using greenlet::refs::BorrowedObject; +using greenlet::refs::BorrowedGreenlet; +using greenlet::refs::BorrowedMainGreenlet; +using greenlet::refs::OwnedMainGreenlet; +using greenlet::refs::OwnedObject; +using greenlet::refs::OwnedGreenlet; +using greenlet::refs::OwnedList; +using greenlet::refs::PyErrFetchParam; +using greenlet::refs::PyArgParseParam; +using greenlet::refs::ImmortalString; +using greenlet::refs::CreatedModule; +using greenlet::refs::PyErrPieces; +using greenlet::refs::NewReference; + +namespace greenlet { +/** + * Thread-local state of greenlets. + * + * Each native thread will get exactly one of these objects, + * automatically accessed through the best available thread-local + * mechanism the compiler supports (``thread_local`` for C++11 + * compilers or ``__thread``/``declspec(thread)`` for older GCC/clang + * or MSVC, respectively.) + * + * Previously, we kept thread-local state mostly in a bunch of + * ``static volatile`` variables in the main greenlet file.. This had + * the problem of requiring extra checks, loops, and great care + * accessing these variables if we potentially invoked any Python code + * that could release the GIL, because the state could change out from + * under us. Making the variables thread-local solves this problem. + * + * When we detected that a greenlet API accessing the current greenlet + * was invoked from a different thread than the greenlet belonged to, + * we stored a reference to the greenlet in the Python thread + * dictionary for the thread the greenlet belonged to. This could lead + * to memory leaks if the thread then exited (because of a reference + * cycle, as greenlets referred to the thread dictionary, and deleting + * non-current greenlets leaked their frame plus perhaps arguments on + * the C stack). If a thread exited while still having running + * greenlet objects (perhaps that had just switched back to the main + * greenlet), and did not invoke one of the greenlet APIs *in that + * thread, immediately before it exited, without some other thread + * then being invoked*, such a leak was guaranteed. + * + * This can be partly solved by using compiler thread-local variables + * instead of the Python thread dictionary, thus avoiding a cycle. + * + * To fully solve this problem, we need a reliable way to know that a + * thread is done and we should clean up the main greenlet. On POSIX, + * we can use the destructor function of ``pthread_key_create``, but + * there's nothing similar on Windows; a C++11 thread local object + * reliably invokes its destructor when the thread it belongs to exits + * (non-C++11 compilers offer ``__thread`` or ``declspec(thread)`` to + * create thread-local variables, but they can't hold C++ objects that + * invoke destructors; the C++11 version is the most portable solution + * I found). When the thread exits, we can drop references and + * otherwise manipulate greenlets and frames that we know can no + * longer be switched to. For compilers that don't support C++11 + * thread locals, we have a solution that uses the python thread + * dictionary, though it may not collect everything as promptly as + * other compilers do, if some other library is using the thread + * dictionary and has a cycle or extra reference. + * + * There are two small wrinkles. The first is that when the thread + * exits, it is too late to actually invoke Python APIs: the Python + * thread state is gone, and the GIL is released. To solve *this* + * problem, our destructor uses ``Py_AddPendingCall`` to transfer the + * destruction work to the main thread. (This is not an issue for the + * dictionary solution.) + * + * The second is that once the thread exits, the thread local object + * is invalid and we can't even access a pointer to it, so we can't + * pass it to ``Py_AddPendingCall``. This is handled by actually using + * a second object that's thread local (ThreadStateCreator) and having + * it dynamically allocate this object so it can live until the + * pending call runs. + */ + + + +class ThreadState { +private: + // As of commit 08ad1dd7012b101db953f492e0021fb08634afad + // this class needed 56 bytes in o Py_DEBUG build + // on 64-bit macOS 11. + // Adding the vector takes us up to 80 bytes () + + /* Strong reference to the main greenlet */ + OwnedMainGreenlet main_greenlet; + + /* Strong reference to the current greenlet. */ + OwnedGreenlet current_greenlet; + + /* Strong reference to the trace function, if any. */ + OwnedObject tracefunc; + + typedef std::vector > deleteme_t; + /* A vector of raw PyGreenlet pointers representing things that need + deleted when this thread is running. The vector owns the + references, but you need to manually INCREF/DECREF as you use + them. We don't use a vector because we + make copy of this vector, and that would become O(n) as all the + refcounts are incremented in the copy. + */ + deleteme_t deleteme; + +#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED + void* exception_state; +#endif + + static std::clock_t _clocks_used_doing_gc; + static ImmortalString get_referrers_name; + static PythonAllocator allocator; + + G_NO_COPIES_OF_CLS(ThreadState); + + + // Allocates a main greenlet for the thread state. If this fails, + // exits the process. Called only during constructing a ThreadState. + MainGreenlet* alloc_main() + { + PyGreenlet* gmain; + + /* create the main greenlet for this thread */ + gmain = reinterpret_cast(PyType_GenericAlloc(&PyGreenlet_Type, 0)); + if (gmain == NULL) { + throw PyFatalError("alloc_main failed to alloc"); //exits the process + } + + MainGreenlet* const main = new MainGreenlet(gmain, this); + + assert(Py_REFCNT(gmain) == 1); + assert(gmain->pimpl == main); + return main; + } + + +public: + static void* operator new(size_t UNUSED(count)) + { + return ThreadState::allocator.allocate(1); + } + + static void operator delete(void* ptr) + { + return ThreadState::allocator.deallocate(static_cast(ptr), + 1); + } + + static void init() + { + ThreadState::get_referrers_name = "get_referrers"; + ThreadState::_clocks_used_doing_gc = 0; + } + + ThreadState() + { + +#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED + this->exception_state = slp_get_exception_state(); +#endif + + // XXX: Potentially dangerous, exposing a not fully + // constructed object. + MainGreenlet* const main = this->alloc_main(); + this->main_greenlet = OwnedMainGreenlet::consuming( + main->self() + ); + assert(this->main_greenlet); + this->current_greenlet = main->self(); + // The main greenlet starts with 1 refs: The returned one. We + // then copied it to the current greenlet. + assert(this->main_greenlet.REFCNT() == 2); + } + + inline void restore_exception_state() + { +#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED + // It's probably important this be inlined and only call C + // functions to avoid adding an SEH frame. + slp_set_exception_state(this->exception_state); +#endif + } + + inline bool has_main_greenlet() const noexcept + { + return bool(this->main_greenlet); + } + + // Called from the ThreadStateCreator when we're in non-standard + // threading mode. In that case, there is an object in the Python + // thread state dictionary that points to us. The main greenlet + // also traverses into us, in which case it's crucial not to + // traverse back into the main greenlet. + int tp_traverse(visitproc visit, void* arg, bool traverse_main=true) + { + if (traverse_main) { + Py_VISIT(main_greenlet.borrow_o()); + } + if (traverse_main || current_greenlet != main_greenlet) { + Py_VISIT(current_greenlet.borrow_o()); + } + Py_VISIT(tracefunc.borrow()); + return 0; + } + + inline BorrowedMainGreenlet borrow_main_greenlet() const noexcept + { + assert(this->main_greenlet); + assert(this->main_greenlet.REFCNT() >= 2); + return this->main_greenlet; + }; + + inline OwnedMainGreenlet get_main_greenlet() const noexcept + { + return this->main_greenlet; + } + + /** + * In addition to returning a new reference to the currunt + * greenlet, this performs any maintenance needed. + */ + inline OwnedGreenlet get_current() + { + /* green_dealloc() cannot delete greenlets from other threads, so + it stores them in the thread dict; delete them now. */ + this->clear_deleteme_list(); + //assert(this->current_greenlet->main_greenlet == this->main_greenlet); + //assert(this->main_greenlet->main_greenlet == this->main_greenlet); + return this->current_greenlet; + } + + /** + * As for non-const get_current(); + */ + inline BorrowedGreenlet borrow_current() + { + this->clear_deleteme_list(); + return this->current_greenlet; + } + + /** + * Does no maintenance. + */ + inline OwnedGreenlet get_current() const + { + return this->current_greenlet; + } + + template + inline bool is_current(const refs::PyObjectPointer& obj) const + { + return this->current_greenlet.borrow_o() == obj.borrow_o(); + } + + inline void set_current(const OwnedGreenlet& target) + { + this->current_greenlet = target; + } + +private: + /** + * Deref and remove the greenlets from the deleteme list. Must be + * holding the GIL. + * + * If *murder* is true, then we must be called from a different + * thread than the one that these greenlets were running in. + * In that case, if the greenlet was actually running, we destroy + * the frame reference and otherwise make it appear dead before + * proceeding; otherwise, we would try (and fail) to raise an + * exception in it and wind up right back in this list. + */ + inline void clear_deleteme_list(const bool murder=false) + { + if (!this->deleteme.empty()) { + // It's possible we could add items to this list while + // running Python code if there's a thread switch, so we + // need to defensively copy it before that can happen. + deleteme_t copy = this->deleteme; + this->deleteme.clear(); // in case things come back on the list + for(deleteme_t::iterator it = copy.begin(), end = copy.end(); + it != end; + ++it ) { + PyGreenlet* to_del = *it; + if (murder) { + // Force each greenlet to appear dead; we can't raise an + // exception into it anymore anyway. + to_del->pimpl->murder_in_place(); + } + + // The only reference to these greenlets should be in + // this list, decreffing them should let them be + // deleted again, triggering calls to green_dealloc() + // in the correct thread (if we're not murdering). + // This may run arbitrary Python code and switch + // threads or greenlets! + Py_DECREF(to_del); + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(nullptr); + PyErr_Clear(); + } + } + } + } + +public: + + /** + * Returns a new reference, or a false object. + */ + inline OwnedObject get_tracefunc() const + { + return tracefunc; + }; + + + inline void set_tracefunc(BorrowedObject tracefunc) + { + assert(tracefunc); + if (tracefunc == BorrowedObject(Py_None)) { + this->tracefunc.CLEAR(); + } + else { + this->tracefunc = tracefunc; + } + } + + /** + * Given a reference to a greenlet that some other thread + * attempted to delete (has a refcount of 0) store it for later + * deletion when the thread this state belongs to is current. + */ + inline void delete_when_thread_running(PyGreenlet* to_del) + { + Py_INCREF(to_del); + this->deleteme.push_back(to_del); + } + + /** + * Set to std::clock_t(-1) to disable. + */ + inline static std::clock_t& clocks_used_doing_gc() + { + return ThreadState::_clocks_used_doing_gc; + } + + ~ThreadState() + { + if (!PyInterpreterState_Head()) { + // We shouldn't get here (our callers protect us) + // but if we do, all we can do is bail early. + return; + } + + // We should not have an "origin" greenlet; that only exists + // for the temporary time during a switch, which should not + // be in progress as the thread dies. + //assert(!this->switching_state.origin); + + this->tracefunc.CLEAR(); + + // Forcibly GC as much as we can. + this->clear_deleteme_list(true); + + // The pending call did this. + assert(this->main_greenlet->thread_state() == nullptr); + + // If the main greenlet is the current greenlet, + // then we "fell off the end" and the thread died. + // It's possible that there is some other greenlet that + // switched to us, leaving a reference to the main greenlet + // on the stack, somewhere uncollectible. Try to detect that. + if (this->current_greenlet == this->main_greenlet && this->current_greenlet) { + assert(this->current_greenlet->is_currently_running_in_some_thread()); + // Drop one reference we hold. + this->current_greenlet.CLEAR(); + assert(!this->current_greenlet); + // Only our reference to the main greenlet should be left, + // But hold onto the pointer in case we need to do extra cleanup. + PyGreenlet* old_main_greenlet = this->main_greenlet.borrow(); + Py_ssize_t cnt = this->main_greenlet.REFCNT(); + this->main_greenlet.CLEAR(); + if (ThreadState::_clocks_used_doing_gc != std::clock_t(-1) + && cnt == 2 && Py_REFCNT(old_main_greenlet) == 1) { + // Highly likely that the reference is somewhere on + // the stack, not reachable by GC. Verify. + // XXX: This is O(n) in the total number of objects. + // TODO: Add a way to disable this at runtime, and + // another way to report on it. + std::clock_t begin = std::clock(); + NewReference gc(PyImport_ImportModule("gc")); + if (gc) { + OwnedObject get_referrers = gc.PyRequireAttr(ThreadState::get_referrers_name); + OwnedList refs(get_referrers.PyCall(old_main_greenlet)); + if (refs && refs.empty()) { + assert(refs.REFCNT() == 1); + // We found nothing! So we left a dangling + // reference: Probably the last thing some + // other greenlet did was call + // 'getcurrent().parent.switch()' to switch + // back to us. Clean it up. This will be the + // case on CPython 3.7 and newer, as they use + // an internal calling conversion that avoids + // creating method objects and storing them on + // the stack. + Py_DECREF(old_main_greenlet); + } + else if (refs + && refs.size() == 1 + && PyCFunction_Check(refs.at(0)) + && Py_REFCNT(refs.at(0)) == 2) { + assert(refs.REFCNT() == 1); + // Ok, we found a C method that refers to the + // main greenlet, and its only referenced + // twice, once in the list we just created, + // once from...somewhere else. If we can't + // find where else, then this is a leak. + // This happens in older versions of CPython + // that create a bound method object somewhere + // on the stack that we'll never get back to. + if (PyCFunction_GetFunction(refs.at(0).borrow()) == (PyCFunction)green_switch) { + BorrowedObject function_w = refs.at(0); + refs.clear(); // destroy the reference + // from the list. + // back to one reference. Can *it* be + // found? + assert(function_w.REFCNT() == 1); + refs = get_referrers.PyCall(function_w); + if (refs && refs.empty()) { + // Nope, it can't be found so it won't + // ever be GC'd. Drop it. + Py_CLEAR(function_w); + } + } + } + std::clock_t end = std::clock(); + ThreadState::_clocks_used_doing_gc += (end - begin); + } + } + } + + // We need to make sure this greenlet appears to be dead, + // because otherwise deallocing it would fail to raise an + // exception in it (the thread is dead) and put it back in our + // deleteme list. + if (this->current_greenlet) { + this->current_greenlet->murder_in_place(); + this->current_greenlet.CLEAR(); + } + + if (this->main_greenlet) { + // Couldn't have been the main greenlet that was running + // when the thread exited (because we already cleared this + // pointer if it was). This shouldn't be possible? + + // If the main greenlet was current when the thread died (it + // should be, right?) then we cleared its self pointer above + // when we cleared the current greenlet's main greenlet pointer. + // assert(this->main_greenlet->main_greenlet == this->main_greenlet + // || !this->main_greenlet->main_greenlet); + // // self reference, probably gone + // this->main_greenlet->main_greenlet.CLEAR(); + + // This will actually go away when the ivar is destructed. + this->main_greenlet.CLEAR(); + } + + if (PyErr_Occurred()) { + PyErr_WriteUnraisable(NULL); + PyErr_Clear(); + } + + } + +}; + +ImmortalString ThreadState::get_referrers_name(nullptr); +PythonAllocator ThreadState::allocator; +std::clock_t ThreadState::_clocks_used_doing_gc(0); + + + + + +}; // namespace greenlet + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/TThreadStateCreator.hpp b/python_embeded/Lib/site-packages/greenlet/TThreadStateCreator.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2ec7ab55bb5c887da8d216215727d549b2cbcf02 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TThreadStateCreator.hpp @@ -0,0 +1,102 @@ +#ifndef GREENLET_THREAD_STATE_CREATOR_HPP +#define GREENLET_THREAD_STATE_CREATOR_HPP + +#include +#include + +#include "greenlet_internal.hpp" +#include "greenlet_refs.hpp" +#include "greenlet_thread_support.hpp" + +#include "TThreadState.hpp" + +namespace greenlet { + + +typedef void (*ThreadStateDestructor)(ThreadState* const); + +template +class ThreadStateCreator +{ +private: + // Initialized to 1, and, if still 1, created on access. + // Set to 0 on destruction. + ThreadState* _state; + G_NO_COPIES_OF_CLS(ThreadStateCreator); + + inline bool has_initialized_state() const noexcept + { + return this->_state != (ThreadState*)1; + } + + inline bool has_state() const noexcept + { + return this->has_initialized_state() && this->_state != nullptr; + } + +public: + + // Only one of these, auto created per thread. + // Constructing the state constructs the MainGreenlet. + ThreadStateCreator() : + _state((ThreadState*)1) + { + } + + ~ThreadStateCreator() + { + if (this->has_state()) { + Destructor(this->_state); + } + + this->_state = nullptr; + } + + inline ThreadState& state() + { + // The main greenlet will own this pointer when it is created, + // which will be right after this. The plan is to give every + // greenlet a pointer to the main greenlet for the thread it + // runs in; if we are doing something cross-thread, we need to + // access the pointer from the main greenlet. Deleting the + // thread, and hence the thread-local storage, will delete the + // state pointer in the main greenlet. + if (!this->has_initialized_state()) { + // XXX: Assuming allocation never fails + this->_state = new ThreadState; + // For non-standard threading, we need to store an object + // in the Python thread state dictionary so that it can be + // DECREF'd when the thread ends (ideally; the dict could + // last longer) and clean this object up. + } + if (!this->_state) { + throw std::runtime_error("Accessing state after destruction."); + } + return *this->_state; + } + + operator ThreadState&() + { + return this->state(); + } + + operator ThreadState*() + { + return &this->state(); + } + + inline int tp_traverse(visitproc visit, void* arg) + { + if (this->has_state()) { + return this->_state->tp_traverse(visit, arg); + } + return 0; + } + +}; + + + +}; // namespace greenlet + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/TThreadStateDestroy.cpp b/python_embeded/Lib/site-packages/greenlet/TThreadStateDestroy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..449b7887113b2398330716dca44e5ca9f7840fc9 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TThreadStateDestroy.cpp @@ -0,0 +1,217 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of the ThreadState destructors. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_THREADSTATE_DESTROY +#define T_THREADSTATE_DESTROY + +#include "TGreenlet.hpp" + +#include "greenlet_thread_support.hpp" +#include "greenlet_compiler_compat.hpp" +#include "TGreenletGlobals.cpp" +#include "TThreadState.hpp" +#include "TThreadStateCreator.hpp" + +namespace greenlet { + +extern "C" { + +struct ThreadState_DestroyNoGIL +{ + /** + This function uses the same lock that the PendingCallback does + */ + static void + MarkGreenletDeadAndQueueCleanup(ThreadState* const state) + { +#if GREENLET_BROKEN_THREAD_LOCAL_CLEANUP_JUST_LEAK + return; +#endif + // We are *NOT* holding the GIL. Our thread is in the middle + // of its death throes and the Python thread state is already + // gone so we can't use most Python APIs. One that is safe is + // ``Py_AddPendingCall``, unless the interpreter itself has + // been torn down. There is a limited number of calls that can + // be queued: 32 (NPENDINGCALLS) in CPython 3.10, so we + // coalesce these calls using our own queue. + + if (!MarkGreenletDeadIfNeeded(state)) { + // No state, or no greenlet + return; + } + + // XXX: Because we don't have the GIL, this is a race condition. + if (!PyInterpreterState_Head()) { + // We have to leak the thread state, if the + // interpreter has shut down when we're getting + // deallocated, we can't run the cleanup code that + // deleting it would imply. + return; + } + + AddToCleanupQueue(state); + + } + +private: + + // If the state has an allocated main greenlet: + // - mark the greenlet as dead by disassociating it from the state; + // - return 1 + // Otherwise, return 0. + static bool + MarkGreenletDeadIfNeeded(ThreadState* const state) + { + if (state && state->has_main_greenlet()) { + // mark the thread as dead ASAP. + // this is racy! If we try to throw or switch to a + // greenlet from this thread from some other thread before + // we clear the state pointer, it won't realize the state + // is dead which can crash the process. + PyGreenlet* p(state->borrow_main_greenlet().borrow()); + assert(p->pimpl->thread_state() == state || p->pimpl->thread_state() == nullptr); + dynamic_cast(p->pimpl)->thread_state(nullptr); + return true; + } + return false; + } + + static void + AddToCleanupQueue(ThreadState* const state) + { + assert(state && state->has_main_greenlet()); + + // NOTE: Because we're not holding the GIL here, some other + // Python thread could run and call ``os.fork()``, which would + // be bad if that happened while we are holding the cleanup + // lock (it wouldn't function in the child process). + // Make a best effort to try to keep the duration we hold the + // lock short. + // TODO: On platforms that support it, use ``pthread_atfork`` to + // drop this lock. + LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); + + mod_globs->queue_to_destroy(state); + if (mod_globs->thread_states_to_destroy.size() == 1) { + // We added the first item to the queue. We need to schedule + // the cleanup. + + // A size greater than 1 means that we have already added the pending call, + // and in fact, it may be executing now. + // If it is executing, our lock makes sure that it will see the item we just added + // to the queue on its next iteration (after we release the lock) + // + // A size of 1 means there is no pending call, OR the pending call is + // currently executing, has dropped the lock, and is deleting the last item + // from the queue; its next iteration will go ahead and delete the item we just added. + // And the pending call we schedule here will have no work to do. + int result = AddPendingCall( + PendingCallback_DestroyQueueWithGIL, + nullptr); + if (result < 0) { + // Hmm, what can we do here? + fprintf(stderr, + "greenlet: WARNING: failed in call to Py_AddPendingCall; " + "expect a memory leak.\n"); + } + } + } + + static int + PendingCallback_DestroyQueueWithGIL(void* UNUSED(arg)) + { + // We're holding the GIL here, so no Python code should be able to + // run to call ``os.fork()``. + while (1) { + ThreadState* to_destroy; + { + LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock); + if (mod_globs->thread_states_to_destroy.empty()) { + break; + } + to_destroy = mod_globs->take_next_to_destroy(); + } + assert(to_destroy); + assert(to_destroy->has_main_greenlet()); + // Drop the lock while we do the actual deletion. + // This allows other calls to MarkGreenletDeadAndQueueCleanup + // to enter and add to our queue. + DestroyOneWithGIL(to_destroy); + } + return 0; + } + + static void + DestroyOneWithGIL(const ThreadState* const state) + { + // Holding the GIL. + // Passed a non-shared pointer to the actual thread state. + // state -> main greenlet + assert(state->has_main_greenlet()); + PyGreenlet* main(state->borrow_main_greenlet()); + // When we need to do cross-thread operations, we check this. + // A NULL value means the thread died some time ago. + // We do this here, rather than in a Python dealloc function + // for the greenlet, in case there's still a reference out + // there. + dynamic_cast(main->pimpl)->thread_state(nullptr); + + delete state; // Deleting this runs the destructor, DECREFs the main greenlet. + } + + + static int AddPendingCall(int (*func)(void*), void* arg) + { + // If the interpreter is in the middle of finalizing, we can't add a + // pending call. Trying to do so will end up in a SIGSEGV, as + // Py_AddPendingCall will not be able to get the interpreter and will + // try to dereference a NULL pointer. It's possible this can still + // segfault if we happen to get context switched, and maybe we should + // just always implement our own AddPendingCall, but I'd like to see if + // this works first +#if GREENLET_PY313 + if (Py_IsFinalizing()) { +#else + if (_Py_IsFinalizing()) { +#endif +#ifdef GREENLET_DEBUG + // No need to log in the general case. Yes, we'll leak, + // but we're shutting down so it should be ok. + fprintf(stderr, + "greenlet: WARNING: Interpreter is finalizing. Ignoring " + "call to Py_AddPendingCall; \n"); +#endif + return 0; + } + return Py_AddPendingCall(func, arg); + } + + + + + +}; +}; + +}; // namespace greenlet + +// The intent when GET_THREAD_STATE() is needed multiple times in a +// function is to take a reference to its return value in a local +// variable, to avoid the thread-local indirection. On some platforms +// (macOS), accessing a thread-local involves a function call (plus an +// initial function call in each function that uses a thread local); +// in contrast, static volatile variables are at some pre-computed +// offset. +typedef greenlet::ThreadStateCreator ThreadStateCreator; +static thread_local ThreadStateCreator g_thread_state_global; +#define GET_THREAD_STATE() g_thread_state_global + +#endif //T_THREADSTATE_DESTROY diff --git a/python_embeded/Lib/site-packages/greenlet/TUserGreenlet.cpp b/python_embeded/Lib/site-packages/greenlet/TUserGreenlet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73a81330d1f70dad3b8fbe922bdcd2102cca55dc --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/TUserGreenlet.cpp @@ -0,0 +1,662 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/** + * Implementation of greenlet::UserGreenlet. + * + * Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#ifndef T_USER_GREENLET_CPP +#define T_USER_GREENLET_CPP + +#include "greenlet_internal.hpp" +#include "TGreenlet.hpp" + +#include "TThreadStateDestroy.cpp" + + +namespace greenlet { +using greenlet::refs::BorrowedMainGreenlet; +greenlet::PythonAllocator UserGreenlet::allocator; + +void* UserGreenlet::operator new(size_t UNUSED(count)) +{ + return allocator.allocate(1); +} + + +void UserGreenlet::operator delete(void* ptr) +{ + return allocator.deallocate(static_cast(ptr), + 1); +} + + +UserGreenlet::UserGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent) + : Greenlet(p), _parent(the_parent) +{ +} + +UserGreenlet::~UserGreenlet() +{ + // Python 3.11: If we don't clear out the raw frame datastack + // when deleting an unfinished greenlet, + // TestLeaks.test_untracked_memory_doesnt_increase_unfinished_thread_dealloc_in_main fails. + this->python_state.did_finish(nullptr); + this->tp_clear(); +} + + +const BorrowedMainGreenlet +UserGreenlet::main_greenlet() const +{ + return this->_main_greenlet; +} + + +BorrowedMainGreenlet +UserGreenlet::find_main_greenlet_in_lineage() const +{ + if (this->started()) { + assert(this->_main_greenlet); + return BorrowedMainGreenlet(this->_main_greenlet); + } + + if (!this->_parent) { + /* garbage collected greenlet in chain */ + // XXX: WHAT? + return BorrowedMainGreenlet(nullptr); + } + + return this->_parent->find_main_greenlet_in_lineage(); +} + + +/** + * CAUTION: This will allocate memory and may trigger garbage + * collection and arbitrary Python code. + */ +OwnedObject +UserGreenlet::throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state) +{ + /* The dying greenlet cannot be a parent of ts_current + because the 'parent' field chain would hold a + reference */ + UserGreenlet::ParentIsCurrentGuard with_current_parent(this, current_thread_state); + + // We don't care about the return value, only whether an + // exception happened. Whether or not an exception happens, + // we need to restore the parent in case the greenlet gets + // resurrected. + return Greenlet::throw_GreenletExit_during_dealloc(current_thread_state); +} + +ThreadState* +UserGreenlet::thread_state() const noexcept +{ + // TODO: maybe make this throw, if the thread state isn't there? + // if (!this->main_greenlet) { + // throw std::runtime_error("No thread state"); // TODO: Better exception + // } + if (!this->_main_greenlet) { + return nullptr; + } + return this->_main_greenlet->thread_state(); +} + + +bool +UserGreenlet::was_running_in_dead_thread() const noexcept +{ + return this->_main_greenlet && !this->thread_state(); +} + +OwnedObject +UserGreenlet::g_switch() +{ + assert(this->args() || PyErr_Occurred()); + + try { + this->check_switch_allowed(); + } + catch (const PyErrOccurred&) { + this->release_args(); + throw; + } + + // Switching greenlets used to attempt to clean out ones that need + // deleted *if* we detected a thread switch. Should it still do + // that? + // An issue is that if we delete a greenlet from another thread, + // it gets queued to this thread, and ``kill_greenlet()`` switches + // back into the greenlet + + /* find the real target by ignoring dead greenlets, + and if necessary starting a greenlet. */ + switchstack_result_t err; + Greenlet* target = this; + // TODO: probably cleaner to handle the case where we do + // switch to ourself separately from the other cases. + // This can probably even further be simplified if we keep + // track of the switching_state we're going for and just call + // into g_switch() if it's not ourself. The main problem with that + // is that we would be using more stack space. + bool target_was_me = true; + bool was_initial_stub = false; + while (target) { + if (target->active()) { + if (!target_was_me) { + target->args() <<= this->args(); + assert(!this->args()); + } + err = target->g_switchstack(); + break; + } + if (!target->started()) { + // We never encounter a main greenlet that's not started. + assert(!target->main()); + UserGreenlet* real_target = static_cast(target); + assert(real_target); + void* dummymarker; + was_initial_stub = true; + if (!target_was_me) { + target->args() <<= this->args(); + assert(!this->args()); + } + try { + // This can only throw back to us while we're + // still in this greenlet. Once the new greenlet + // is bootstrapped, it has its own exception state. + err = real_target->g_initialstub(&dummymarker); + } + catch (const PyErrOccurred&) { + this->release_args(); + throw; + } + catch (const GreenletStartedWhileInPython&) { + // The greenlet was started sometime before this + // greenlet actually switched to it, i.e., + // "concurrent" calls to switch() or throw(). + // We need to retry the switch. + // Note that the current greenlet has been reset + // to this one (or we wouldn't be running!) + continue; + } + break; + } + + target = target->parent(); + target_was_me = false; + } + // The ``this`` pointer and all other stack or register based + // variables are invalid now, at least where things succeed + // above. + // But this one, probably not so much? It's not clear if it's + // safe to throw an exception at this point. + + if (err.status < 0) { + // If we get here, either g_initialstub() + // failed, or g_switchstack() failed. Either one of those + // cases SHOULD leave us in the original greenlet with a valid + // stack. + return this->on_switchstack_or_initialstub_failure(target, err, target_was_me, was_initial_stub); + } + + // err.the_new_current_greenlet would be the same as ``target``, + // if target wasn't probably corrupt. + return err.the_new_current_greenlet->g_switch_finish(err); +} + + + +Greenlet::switchstack_result_t +UserGreenlet::g_initialstub(void* mark) +{ + OwnedObject run; + + // We need to grab a reference to the current switch arguments + // in case we're entered concurrently during the call to + // GetAttr() and have to try again. + // We'll restore them when we return in that case. + // Scope them tightly to avoid ref leaks. + { + SwitchingArgs args(this->args()); + + /* save exception in case getattr clears it */ + PyErrPieces saved; + + /* + self.run is the object to call in the new greenlet. + This could run arbitrary python code and switch greenlets! + */ + run = this->self().PyRequireAttr(mod_globs->str_run); + /* restore saved exception */ + saved.PyErrRestore(); + + + /* recheck that it's safe to switch in case greenlet reparented anywhere above */ + this->check_switch_allowed(); + + /* by the time we got here another start could happen elsewhere, + * that means it should now be a regular switch. + * This can happen if the Python code is a subclass that implements + * __getattribute__ or __getattr__, or makes ``run`` a descriptor; + * all of those can run arbitrary code that switches back into + * this greenlet. + */ + if (this->stack_state.started()) { + // the successful switch cleared these out, we need to + // restore our version. They will be copied on up to the + // next target. + assert(!this->args()); + this->args() <<= args; + throw GreenletStartedWhileInPython(); + } + } + + // Sweet, if we got here, we have the go-ahead and will switch + // greenlets. + // Nothing we do from here on out should allow for a thread or + // greenlet switch: No arbitrary calls to Python, including + // decref'ing + +#if GREENLET_USE_CFRAME + /* OK, we need it, we're about to switch greenlets, save the state. */ + /* + See green_new(). This is a stack-allocated variable used + while *self* is in PyObject_Call(). + We want to defer copying the state info until we're sure + we need it and are in a stable place to do so. + */ + _PyCFrame trace_info; + + this->python_state.set_new_cframe(trace_info); +#endif + /* start the greenlet */ + ThreadState& thread_state = GET_THREAD_STATE().state(); + this->stack_state = StackState(mark, + thread_state.borrow_current()->stack_state); + this->python_state.set_initial_state(PyThreadState_GET()); + this->exception_state.clear(); + this->_main_greenlet = thread_state.get_main_greenlet(); + + /* perform the initial switch */ + switchstack_result_t err = this->g_switchstack(); + /* returns twice! + The 1st time with ``err == 1``: we are in the new greenlet. + This one owns a greenlet that used to be current. + The 2nd time with ``err <= 0``: back in the caller's + greenlet; this happens if the child finishes or switches + explicitly to us. Either way, the ``err`` variable is + created twice at the same memory location, but possibly + having different ``origin`` values. Note that it's not + constructed for the second time until the switch actually happens. + */ + if (err.status == 1) { + // In the new greenlet. + + // This never returns! Calling inner_bootstrap steals + // the contents of our run object within this stack frame, so + // it is not valid to do anything with it. + try { + this->inner_bootstrap(err.origin_greenlet.relinquish_ownership(), + run.relinquish_ownership()); + } + // Getting a C++ exception here isn't good. It's probably a + // bug in the underlying greenlet, meaning it's probably a + // C++ extension. We're going to abort anyway, but try to + // display some nice information *if* possible. Some obscure + // platforms don't properly support this (old 32-bit Arm, see see + // https://github.com/python-greenlet/greenlet/issues/385); that's not + // great, but should usually be OK because, as mentioned above, we're + // terminating anyway. + // + // The catching is tested by + // ``test_cpp.CPPTests.test_unhandled_exception_in_greenlet_aborts``. + // + // PyErrOccurred can theoretically be thrown by + // inner_bootstrap() -> g_switch_finish(), but that should + // never make it back to here. It is a std::exception and + // would be caught if it is. + catch (const std::exception& e) { + std::string base = "greenlet: Unhandled C++ exception: "; + base += e.what(); + Py_FatalError(base.c_str()); + } + catch (...) { + // Some compilers/runtimes use exceptions internally. + // It appears that GCC on Linux with libstdc++ throws an + // exception internally at process shutdown time to unwind + // stacks and clean up resources. Depending on exactly + // where we are when the process exits, that could result + // in an unknown exception getting here. If we + // Py_FatalError() or abort() here, we interfere with + // orderly process shutdown. Throwing the exception on up + // is the right thing to do. + // + // gevent's ``examples/dns_mass_resolve.py`` demonstrates this. +#ifndef NDEBUG + fprintf(stderr, + "greenlet: inner_bootstrap threw unknown exception; " + "is the process terminating?\n"); +#endif + throw; + } + Py_FatalError("greenlet: inner_bootstrap returned with no exception.\n"); + } + + + // In contrast, notice that we're keeping the origin greenlet + // around as an owned reference; we need it to call the trace + // function for the switch back into the parent. It was only + // captured at the time the switch actually happened, though, + // so we haven't been keeping an extra reference around this + // whole time. + + /* back in the parent */ + if (err.status < 0) { + /* start failed badly, restore greenlet state */ + this->stack_state = StackState(); + this->_main_greenlet.CLEAR(); + // CAUTION: This may run arbitrary Python code. + run.CLEAR(); // inner_bootstrap didn't run, we own the reference. + } + + // In the success case, the spawned code (inner_bootstrap) will + // take care of decrefing this, so we relinquish ownership so as + // to not double-decref. + + run.relinquish_ownership(); + + return err; +} + + +void +UserGreenlet::inner_bootstrap(PyGreenlet* origin_greenlet, PyObject* run) +{ + // The arguments here would be another great place for move. + // As it is, we take them as a reference so that when we clear + // them we clear what's on the stack above us. Do that NOW, and + // without using a C++ RAII object, + // so there's no way that exiting the parent frame can clear it, + // or we clear it unexpectedly. This arises in the context of the + // interpreter shutting down. See https://github.com/python-greenlet/greenlet/issues/325 + //PyObject* run = _run.relinquish_ownership(); + + /* in the new greenlet */ + assert(this->thread_state()->borrow_current() == BorrowedGreenlet(this->_self)); + // C++ exceptions cannot propagate to the parent greenlet from + // here. (TODO: Do we need a catch(...) clause, perhaps on the + // function itself? ALl we could do is terminate the program.) + // NOTE: On 32-bit Windows, the call chain is extremely + // important here in ways that are subtle, having to do with + // the depth of the SEH list. The call to restore it MUST NOT + // add a new SEH handler to the list, or we'll restore it to + // the wrong thing. + this->thread_state()->restore_exception_state(); + /* stack variables from above are no good and also will not unwind! */ + // EXCEPT: That can't be true, we access run, among others, here. + + this->stack_state.set_active(); /* running */ + + // We're about to possibly run Python code again, which + // could switch back/away to/from us, so we need to grab the + // arguments locally. + SwitchingArgs args; + args <<= this->args(); + assert(!this->args()); + + // XXX: We could clear this much earlier, right? + // Or would that introduce the possibility of running Python + // code when we don't want to? + // CAUTION: This may run arbitrary Python code. + this->_run_callable.CLEAR(); + + + // The first switch we need to manually call the trace + // function here instead of in g_switch_finish, because we + // never return there. + if (OwnedObject tracefunc = this->thread_state()->get_tracefunc()) { + OwnedGreenlet trace_origin; + trace_origin = origin_greenlet; + try { + g_calltrace(tracefunc, + args ? mod_globs->event_switch : mod_globs->event_throw, + trace_origin, + this->_self); + } + catch (const PyErrOccurred&) { + /* Turn trace errors into switch throws */ + args.CLEAR(); + } + } + + // We no longer need the origin, it was only here for + // tracing. + // We may never actually exit this stack frame so we need + // to explicitly clear it. + // This could run Python code and switch. + Py_CLEAR(origin_greenlet); + + OwnedObject result; + if (!args) { + /* pending exception */ + result = NULL; + } + else { + /* call g.run(*args, **kwargs) */ + // This could result in further switches + try { + //result = run.PyCall(args.args(), args.kwargs()); + // CAUTION: Just invoking this, before the function even + // runs, may cause memory allocations, which may trigger + // GC, which may run arbitrary Python code. + result = OwnedObject::consuming(PyObject_Call(run, args.args().borrow(), args.kwargs().borrow())); + } + catch (...) { + // Unhandled C++ exception! + + // If we declare ourselves as noexcept, if we don't catch + // this here, most platforms will just abort() the + // process. But on 64-bit Windows with older versions of + // the C runtime, this can actually corrupt memory and + // just return. We see this when compiling with the + // Windows 7.0 SDK targeting Windows Server 2008, but not + // when using the Appveyor Visual Studio 2019 image. So + // this currently only affects Python 2.7 on Windows 64. + // That is, the tests pass and the runtime aborts + // everywhere else. + // + // However, if we catch it and try to continue with a + // Python error, then all Windows 64 bit platforms corrupt + // memory. So all we can do is manually abort, hopefully + // with a good error message. (Note that the above was + // tested WITHOUT the `/EHr` switch being used at compile + // time, so MSVC may have "optimized" out important + // checking. Using that switch, we may be in a better + // place in terms of memory corruption.) But sometimes it + // can't be caught here at all, which is confusing but not + // terribly surprising; so again, the G_NOEXCEPT_WIN32 + // plus "/EHr". + // + // Hopefully the basic C stdlib is still functional enough + // for us to at least print an error. + // + // It gets more complicated than that, though, on some + // platforms, specifically at least Linux/gcc/libstdc++. They use + // an exception to unwind the stack when a background + // thread exits. (See comments about noexcept.) So this + // may not actually represent anything untoward. On those + // platforms we allow throws of this to propagate, or + // attempt to anyway. +# if defined(WIN32) || defined(_WIN32) + Py_FatalError( + "greenlet: Unhandled C++ exception from a greenlet run function. " + "Because memory is likely corrupted, terminating process."); + std::abort(); +#else + throw; +#endif + } + } + // These lines may run arbitrary code + args.CLEAR(); + Py_CLEAR(run); + + if (!result + && mod_globs->PyExc_GreenletExit.PyExceptionMatches() + && (this->args())) { + // This can happen, for example, if our only reference + // goes away after we switch back to the parent. + // See test_dealloc_switch_args_not_lost + PyErrPieces clear_error; + result <<= this->args(); + result = single_result(result); + } + this->release_args(); + this->python_state.did_finish(PyThreadState_GET()); + + result = g_handle_exit(result); + assert(this->thread_state()->borrow_current() == this->_self); + + /* jump back to parent */ + this->stack_state.set_inactive(); /* dead */ + + + // TODO: Can we decref some things here? Release our main greenlet + // and maybe parent? + for (Greenlet* parent = this->_parent; + parent; + parent = parent->parent()) { + // We need to somewhere consume a reference to + // the result; in most cases we'll never have control + // back in this stack frame again. Calling + // green_switch actually adds another reference! + // This would probably be clearer with a specific API + // to hand results to the parent. + parent->args() <<= result; + assert(!result); + // The parent greenlet now owns the result; in the + // typical case we'll never get back here to assign to + // result and thus release the reference. + try { + result = parent->g_switch(); + } + catch (const PyErrOccurred&) { + // Ignore, keep passing the error on up. + } + + /* Return here means switch to parent failed, + * in which case we throw *current* exception + * to the next parent in chain. + */ + assert(!result); + } + /* We ran out of parents, cannot continue */ + PyErr_WriteUnraisable(this->self().borrow_o()); + Py_FatalError("greenlet: ran out of parent greenlets while propagating exception; " + "cannot continue"); + std::abort(); +} + +void +UserGreenlet::run(const BorrowedObject nrun) +{ + if (this->started()) { + throw AttributeError( + "run cannot be set " + "after the start of the greenlet"); + } + this->_run_callable = nrun; +} + +const OwnedGreenlet +UserGreenlet::parent() const +{ + return this->_parent; +} + +void +UserGreenlet::parent(const BorrowedObject raw_new_parent) +{ + if (!raw_new_parent) { + throw AttributeError("can't delete attribute"); + } + + BorrowedMainGreenlet main_greenlet_of_new_parent; + BorrowedGreenlet new_parent(raw_new_parent.borrow()); // could + // throw + // TypeError! + for (BorrowedGreenlet p = new_parent; p; p = p->parent()) { + if (p == this->self()) { + throw ValueError("cyclic parent chain"); + } + main_greenlet_of_new_parent = p->main_greenlet(); + } + + if (!main_greenlet_of_new_parent) { + throw ValueError("parent must not be garbage collected"); + } + + if (this->started() + && this->_main_greenlet != main_greenlet_of_new_parent) { + throw ValueError("parent cannot be on a different thread"); + } + + this->_parent = new_parent; +} + +void +UserGreenlet::murder_in_place() +{ + this->_main_greenlet.CLEAR(); + Greenlet::murder_in_place(); +} + +bool +UserGreenlet::belongs_to_thread(const ThreadState* thread_state) const +{ + return Greenlet::belongs_to_thread(thread_state) && this->_main_greenlet == thread_state->borrow_main_greenlet(); +} + + +int +UserGreenlet::tp_traverse(visitproc visit, void* arg) +{ + Py_VISIT(this->_parent.borrow_o()); + Py_VISIT(this->_main_greenlet.borrow_o()); + Py_VISIT(this->_run_callable.borrow_o()); + + return Greenlet::tp_traverse(visit, arg); +} + +int +UserGreenlet::tp_clear() +{ + Greenlet::tp_clear(); + this->_parent.CLEAR(); + this->_main_greenlet.CLEAR(); + this->_run_callable.CLEAR(); + return 0; +} + +UserGreenlet::ParentIsCurrentGuard::ParentIsCurrentGuard(UserGreenlet* p, + const ThreadState& thread_state) + : oldparent(p->_parent), + greenlet(p) +{ + p->_parent = thread_state.get_current(); +} + +UserGreenlet::ParentIsCurrentGuard::~ParentIsCurrentGuard() +{ + this->greenlet->_parent = oldparent; + oldparent.CLEAR(); +} + +}; //namespace greenlet +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/__init__.py b/python_embeded/Lib/site-packages/greenlet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91f075a2d5db15f9c48be888722f5254eb67370a --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/__init__.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +""" +The root of the greenlet package. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +__all__ = [ + '__version__', + '_C_API', + + 'GreenletExit', + 'error', + + 'getcurrent', + 'greenlet', + + 'gettrace', + 'settrace', +] + +# pylint:disable=no-name-in-module + +### +# Metadata +### +__version__ = '3.2.3' +from ._greenlet import _C_API # pylint:disable=no-name-in-module + +### +# Exceptions +### +from ._greenlet import GreenletExit +from ._greenlet import error + +### +# greenlets +### +from ._greenlet import getcurrent +from ._greenlet import greenlet + +### +# tracing +### +try: + from ._greenlet import gettrace + from ._greenlet import settrace +except ImportError: + # Tracing wasn't supported. + # XXX: The option to disable it was removed in 1.0, + # so this branch should be dead code. + pass + +### +# Constants +# These constants aren't documented and aren't recommended. +# In 1.0, USE_GC and USE_TRACING are always true, and USE_CONTEXT_VARS +# is the same as ``sys.version_info[:2] >= 3.7`` +### +from ._greenlet import GREENLET_USE_CONTEXT_VARS # pylint:disable=unused-import +from ._greenlet import GREENLET_USE_GC # pylint:disable=unused-import +from ._greenlet import GREENLET_USE_TRACING # pylint:disable=unused-import + +# Controlling the use of the gc module. Provisional API for this greenlet +# implementation in 2.0. +from ._greenlet import CLOCKS_PER_SEC # pylint:disable=unused-import +from ._greenlet import enable_optional_cleanup # pylint:disable=unused-import +from ._greenlet import get_clocks_used_doing_optional_cleanup # pylint:disable=unused-import + +# Other APIS in the _greenlet module are for test support. diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet.cpp b/python_embeded/Lib/site-packages/greenlet/greenlet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8d92a00bb961e930141e5c3cd8f682dbd667751 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet.cpp @@ -0,0 +1,320 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +/* Format with: + * clang-format -i --style=file src/greenlet/greenlet.c + * + * + * Fix missing braces with: + * clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements" +*/ +#include +#include +#include +#include + + +#define PY_SSIZE_T_CLEAN +#include +#include "structmember.h" // PyMemberDef + +#include "greenlet_internal.hpp" +// Code after this point can assume access to things declared in stdint.h, +// including the fixed-width types. This goes for the platform-specific switch functions +// as well. +#include "greenlet_refs.hpp" +#include "greenlet_slp_switch.hpp" + +#include "greenlet_thread_support.hpp" +#include "TGreenlet.hpp" + +#include "TGreenletGlobals.cpp" + +#include "TGreenlet.cpp" +#include "TMainGreenlet.cpp" +#include "TUserGreenlet.cpp" +#include "TBrokenGreenlet.cpp" +#include "TExceptionState.cpp" +#include "TPythonState.cpp" +#include "TStackState.cpp" + +#include "TThreadState.hpp" +#include "TThreadStateCreator.hpp" +#include "TThreadStateDestroy.cpp" + +#include "PyGreenlet.cpp" +#include "PyGreenletUnswitchable.cpp" +#include "CObjects.cpp" + +using greenlet::LockGuard; +using greenlet::LockInitError; +using greenlet::PyErrOccurred; +using greenlet::Require; + +using greenlet::g_handle_exit; +using greenlet::single_result; + +using greenlet::Greenlet; +using greenlet::UserGreenlet; +using greenlet::MainGreenlet; +using greenlet::BrokenGreenlet; +using greenlet::ThreadState; +using greenlet::PythonState; + + + +// ******* Implementation of things from included files +template +greenlet::refs::_BorrowedGreenlet& greenlet::refs::_BorrowedGreenlet::operator=(const greenlet::refs::BorrowedObject& other) +{ + this->_set_raw_pointer(static_cast(other)); + return *this; +} + +template +inline greenlet::refs::_BorrowedGreenlet::operator Greenlet*() const noexcept +{ + if (!this->p) { + return nullptr; + } + return reinterpret_cast(this->p)->pimpl; +} + +template +greenlet::refs::_BorrowedGreenlet::_BorrowedGreenlet(const BorrowedObject& p) + : BorrowedReference(nullptr) +{ + + this->_set_raw_pointer(p.borrow()); +} + +template +inline greenlet::refs::_OwnedGreenlet::operator Greenlet*() const noexcept +{ + if (!this->p) { + return nullptr; + } + return reinterpret_cast(this->p)->pimpl; +} + + + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wmissing-field-initializers" +# pragma clang diagnostic ignored "-Wwritable-strings" +#elif defined(__GNUC__) +# pragma GCC diagnostic push +// warning: ISO C++ forbids converting a string constant to ‘char*’ +// (The python APIs aren't const correct and accept writable char*) +# pragma GCC diagnostic ignored "-Wwrite-strings" +#endif + + +/*********************************************************** + +A PyGreenlet is a range of C stack addresses that must be +saved and restored in such a way that the full range of the +stack contains valid data when we switch to it. + +Stack layout for a greenlet: + + | ^^^ | + | older data | + | | + stack_stop . |_______________| + . | | + . | greenlet data | + . | in stack | + . * |_______________| . . _____________ stack_copy + stack_saved + . | | | | + . | data | |greenlet data| + . | unrelated | | saved | + . | to | | in heap | + stack_start . | this | . . |_____________| stack_copy + | greenlet | + | | + | newer data | + | vvv | + + +Note that a greenlet's stack data is typically partly at its correct +place in the stack, and partly saved away in the heap, but always in +the above configuration: two blocks, the more recent one in the heap +and the older one still in the stack (either block may be empty). + +Greenlets are chained: each points to the previous greenlet, which is +the one that owns the data currently in the C stack above my +stack_stop. The currently running greenlet is the first element of +this chain. The main (initial) greenlet is the last one. Greenlets +whose stack is entirely in the heap can be skipped from the chain. + +The chain is not related to execution order, but only to the order +in which bits of C stack happen to belong to greenlets at a particular +point in time. + +The main greenlet doesn't have a stack_stop: it is responsible for the +complete rest of the C stack, and we don't know where it begins. We +use (char*) -1, the largest possible address. + +States: + stack_stop == NULL && stack_start == NULL: did not start yet + stack_stop != NULL && stack_start == NULL: already finished + stack_stop != NULL && stack_start != NULL: active + +The running greenlet's stack_start is undefined but not NULL. + + ***********************************************************/ + + + + +/***********************************************************/ + +/* Some functions must not be inlined: + * slp_restore_state, when inlined into slp_switch might cause + it to restore stack over its own local variables + * slp_save_state, when inlined would add its own local + variables to the saved stack, wasting space + * slp_switch, cannot be inlined for obvious reasons + * g_initialstub, when inlined would receive a pointer into its + own stack frame, leading to incomplete stack save/restore + +g_initialstub is a member function and declared virtual so that the +compiler always calls it through a vtable. + +slp_save_state and slp_restore_state are also member functions. They +are called from trampoline functions that themselves are declared as +not eligible for inlining. +*/ + +extern "C" { +static int GREENLET_NOINLINE(slp_save_state_trampoline)(char* stackref) +{ + return switching_thread_state->slp_save_state(stackref); +} +static void GREENLET_NOINLINE(slp_restore_state_trampoline)() +{ + switching_thread_state->slp_restore_state(); +} +} + + +/***********************************************************/ + + +#include "PyModule.cpp" + + + +static PyObject* +greenlet_internal_mod_init() noexcept +{ + static void* _PyGreenlet_API[PyGreenlet_API_pointers]; + + try { + CreatedModule m(greenlet_module_def); + + Require(PyType_Ready(&PyGreenlet_Type)); + Require(PyType_Ready(&PyGreenletUnswitchable_Type)); + + mod_globs = new greenlet::GreenletGlobals; + ThreadState::init(); + + m.PyAddObject("greenlet", PyGreenlet_Type); + m.PyAddObject("UnswitchableGreenlet", PyGreenletUnswitchable_Type); + m.PyAddObject("error", mod_globs->PyExc_GreenletError); + m.PyAddObject("GreenletExit", mod_globs->PyExc_GreenletExit); + + m.PyAddObject("GREENLET_USE_GC", 1); + m.PyAddObject("GREENLET_USE_TRACING", 1); + m.PyAddObject("GREENLET_USE_CONTEXT_VARS", 1L); + m.PyAddObject("GREENLET_USE_STANDARD_THREADING", 1L); + + OwnedObject clocks_per_sec = OwnedObject::consuming(PyLong_FromSsize_t(CLOCKS_PER_SEC)); + m.PyAddObject("CLOCKS_PER_SEC", clocks_per_sec); + + /* also publish module-level data as attributes of the greentype. */ + // XXX: This is weird, and enables a strange pattern of + // confusing the class greenlet with the module greenlet; with + // the exception of (possibly) ``getcurrent()``, this + // shouldn't be encouraged so don't add new items here. + for (const char* const* p = copy_on_greentype; *p; p++) { + OwnedObject o = m.PyRequireAttr(*p); + PyDict_SetItemString(PyGreenlet_Type.tp_dict, *p, o.borrow()); + } + + /* + * Expose C API + */ + + /* types */ + _PyGreenlet_API[PyGreenlet_Type_NUM] = (void*)&PyGreenlet_Type; + + /* exceptions */ + _PyGreenlet_API[PyExc_GreenletError_NUM] = (void*)mod_globs->PyExc_GreenletError; + _PyGreenlet_API[PyExc_GreenletExit_NUM] = (void*)mod_globs->PyExc_GreenletExit; + + /* methods */ + _PyGreenlet_API[PyGreenlet_New_NUM] = (void*)PyGreenlet_New; + _PyGreenlet_API[PyGreenlet_GetCurrent_NUM] = (void*)PyGreenlet_GetCurrent; + _PyGreenlet_API[PyGreenlet_Throw_NUM] = (void*)PyGreenlet_Throw; + _PyGreenlet_API[PyGreenlet_Switch_NUM] = (void*)PyGreenlet_Switch; + _PyGreenlet_API[PyGreenlet_SetParent_NUM] = (void*)PyGreenlet_SetParent; + + /* Previously macros, but now need to be functions externally. */ + _PyGreenlet_API[PyGreenlet_MAIN_NUM] = (void*)Extern_PyGreenlet_MAIN; + _PyGreenlet_API[PyGreenlet_STARTED_NUM] = (void*)Extern_PyGreenlet_STARTED; + _PyGreenlet_API[PyGreenlet_ACTIVE_NUM] = (void*)Extern_PyGreenlet_ACTIVE; + _PyGreenlet_API[PyGreenlet_GET_PARENT_NUM] = (void*)Extern_PyGreenlet_GET_PARENT; + + /* XXX: Note that our module name is ``greenlet._greenlet``, but for + backwards compatibility with existing C code, we need the _C_API to + be directly in greenlet. + */ + const NewReference c_api_object(Require( + PyCapsule_New( + (void*)_PyGreenlet_API, + "greenlet._C_API", + NULL))); + m.PyAddObject("_C_API", c_api_object); + assert(c_api_object.REFCNT() == 2); + + // cerr << "Sizes:" + // << "\n\tGreenlet : " << sizeof(Greenlet) + // << "\n\tUserGreenlet : " << sizeof(UserGreenlet) + // << "\n\tMainGreenlet : " << sizeof(MainGreenlet) + // << "\n\tExceptionState : " << sizeof(greenlet::ExceptionState) + // << "\n\tPythonState : " << sizeof(greenlet::PythonState) + // << "\n\tStackState : " << sizeof(greenlet::StackState) + // << "\n\tSwitchingArgs : " << sizeof(greenlet::SwitchingArgs) + // << "\n\tOwnedObject : " << sizeof(greenlet::refs::OwnedObject) + // << "\n\tBorrowedObject : " << sizeof(greenlet::refs::BorrowedObject) + // << "\n\tPyGreenlet : " << sizeof(PyGreenlet) + // << endl; + + return m.borrow(); // But really it's the main reference. + } + catch (const LockInitError& e) { + PyErr_SetString(PyExc_MemoryError, e.what()); + return NULL; + } + catch (const PyErrOccurred&) { + return NULL; + } + +} + +extern "C" { + +PyMODINIT_FUNC +PyInit__greenlet(void) +{ + return greenlet_internal_mod_init(); +} + +}; // extern C + +#ifdef __clang__ +# pragma clang diagnostic pop +#elif defined(__GNUC__) +# pragma GCC diagnostic pop +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet.h b/python_embeded/Lib/site-packages/greenlet/greenlet.h new file mode 100644 index 0000000000000000000000000000000000000000..d02a16e43426fb1c1bb286f1cda463cb9b1185ad --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet.h @@ -0,0 +1,164 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ + +/* Greenlet object interface */ + +#ifndef Py_GREENLETOBJECT_H +#define Py_GREENLETOBJECT_H + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* This is deprecated and undocumented. It does not change. */ +#define GREENLET_VERSION "1.0.0" + +#ifndef GREENLET_MODULE +#define implementation_ptr_t void* +#endif + +typedef struct _greenlet { + PyObject_HEAD + PyObject* weakreflist; + PyObject* dict; + implementation_ptr_t pimpl; +} PyGreenlet; + +#define PyGreenlet_Check(op) (op && PyObject_TypeCheck(op, &PyGreenlet_Type)) + + +/* C API functions */ + +/* Total number of symbols that are exported */ +#define PyGreenlet_API_pointers 12 + +#define PyGreenlet_Type_NUM 0 +#define PyExc_GreenletError_NUM 1 +#define PyExc_GreenletExit_NUM 2 + +#define PyGreenlet_New_NUM 3 +#define PyGreenlet_GetCurrent_NUM 4 +#define PyGreenlet_Throw_NUM 5 +#define PyGreenlet_Switch_NUM 6 +#define PyGreenlet_SetParent_NUM 7 + +#define PyGreenlet_MAIN_NUM 8 +#define PyGreenlet_STARTED_NUM 9 +#define PyGreenlet_ACTIVE_NUM 10 +#define PyGreenlet_GET_PARENT_NUM 11 + +#ifndef GREENLET_MODULE +/* This section is used by modules that uses the greenlet C API */ +static void** _PyGreenlet_API = NULL; + +# define PyGreenlet_Type \ + (*(PyTypeObject*)_PyGreenlet_API[PyGreenlet_Type_NUM]) + +# define PyExc_GreenletError \ + ((PyObject*)_PyGreenlet_API[PyExc_GreenletError_NUM]) + +# define PyExc_GreenletExit \ + ((PyObject*)_PyGreenlet_API[PyExc_GreenletExit_NUM]) + +/* + * PyGreenlet_New(PyObject *args) + * + * greenlet.greenlet(run, parent=None) + */ +# define PyGreenlet_New \ + (*(PyGreenlet * (*)(PyObject * run, PyGreenlet * parent)) \ + _PyGreenlet_API[PyGreenlet_New_NUM]) + +/* + * PyGreenlet_GetCurrent(void) + * + * greenlet.getcurrent() + */ +# define PyGreenlet_GetCurrent \ + (*(PyGreenlet * (*)(void)) _PyGreenlet_API[PyGreenlet_GetCurrent_NUM]) + +/* + * PyGreenlet_Throw( + * PyGreenlet *greenlet, + * PyObject *typ, + * PyObject *val, + * PyObject *tb) + * + * g.throw(...) + */ +# define PyGreenlet_Throw \ + (*(PyObject * (*)(PyGreenlet * self, \ + PyObject * typ, \ + PyObject * val, \ + PyObject * tb)) \ + _PyGreenlet_API[PyGreenlet_Throw_NUM]) + +/* + * PyGreenlet_Switch(PyGreenlet *greenlet, PyObject *args) + * + * g.switch(*args, **kwargs) + */ +# define PyGreenlet_Switch \ + (*(PyObject * \ + (*)(PyGreenlet * greenlet, PyObject * args, PyObject * kwargs)) \ + _PyGreenlet_API[PyGreenlet_Switch_NUM]) + +/* + * PyGreenlet_SetParent(PyObject *greenlet, PyObject *new_parent) + * + * g.parent = new_parent + */ +# define PyGreenlet_SetParent \ + (*(int (*)(PyGreenlet * greenlet, PyGreenlet * nparent)) \ + _PyGreenlet_API[PyGreenlet_SetParent_NUM]) + +/* + * PyGreenlet_GetParent(PyObject* greenlet) + * + * return greenlet.parent; + * + * This could return NULL even if there is no exception active. + * If it does not return NULL, you are responsible for decrementing the + * reference count. + */ +# define PyGreenlet_GetParent \ + (*(PyGreenlet* (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_GET_PARENT_NUM]) + +/* + * deprecated, undocumented alias. + */ +# define PyGreenlet_GET_PARENT PyGreenlet_GetParent + +# define PyGreenlet_MAIN \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_MAIN_NUM]) + +# define PyGreenlet_STARTED \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_STARTED_NUM]) + +# define PyGreenlet_ACTIVE \ + (*(int (*)(PyGreenlet*)) \ + _PyGreenlet_API[PyGreenlet_ACTIVE_NUM]) + + + + +/* Macro that imports greenlet and initializes C API */ +/* NOTE: This has actually moved to ``greenlet._greenlet._C_API``, but we + keep the older definition to be sure older code that might have a copy of + the header still works. */ +# define PyGreenlet_Import() \ + { \ + _PyGreenlet_API = (void**)PyCapsule_Import("greenlet._C_API", 0); \ + } + +#endif /* GREENLET_MODULE */ + +#ifdef __cplusplus +} +#endif +#endif /* !Py_GREENLETOBJECT_H */ diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_allocator.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_allocator.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b452f5444262fb3553bee15c4692e06d7fac549c --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_allocator.hpp @@ -0,0 +1,63 @@ +#ifndef GREENLET_ALLOCATOR_HPP +#define GREENLET_ALLOCATOR_HPP + +#define PY_SSIZE_T_CLEAN +#include +#include +#include "greenlet_compiler_compat.hpp" + + +namespace greenlet +{ + // This allocator is stateless; all instances are identical. + // It can *ONLY* be used when we're sure we're holding the GIL + // (Python's allocators require the GIL). + template + struct PythonAllocator : public std::allocator { + + PythonAllocator(const PythonAllocator& UNUSED(other)) + : std::allocator() + { + } + + PythonAllocator(const std::allocator other) + : std::allocator(other) + {} + + template + PythonAllocator(const std::allocator& other) + : std::allocator(other) + { + } + + PythonAllocator() : std::allocator() {} + + T* allocate(size_t number_objects, const void* UNUSED(hint)=0) + { + void* p; + if (number_objects == 1) + p = PyObject_Malloc(sizeof(T)); + else + p = PyMem_Malloc(sizeof(T) * number_objects); + return static_cast(p); + } + + void deallocate(T* t, size_t n) + { + void* p = t; + if (n == 1) { + PyObject_Free(p); + } + else + PyMem_Free(p); + } + // This member is deprecated in C++17 and removed in C++20 + template< class U > + struct rebind { + typedef PythonAllocator other; + }; + + }; +} + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_compiler_compat.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_compiler_compat.hpp new file mode 100644 index 0000000000000000000000000000000000000000..af24bd83e1f2c5c89c5e17b973402a1153514a05 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_compiler_compat.hpp @@ -0,0 +1,98 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef GREENLET_COMPILER_COMPAT_HPP +#define GREENLET_COMPILER_COMPAT_HPP + +/** + * Definitions to aid with compatibility with different compilers. + * + * .. caution:: Use extreme care with noexcept. + * Some compilers and runtimes, specifically gcc/libgcc/libstdc++ on + * Linux, implement stack unwinding by throwing an uncatchable + * exception, one that specifically does not appear to be an active + * exception to the rest of the runtime. If this happens while we're in a noexcept function, + * we have violated our dynamic exception contract, and so the runtime + * will call std::terminate(), which kills the process with the + * unhelpful message "terminate called without an active exception". + * + * This has happened in this scenario: A background thread is running + * a greenlet that has made a native call and released the GIL. + * Meanwhile, the main thread finishes and starts shutting down the + * interpreter. When the background thread is scheduled again and + * attempts to obtain the GIL, it notices that the interpreter is + * exiting and calls ``pthread_exit()``. This in turn starts to unwind + * the stack by throwing that exception. But we had the ``PyCall`` + * functions annotated as noexcept, so the runtime terminated us. + * + * #2 0x00007fab26fec2b7 in std::terminate() () from /lib/x86_64-linux-gnu/libstdc++.so.6 + * #3 0x00007fab26febb3c in __gxx_personality_v0 () from /lib/x86_64-linux-gnu/libstdc++.so.6 + * #4 0x00007fab26f34de6 in ?? () from /lib/x86_64-linux-gnu/libgcc_s.so.1 + * #6 0x00007fab276a34c6 in __GI___pthread_unwind at ./nptl/unwind.c:130 + * #7 0x00007fab2769bd3a in __do_cancel () at ../sysdeps/nptl/pthreadP.h:280 + * #8 __GI___pthread_exit (value=value@entry=0x0) at ./nptl/pthread_exit.c:36 + * #9 0x000000000052e567 in PyThread_exit_thread () at ../Python/thread_pthread.h:370 + * #10 0x00000000004d60b5 in take_gil at ../Python/ceval_gil.h:224 + * #11 0x00000000004d65f9 in PyEval_RestoreThread at ../Python/ceval.c:467 + * #12 0x000000000060cce3 in setipaddr at ../Modules/socketmodule.c:1203 + * #13 0x00000000006101cd in socket_gethostbyname + */ + +#include + +# define G_NO_COPIES_OF_CLS(Cls) private: \ + Cls(const Cls& other) = delete; \ + Cls& operator=(const Cls& other) = delete + +# define G_NO_ASSIGNMENT_OF_CLS(Cls) private: \ + Cls& operator=(const Cls& other) = delete + +# define G_NO_COPY_CONSTRUCTOR_OF_CLS(Cls) private: \ + Cls(const Cls& other) = delete; + + +// CAUTION: MSVC is stupidly picky: +// +// "The compiler ignores, without warning, any __declspec keywords +// placed after * or & and in front of the variable identifier in a +// declaration." +// (https://docs.microsoft.com/en-us/cpp/cpp/declspec?view=msvc-160) +// +// So pointer return types must be handled differently (because of the +// trailing *), or you get inscrutable compiler warnings like "error +// C2059: syntax error: ''" +// +// In C++ 11, there is a standard syntax for attributes, and +// GCC defines an attribute to use with this: [[gnu:noinline]]. +// In the future, this is expected to become standard. + +#if defined(__GNUC__) || defined(__clang__) +/* We used to check for GCC 4+ or 3.4+, but those compilers are + laughably out of date. Just assume they support it. */ +# define GREENLET_NOINLINE(name) __attribute__((noinline)) name +# define GREENLET_NOINLINE_P(rtype, name) rtype __attribute__((noinline)) name +# define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) +#elif defined(_MSC_VER) +/* We used to check for && (_MSC_VER >= 1300) but that's also out of date. */ +# define GREENLET_NOINLINE(name) __declspec(noinline) name +# define GREENLET_NOINLINE_P(rtype, name) __declspec(noinline) rtype name +# define UNUSED(x) UNUSED_ ## x +#endif + +#if defined(_MSC_VER) +# define G_NOEXCEPT_WIN32 noexcept +#else +# define G_NOEXCEPT_WIN32 +#endif + +#if defined(__GNUC__) && defined(__POWERPC__) && defined(__APPLE__) +// 32-bit PPC/MacOSX. Only known to be tested on unreleased versions +// of macOS 10.6 using a macports build gcc 14. It appears that +// running C++ destructors of thread-local variables is broken. + +// See https://github.com/python-greenlet/greenlet/pull/419 +# define GREENLET_BROKEN_THREAD_LOCAL_CLEANUP_JUST_LEAK 1 +#else +# define GREENLET_BROKEN_THREAD_LOCAL_CLEANUP_JUST_LEAK 0 +#endif + + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_cpython_compat.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_cpython_compat.hpp new file mode 100644 index 0000000000000000000000000000000000000000..979d6f94a01e6c965094dc793e1a95de2671250e --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_cpython_compat.hpp @@ -0,0 +1,148 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef GREENLET_CPYTHON_COMPAT_H +#define GREENLET_CPYTHON_COMPAT_H + +/** + * Helpers for compatibility with multiple versions of CPython. + */ + +#define PY_SSIZE_T_CLEAN +#include "Python.h" + + +#if PY_VERSION_HEX >= 0x30A00B1 +# define GREENLET_PY310 1 +#else +# define GREENLET_PY310 0 +#endif + +/* +Python 3.10 beta 1 changed tstate->use_tracing to a nested cframe member. +See https://github.com/python/cpython/pull/25276 +We have to save and restore this as well. + +Python 3.13 removed PyThreadState.cframe (GH-108035). +*/ +#if GREENLET_PY310 && PY_VERSION_HEX < 0x30D0000 +# define GREENLET_USE_CFRAME 1 +#else +# define GREENLET_USE_CFRAME 0 +#endif + + +#if PY_VERSION_HEX >= 0x30B00A4 +/* +Greenlet won't compile on anything older than Python 3.11 alpha 4 (see +https://bugs.python.org/issue46090). Summary of breaking internal changes: +- Python 3.11 alpha 1 changed how frame objects are represented internally. + - https://github.com/python/cpython/pull/30122 +- Python 3.11 alpha 3 changed how recursion limits are stored. + - https://github.com/python/cpython/pull/29524 +- Python 3.11 alpha 4 changed how exception state is stored. It also includes a + change to help greenlet save and restore the interpreter frame "data stack". + - https://github.com/python/cpython/pull/30122 + - https://github.com/python/cpython/pull/30234 +*/ +# define GREENLET_PY311 1 +#else +# define GREENLET_PY311 0 +#endif + + +#if PY_VERSION_HEX >= 0x30C0000 +# define GREENLET_PY312 1 +#else +# define GREENLET_PY312 0 +#endif + +#if PY_VERSION_HEX >= 0x30D0000 +# define GREENLET_PY313 1 +#else +# define GREENLET_PY313 0 +#endif + +#if PY_VERSION_HEX >= 0x30E0000 +# define GREENLET_PY314 1 +#else +# define GREENLET_PY314 0 +#endif + +#ifndef Py_SET_REFCNT +/* Py_REFCNT and Py_SIZE macros are converted to functions +https://bugs.python.org/issue39573 */ +# define Py_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) +#endif + +#ifndef _Py_DEC_REFTOTAL +/* _Py_DEC_REFTOTAL macro has been removed from Python 3.9 by: + https://github.com/python/cpython/commit/49932fec62c616ec88da52642339d83ae719e924 + + The symbol we use to replace it was removed by at least 3.12. +*/ +# ifdef Py_REF_DEBUG +# if GREENLET_PY312 +# define _Py_DEC_REFTOTAL +# else +# define _Py_DEC_REFTOTAL _Py_RefTotal-- +# endif +# else +# define _Py_DEC_REFTOTAL +# endif +#endif +// Define these flags like Cython does if we're on an old version. +#ifndef Py_TPFLAGS_CHECKTYPES + #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX + #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER + #define Py_TPFLAGS_HAVE_NEWBUFFER 0 +#endif + +#ifndef Py_TPFLAGS_HAVE_VERSION_TAG + #define Py_TPFLAGS_HAVE_VERSION_TAG 0 +#endif + +#define G_TPFLAGS_DEFAULT Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_VERSION_TAG | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_HAVE_GC + + +#if PY_VERSION_HEX < 0x03090000 +// The official version only became available in 3.9 +# define PyObject_GC_IsTracked(o) _PyObject_GC_IS_TRACKED(o) +#endif + + +// bpo-43760 added PyThreadState_EnterTracing() to Python 3.11.0a2 +#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) +static inline void PyThreadState_EnterTracing(PyThreadState *tstate) +{ + tstate->tracing++; +#if PY_VERSION_HEX >= 0x030A00A1 + tstate->cframe->use_tracing = 0; +#else + tstate->use_tracing = 0; +#endif +} +#endif + +// bpo-43760 added PyThreadState_LeaveTracing() to Python 3.11.0a2 +#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION) +static inline void PyThreadState_LeaveTracing(PyThreadState *tstate) +{ + tstate->tracing--; + int use_tracing = (tstate->c_tracefunc != NULL + || tstate->c_profilefunc != NULL); +#if PY_VERSION_HEX >= 0x030A00A1 + tstate->cframe->use_tracing = use_tracing; +#else + tstate->use_tracing = use_tracing; +#endif +} +#endif + +#if !defined(Py_C_RECURSION_LIMIT) && defined(C_RECURSION_LIMIT) +# define Py_C_RECURSION_LIMIT C_RECURSION_LIMIT +#endif + +#endif /* GREENLET_CPYTHON_COMPAT_H */ diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_exceptions.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_exceptions.hpp new file mode 100644 index 0000000000000000000000000000000000000000..617f07c2faa372508ea99f383233709443653a5d --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_exceptions.hpp @@ -0,0 +1,171 @@ +#ifndef GREENLET_EXCEPTIONS_HPP +#define GREENLET_EXCEPTIONS_HPP + +#define PY_SSIZE_T_CLEAN +#include +#include +#include + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +#endif + +namespace greenlet { + + class PyErrOccurred : public std::runtime_error + { + public: + + // CAUTION: In debug builds, may run arbitrary Python code. + static const PyErrOccurred + from_current() + { + assert(PyErr_Occurred()); +#ifndef NDEBUG + // This is not exception safe, and + // not necessarily safe in general (what if it switches?) + // But we only do this in debug mode, where we are in + // tight control of what exceptions are getting raised and + // can prevent those issues. + + // You can't call PyObject_Str with a pending exception. + PyObject* typ; + PyObject* val; + PyObject* tb; + + PyErr_Fetch(&typ, &val, &tb); + PyObject* typs = PyObject_Str(typ); + PyObject* vals = PyObject_Str(val ? val : typ); + const char* typ_msg = PyUnicode_AsUTF8(typs); + const char* val_msg = PyUnicode_AsUTF8(vals); + PyErr_Restore(typ, val, tb); + + std::string msg(typ_msg); + msg += ": "; + msg += val_msg; + PyErrOccurred ex(msg); + Py_XDECREF(typs); + Py_XDECREF(vals); + + return ex; +#else + return PyErrOccurred(); +#endif + } + + PyErrOccurred() : std::runtime_error("") + { + assert(PyErr_Occurred()); + } + + PyErrOccurred(const std::string& msg) : std::runtime_error(msg) + { + assert(PyErr_Occurred()); + } + + PyErrOccurred(PyObject* exc_kind, const char* const msg) + : std::runtime_error(msg) + { + PyErr_SetString(exc_kind, msg); + } + + PyErrOccurred(PyObject* exc_kind, const std::string msg) + : std::runtime_error(msg) + { + // This copies the c_str, so we don't have any lifetime + // issues to worry about. + PyErr_SetString(exc_kind, msg.c_str()); + } + + PyErrOccurred(PyObject* exc_kind, + const std::string msg, //This is the format + //string; that's not + //usually safe! + + PyObject* borrowed_obj_one, PyObject* borrowed_obj_two) + : std::runtime_error(msg) + { + + //This is designed specifically for the + //``check_switch_allowed`` function. + + // PyObject_Str and PyObject_Repr are safe to call with + // NULL pointers; they return the string "" in that + // case. + // This function always returns null. + PyErr_Format(exc_kind, + msg.c_str(), + borrowed_obj_one, borrowed_obj_two); + } + }; + + class TypeError : public PyErrOccurred + { + public: + TypeError(const char* const what) + : PyErrOccurred(PyExc_TypeError, what) + { + } + TypeError(const std::string what) + : PyErrOccurred(PyExc_TypeError, what) + { + } + }; + + class ValueError : public PyErrOccurred + { + public: + ValueError(const char* const what) + : PyErrOccurred(PyExc_ValueError, what) + { + } + }; + + class AttributeError : public PyErrOccurred + { + public: + AttributeError(const char* const what) + : PyErrOccurred(PyExc_AttributeError, what) + { + } + }; + + /** + * Calls `Py_FatalError` when constructed, so you can't actually + * throw this. It just makes static analysis easier. + */ + class PyFatalError : public std::runtime_error + { + public: + PyFatalError(const char* const msg) + : std::runtime_error(msg) + { + Py_FatalError(msg); + } + }; + + static inline PyObject* + Require(PyObject* p, const std::string& msg="") + { + if (!p) { + throw PyErrOccurred(msg); + } + return p; + }; + + static inline void + Require(const int retval) + { + if (retval < 0) { + throw PyErrOccurred(); + } + }; + + +}; +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_internal.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_internal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f2b15d5fa3f8cc240f8fff066bc2338559e9cc60 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_internal.hpp @@ -0,0 +1,107 @@ +/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */ +#ifndef GREENLET_INTERNAL_H +#define GREENLET_INTERNAL_H +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wunused-function" +#endif + +/** + * Implementation helpers. + * + * C++ templates and inline functions should go here. + */ +#define PY_SSIZE_T_CLEAN +#include "greenlet_compiler_compat.hpp" +#include "greenlet_cpython_compat.hpp" +#include "greenlet_exceptions.hpp" +#include "TGreenlet.hpp" +#include "greenlet_allocator.hpp" + +#include +#include + +#define GREENLET_MODULE +struct _greenlet; +typedef struct _greenlet PyGreenlet; +namespace greenlet { + + class ThreadState; + // We can't use the PythonAllocator for this, because we push to it + // from the thread state destructor, which doesn't have the GIL, + // and Python's allocators can only be called with the GIL. + typedef std::vector cleanup_queue_t; + +}; + + +#define implementation_ptr_t greenlet::Greenlet* + + +#include "greenlet.h" + +void +greenlet::refs::MainGreenletExactChecker(void *p) +{ + if (!p) { + return; + } + // We control the class of the main greenlet exactly. + if (Py_TYPE(p) != &PyGreenlet_Type) { + std::string err("MainGreenlet: Expected exactly a greenlet, not a "); + err += Py_TYPE(p)->tp_name; + throw greenlet::TypeError(err); + } + + // Greenlets from dead threads no longer respond to main() with a + // true value; so in that case we need to perform an additional + // check. + Greenlet* g = static_cast(p)->pimpl; + if (g->main()) { + return; + } + if (!dynamic_cast(g)) { + std::string err("MainGreenlet: Expected exactly a main greenlet, not a "); + err += Py_TYPE(p)->tp_name; + throw greenlet::TypeError(err); + } +} + + + +template +inline greenlet::Greenlet* greenlet::refs::_OwnedGreenlet::operator->() const noexcept +{ + return reinterpret_cast(this->p)->pimpl; +} + +template +inline greenlet::Greenlet* greenlet::refs::_BorrowedGreenlet::operator->() const noexcept +{ + return reinterpret_cast(this->p)->pimpl; +} + +#include +#include + + +extern PyTypeObject PyGreenlet_Type; + + + +/** + * Forward declarations needed in multiple files. + */ +static PyObject* green_switch(PyGreenlet* self, PyObject* args, PyObject* kwargs); + + +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + + +#endif + +// Local Variables: +// flycheck-clang-include-path: ("../../include" "/opt/local/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10") +// End: diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_msvc_compat.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_msvc_compat.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c00245b057cce4d7083e7fd965c4e11bb20292d3 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_msvc_compat.hpp @@ -0,0 +1,91 @@ +#ifndef GREENLET_MSVC_COMPAT_HPP +#define GREENLET_MSVC_COMPAT_HPP +/* + * Support for MSVC on Windows. + * + * Beginning with Python 3.14, some of the internal + * include files we need are not compatible with MSVC + * in C++ mode: + * + * internal\pycore_stackref.h(253): error C4576: a parenthesized type + * followed by an initializer list is a non-standard explicit type conversion syntax + * + * This file is included from ``internal/pycore_interpframe.h``, which + * we need for the ``_PyFrame_IsIncomplete`` API. + * + * Unfortunately, that API is a ``static inline`` function, as are a + * bunch of the functions it calls. The only solution seems to be to + * copy those definitions and the supporting inline functions here. + * + * Now, this makes us VERY fragile to changes in those functions. Because + * they're internal and static, the CPython devs might feel free to change + * them in even minor versions, meaning that we could runtime link and load, + * but still crash. We have that problem on all platforms though. It's just worse + * here because we have to keep copying the updated definitions. + */ +#include +#include "greenlet_cpython_compat.hpp" + +// This file is only included on 3.14+ + +extern "C" { + +// pycore_code.h ---------------- +#define _PyCode_CODE(CO) _Py_RVALUE((_Py_CODEUNIT *)(CO)->co_code_adaptive) +// End pycore_code.h ---------- + +// pycore_interpframe.h ---------- +#if !defined(Py_GIL_DISABLED) && defined(Py_STACKREF_DEBUG) + +#define Py_TAG_BITS 0 +#else +#define Py_TAG_BITS ((uintptr_t)1) +#define Py_TAG_DEFERRED (1) +#endif + + +static const _PyStackRef PyStackRef_NULL = { .bits = Py_TAG_DEFERRED}; +#define PyStackRef_IsNull(stackref) ((stackref).bits == PyStackRef_NULL.bits) + +static inline PyObject * +PyStackRef_AsPyObjectBorrow(_PyStackRef stackref) +{ + PyObject *cleared = ((PyObject *)((stackref).bits & (~Py_TAG_BITS))); + return cleared; +} + +static inline PyCodeObject *_PyFrame_GetCode(_PyInterpreterFrame *f) { + assert(!PyStackRef_IsNull(f->f_executable)); + PyObject *executable = PyStackRef_AsPyObjectBorrow(f->f_executable); + assert(PyCode_Check(executable)); + return (PyCodeObject *)executable; +} + + +static inline _Py_CODEUNIT * +_PyFrame_GetBytecode(_PyInterpreterFrame *f) +{ +#ifdef Py_GIL_DISABLED + PyCodeObject *co = _PyFrame_GetCode(f); + _PyCodeArray *tlbc = _PyCode_GetTLBCArray(co); + assert(f->tlbc_index >= 0 && f->tlbc_index < tlbc->size); + return (_Py_CODEUNIT *)tlbc->entries[f->tlbc_index]; +#else + return _PyCode_CODE(_PyFrame_GetCode(f)); +#endif +} + +static inline bool //_Py_NO_SANITIZE_THREAD +_PyFrame_IsIncomplete(_PyInterpreterFrame *frame) +{ + if (frame->owner >= FRAME_OWNED_BY_INTERPRETER) { + return true; + } + return frame->owner != FRAME_OWNED_BY_GENERATOR && + frame->instr_ptr < _PyFrame_GetBytecode(frame) + + _PyFrame_GetCode(frame)->_co_firsttraceable; +} +// pycore_interpframe.h ---------- + +} +#endif // GREENLET_MSVC_COMPAT_HPP diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_refs.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_refs.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b7e5e3f2aba7c2ee9ea48a6e261c8366482531db --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_refs.hpp @@ -0,0 +1,1118 @@ +#ifndef GREENLET_REFS_HPP +#define GREENLET_REFS_HPP + +#define PY_SSIZE_T_CLEAN +#include + +#include + +//#include "greenlet_internal.hpp" +#include "greenlet_compiler_compat.hpp" +#include "greenlet_cpython_compat.hpp" +#include "greenlet_exceptions.hpp" + +struct _greenlet; +struct _PyMainGreenlet; + +typedef struct _greenlet PyGreenlet; +extern PyTypeObject PyGreenlet_Type; + + +#ifdef GREENLET_USE_STDIO +#include +using std::cerr; +using std::endl; +#endif + +namespace greenlet +{ + class Greenlet; + + namespace refs + { + // Type checkers throw a TypeError if the argument is not + // null, and isn't of the required Python type. + // (We can't use most of the defined type checkers + // like PyList_Check, etc, directly, because they are + // implemented as macros.) + typedef void (*TypeChecker)(void*); + + void + NoOpChecker(void*) + { + return; + } + + void + GreenletChecker(void *p) + { + if (!p) { + return; + } + + PyTypeObject* typ = Py_TYPE(p); + // fast, common path. (PyObject_TypeCheck is a macro or + // static inline function, and it also does a + // direct comparison of the type pointers, but its fast + // path only handles one type) + if (typ == &PyGreenlet_Type) { + return; + } + + if (!PyObject_TypeCheck(p, &PyGreenlet_Type)) { + std::string err("GreenletChecker: Expected any type of greenlet, not "); + err += Py_TYPE(p)->tp_name; + throw TypeError(err); + } + } + + void + MainGreenletExactChecker(void *p); + + template + class PyObjectPointer; + + template + class OwnedReference; + + + template + class BorrowedReference; + + typedef BorrowedReference BorrowedObject; + typedef OwnedReference OwnedObject; + + class ImmortalObject; + class ImmortalString; + + template + class _OwnedGreenlet; + + typedef _OwnedGreenlet OwnedGreenlet; + typedef _OwnedGreenlet OwnedMainGreenlet; + + template + class _BorrowedGreenlet; + + typedef _BorrowedGreenlet BorrowedGreenlet; + + void + ContextExactChecker(void *p) + { + if (!p) { + return; + } + if (!PyContext_CheckExact(p)) { + throw TypeError( + "greenlet context must be a contextvars.Context or None" + ); + } + } + + typedef OwnedReference OwnedContext; + } +} + +namespace greenlet { + + + namespace refs { + // A set of classes to make reference counting rules in python + // code explicit. + // + // Rules of use: + // (1) Functions returning a new reference that the caller of the + // function is expected to dispose of should return a + // ``OwnedObject`` object. This object automatically releases its + // reference when it goes out of scope. It works like a ``std::shared_ptr`` + // and can be copied or used as a function parameter (but don't do + // that). Note that constructing a ``OwnedObject`` from a + // PyObject* steals the reference. + // (2) Parameters to functions should be either a + // ``OwnedObject&``, or, more generally, a ``PyObjectPointer&``. + // If the function needs to create its own new reference, it can + // do so by copying to a local ``OwnedObject``. + // (3) Functions returning an existing pointer that is NOT + // incref'd, and which the caller MUST NOT decref, + // should return a ``BorrowedObject``. + + // XXX: The following two paragraphs do not hold for all platforms. + // Notably, 32-bit PPC Linux passes structs by reference, not by + // value, so this actually doesn't work. (Although that's the only + // platform that doesn't work on.) DO NOT ATTEMPT IT. The + // unfortunate consequence of that is that the slots which we + // *know* are already type safe will wind up calling the type + // checker function (when we had the slots accepting + // BorrowedGreenlet, this was bypassed), so this slows us down. + // TODO: Optimize this again. + + // For a class with a single pointer member, whose constructor + // does nothing but copy a pointer parameter into the member, and + // which can then be converted back to the pointer type, compilers + // generate code that's the same as just passing the pointer. + // That is, func(BorrowedObject x) called like ``PyObject* p = + // ...; f(p)`` has 0 overhead. Similarly, they "unpack" to the + // pointer type with 0 overhead. + // + // If there are no virtual functions, no complex inheritance (maybe?) and + // no destructor, these can be directly used as parameters in + // Python callbacks like tp_init: the layout is the same as a + // single pointer. Only subclasses with trivial constructors that + // do nothing but set the single pointer member are safe to use + // that way. + + + // This is the base class for things that can be done with a + // PyObject pointer. It assumes nothing about memory management. + // NOTE: Nothing is virtual, so subclasses shouldn't add new + // storage fields or try to override these methods. + template + class PyObjectPointer + { + public: + typedef T PyType; + protected: + T* p; + public: + PyObjectPointer(T* it=nullptr) : p(it) + { + TC(p); + } + + // We don't allow automatic casting to PyObject* at this + // level, because then we could be passed to Py_DECREF/INCREF, + // but we want nothing to do with memory management. If you + // know better, then you can use the get() method, like on a + // std::shared_ptr. Except we name it borrow() to clarify that + // if this is a reference-tracked object, the pointer you get + // back will go away when the object does. + // TODO: This should probably not exist here, but be moved + // down to relevant sub-types. + + T* borrow() const noexcept + { + return this->p; + } + + PyObject* borrow_o() const noexcept + { + return reinterpret_cast(this->p); + } + + T* operator->() const noexcept + { + return this->p; + } + + bool is_None() const noexcept + { + return this->p == Py_None; + } + + PyObject* acquire_or_None() const noexcept + { + PyObject* result = this->p ? reinterpret_cast(this->p) : Py_None; + Py_INCREF(result); + return result; + } + + explicit operator bool() const noexcept + { + return this->p != nullptr; + } + + bool operator!() const noexcept + { + return this->p == nullptr; + } + + Py_ssize_t REFCNT() const noexcept + { + return p ? Py_REFCNT(p) : -42; + } + + PyTypeObject* TYPE() const noexcept + { + return p ? Py_TYPE(p) : nullptr; + } + + inline OwnedObject PyStr() const noexcept; + inline const std::string as_str() const noexcept; + inline OwnedObject PyGetAttr(const ImmortalObject& name) const noexcept; + inline OwnedObject PyRequireAttr(const char* const name) const; + inline OwnedObject PyRequireAttr(const ImmortalString& name) const; + inline OwnedObject PyCall(const BorrowedObject& arg) const; + inline OwnedObject PyCall(PyGreenlet* arg) const ; + inline OwnedObject PyCall(PyObject* arg) const ; + // PyObject_Call(this, args, kwargs); + inline OwnedObject PyCall(const BorrowedObject args, + const BorrowedObject kwargs) const; + inline OwnedObject PyCall(const OwnedObject& args, + const OwnedObject& kwargs) const; + + protected: + void _set_raw_pointer(void* t) + { + TC(t); + p = reinterpret_cast(t); + } + void* _get_raw_pointer() const + { + return p; + } + }; + +#ifdef GREENLET_USE_STDIO + template + std::ostream& operator<<(std::ostream& os, const PyObjectPointer& s) + { + const std::type_info& t = typeid(s); + os << t.name() + << "(addr=" << s.borrow() + << ", refcnt=" << s.REFCNT() + << ", value=" << s.as_str() + << ")"; + + return os; + } +#endif + + template + inline bool operator==(const PyObjectPointer& lhs, const PyObject* const rhs) noexcept + { + return static_cast(lhs.borrow_o()) == static_cast(rhs); + } + + template + inline bool operator==(const PyObjectPointer& lhs, const PyObjectPointer& rhs) noexcept + { + return lhs.borrow_o() == rhs.borrow_o(); + } + + template + inline bool operator!=(const PyObjectPointer& lhs, + const PyObjectPointer& rhs) noexcept + { + return lhs.borrow_o() != rhs.borrow_o(); + } + + template + class OwnedReference : public PyObjectPointer + { + private: + friend class OwnedList; + + protected: + explicit OwnedReference(T* it) : PyObjectPointer(it) + { + } + + public: + + // Constructors + + static OwnedReference consuming(PyObject* p) + { + return OwnedReference(reinterpret_cast(p)); + } + + static OwnedReference owning(T* p) + { + OwnedReference result(p); + Py_XINCREF(result.p); + return result; + } + + OwnedReference() : PyObjectPointer(nullptr) + {} + + explicit OwnedReference(const PyObjectPointer<>& other) + : PyObjectPointer(nullptr) + { + T* op = other.borrow(); + TC(op); + this->p = other.borrow(); + Py_XINCREF(this->p); + } + + // It would be good to make use of the C++11 distinction + // between move and copy operations, e.g., constructing from a + // pointer should be a move operation. + // In the common case of ``OwnedObject x = Py_SomeFunction()``, + // the call to the copy constructor will be elided completely. + OwnedReference(const OwnedReference& other) + : PyObjectPointer(other.p) + { + Py_XINCREF(this->p); + } + + static OwnedReference None() + { + Py_INCREF(Py_None); + return OwnedReference(Py_None); + } + + // We can assign from exactly our type without any extra checking + OwnedReference& operator=(const OwnedReference& other) + { + Py_XINCREF(other.p); + const T* tmp = this->p; + this->p = other.p; + Py_XDECREF(tmp); + return *this; + } + + OwnedReference& operator=(const BorrowedReference other) + { + return this->operator=(other.borrow()); + } + + OwnedReference& operator=(T* const other) + { + TC(other); + Py_XINCREF(other); + T* tmp = this->p; + this->p = other; + Py_XDECREF(tmp); + return *this; + } + + // We can assign from an arbitrary reference type + // if it passes our check. + template + OwnedReference& operator=(const OwnedReference& other) + { + X* op = other.borrow(); + TC(op); + return this->operator=(reinterpret_cast(op)); + } + + inline void steal(T* other) + { + assert(this->p == nullptr); + TC(other); + this->p = other; + } + + T* relinquish_ownership() + { + T* result = this->p; + this->p = nullptr; + return result; + } + + T* acquire() const + { + // Return a new reference. + // TODO: This may go away when we have reference objects + // throughout the code. + Py_XINCREF(this->p); + return this->p; + } + + // Nothing else declares a destructor, we're the leaf, so we + // should be able to get away without virtual. + ~OwnedReference() + { + Py_CLEAR(this->p); + } + + void CLEAR() + { + Py_CLEAR(this->p); + assert(this->p == nullptr); + } + }; + + static inline + void operator<<=(PyObject*& target, OwnedObject& o) + { + target = o.relinquish_ownership(); + } + + + class NewReference : public OwnedObject + { + private: + G_NO_COPIES_OF_CLS(NewReference); + public: + // Consumes the reference. Only use this + // for API return values. + NewReference(PyObject* it) : OwnedObject(it) + { + } + }; + + class NewDictReference : public NewReference + { + private: + G_NO_COPIES_OF_CLS(NewDictReference); + public: + NewDictReference() : NewReference(PyDict_New()) + { + if (!this->p) { + throw PyErrOccurred(); + } + } + + void SetItem(const char* const key, PyObject* value) + { + Require(PyDict_SetItemString(this->p, key, value)); + } + + void SetItem(const PyObjectPointer<>& key, PyObject* value) + { + Require(PyDict_SetItem(this->p, key.borrow_o(), value)); + } + }; + + template + class _OwnedGreenlet: public OwnedReference + { + private: + protected: + _OwnedGreenlet(T* it) : OwnedReference(it) + {} + + public: + _OwnedGreenlet() : OwnedReference() + {} + + _OwnedGreenlet(const _OwnedGreenlet& other) : OwnedReference(other) + { + } + _OwnedGreenlet(OwnedMainGreenlet& other) : + OwnedReference(reinterpret_cast(other.acquire())) + { + } + _OwnedGreenlet(const BorrowedGreenlet& other); + // Steals a reference. + static _OwnedGreenlet consuming(PyGreenlet* it) + { + return _OwnedGreenlet(reinterpret_cast(it)); + } + + inline _OwnedGreenlet& operator=(const OwnedGreenlet& other) + { + return this->operator=(other.borrow()); + } + + inline _OwnedGreenlet& operator=(const BorrowedGreenlet& other); + + _OwnedGreenlet& operator=(const OwnedMainGreenlet& other) + { + PyGreenlet* owned = other.acquire(); + Py_XDECREF(this->p); + this->p = reinterpret_cast(owned); + return *this; + } + + _OwnedGreenlet& operator=(T* const other) + { + OwnedReference::operator=(other); + return *this; + } + + T* relinquish_ownership() + { + T* result = this->p; + this->p = nullptr; + return result; + } + + PyObject* relinquish_ownership_o() + { + return reinterpret_cast(relinquish_ownership()); + } + + inline Greenlet* operator->() const noexcept; + inline operator Greenlet*() const noexcept; + }; + + template + class BorrowedReference : public PyObjectPointer + { + public: + // Allow implicit creation from PyObject* pointers as we + // transition to using these classes. Also allow automatic + // conversion to PyObject* for passing to C API calls and even + // for Py_INCREF/DECREF, because we ourselves do no memory management. + BorrowedReference(T* it) : PyObjectPointer(it) + {} + + BorrowedReference(const PyObjectPointer& ref) : PyObjectPointer(ref.borrow()) + {} + + BorrowedReference() : PyObjectPointer(nullptr) + {} + + operator T*() const + { + return this->p; + } + }; + + typedef BorrowedReference BorrowedObject; + //typedef BorrowedReference BorrowedGreenlet; + + template + class _BorrowedGreenlet : public BorrowedReference + { + public: + _BorrowedGreenlet() : + BorrowedReference(nullptr) + {} + + _BorrowedGreenlet(T* it) : + BorrowedReference(it) + {} + + _BorrowedGreenlet(const BorrowedObject& it); + + _BorrowedGreenlet(const OwnedGreenlet& it) : + BorrowedReference(it.borrow()) + {} + + _BorrowedGreenlet& operator=(const BorrowedObject& other); + + // We get one of these for PyGreenlet, but one for PyObject + // is handy as well + operator PyObject*() const + { + return reinterpret_cast(this->p); + } + Greenlet* operator->() const noexcept; + operator Greenlet*() const noexcept; + }; + + typedef _BorrowedGreenlet BorrowedGreenlet; + + template + _OwnedGreenlet::_OwnedGreenlet(const BorrowedGreenlet& other) + : OwnedReference(reinterpret_cast(other.borrow())) + { + Py_XINCREF(this->p); + } + + + class BorrowedMainGreenlet + : public _BorrowedGreenlet + { + public: + BorrowedMainGreenlet(const OwnedMainGreenlet& it) : + _BorrowedGreenlet(it.borrow()) + {} + BorrowedMainGreenlet(PyGreenlet* it=nullptr) + : _BorrowedGreenlet(it) + {} + }; + + template + _OwnedGreenlet& _OwnedGreenlet::operator=(const BorrowedGreenlet& other) + { + return this->operator=(other.borrow()); + } + + + class ImmortalObject : public PyObjectPointer<> + { + private: + G_NO_ASSIGNMENT_OF_CLS(ImmortalObject); + public: + explicit ImmortalObject(PyObject* it) : PyObjectPointer<>(it) + { + } + + ImmortalObject(const ImmortalObject& other) + : PyObjectPointer<>(other.p) + { + + } + + /** + * Become the new owner of the object. Does not change the + * reference count. + */ + ImmortalObject& operator=(PyObject* it) + { + assert(this->p == nullptr); + this->p = it; + return *this; + } + + static ImmortalObject consuming(PyObject* it) + { + return ImmortalObject(it); + } + + inline operator PyObject*() const + { + return this->p; + } + }; + + class ImmortalString : public ImmortalObject + { + private: + G_NO_COPIES_OF_CLS(ImmortalString); + const char* str; + public: + ImmortalString(const char* const str) : + ImmortalObject(str ? Require(PyUnicode_InternFromString(str)) : nullptr) + { + this->str = str; + } + + inline ImmortalString& operator=(const char* const str) + { + if (!this->p) { + this->p = Require(PyUnicode_InternFromString(str)); + this->str = str; + } + else { + assert(this->str == str); + } + return *this; + } + + inline operator std::string() const + { + return this->str; + } + + }; + + class ImmortalEventName : public ImmortalString + { + private: + G_NO_COPIES_OF_CLS(ImmortalEventName); + public: + ImmortalEventName(const char* const str) : ImmortalString(str) + {} + }; + + class ImmortalException : public ImmortalObject + { + private: + G_NO_COPIES_OF_CLS(ImmortalException); + public: + ImmortalException(const char* const name, PyObject* base=nullptr) : + ImmortalObject(name + // Python 2.7 isn't const correct + ? Require(PyErr_NewException((char*)name, base, nullptr)) + : nullptr) + {} + + inline bool PyExceptionMatches() const + { + return PyErr_ExceptionMatches(this->p) > 0; + } + + }; + + template + inline OwnedObject PyObjectPointer::PyStr() const noexcept + { + if (!this->p) { + return OwnedObject(); + } + return OwnedObject::consuming(PyObject_Str(reinterpret_cast(this->p))); + } + + template + inline const std::string PyObjectPointer::as_str() const noexcept + { + // NOTE: This is not Python exception safe. + if (this->p) { + // The Python APIs return a cached char* value that's only valid + // as long as the original object stays around, and we're + // about to (probably) toss it. Hence the copy to std::string. + OwnedObject py_str = this->PyStr(); + if (!py_str) { + return "(nil)"; + } + return PyUnicode_AsUTF8(py_str.borrow()); + } + return "(nil)"; + } + + template + inline OwnedObject PyObjectPointer::PyGetAttr(const ImmortalObject& name) const noexcept + { + assert(this->p); + return OwnedObject::consuming(PyObject_GetAttr(reinterpret_cast(this->p), name)); + } + + template + inline OwnedObject PyObjectPointer::PyRequireAttr(const char* const name) const + { + assert(this->p); + return OwnedObject::consuming(Require(PyObject_GetAttrString(this->p, name), name)); + } + + template + inline OwnedObject PyObjectPointer::PyRequireAttr(const ImmortalString& name) const + { + assert(this->p); + return OwnedObject::consuming(Require( + PyObject_GetAttr( + reinterpret_cast(this->p), + name + ), + name + )); + } + + template + inline OwnedObject PyObjectPointer::PyCall(const BorrowedObject& arg) const + { + return this->PyCall(arg.borrow()); + } + + template + inline OwnedObject PyObjectPointer::PyCall(PyGreenlet* arg) const + { + return this->PyCall(reinterpret_cast(arg)); + } + + template + inline OwnedObject PyObjectPointer::PyCall(PyObject* arg) const + { + assert(this->p); + return OwnedObject::consuming(PyObject_CallFunctionObjArgs(this->p, arg, NULL)); + } + + template + inline OwnedObject PyObjectPointer::PyCall(const BorrowedObject args, + const BorrowedObject kwargs) const + { + assert(this->p); + return OwnedObject::consuming(PyObject_Call(this->p, args, kwargs)); + } + + template + inline OwnedObject PyObjectPointer::PyCall(const OwnedObject& args, + const OwnedObject& kwargs) const + { + assert(this->p); + return OwnedObject::consuming(PyObject_Call(this->p, args.borrow(), kwargs.borrow())); + } + + inline void + ListChecker(void * p) + { + if (!p) { + return; + } + if (!PyList_Check(p)) { + throw TypeError("Expected a list"); + } + } + + class OwnedList : public OwnedReference + { + private: + G_NO_ASSIGNMENT_OF_CLS(OwnedList); + public: + // TODO: Would like to use move. + explicit OwnedList(const OwnedObject& other) + : OwnedReference(other) + { + } + + OwnedList& operator=(const OwnedObject& other) + { + if (other && PyList_Check(other.p)) { + // Valid list. Own a new reference to it, discard the + // reference to what we did own. + PyObject* new_ptr = other.p; + Py_INCREF(new_ptr); + Py_XDECREF(this->p); + this->p = new_ptr; + } + else { + // Either the other object was NULL (an error) or it + // wasn't a list. Either way, we're now invalidated. + Py_XDECREF(this->p); + this->p = nullptr; + } + return *this; + } + + inline bool empty() const + { + return PyList_GET_SIZE(p) == 0; + } + + inline Py_ssize_t size() const + { + return PyList_GET_SIZE(p); + } + + inline BorrowedObject at(const Py_ssize_t index) const + { + return PyList_GET_ITEM(p, index); + } + + inline void clear() + { + PyList_SetSlice(p, 0, PyList_GET_SIZE(p), NULL); + } + }; + + // Use this to represent the module object used at module init + // time. + // This could either be a borrowed (Py2) or new (Py3) reference; + // either way, we don't want to do any memory management + // on it here, Python itself will handle that. + // XXX: Actually, that's not quite right. On Python 3, if an + // exception occurs before we return to the interpreter, this will + // leak; but all previous versions also had that problem. + class CreatedModule : public PyObjectPointer<> + { + private: + G_NO_COPIES_OF_CLS(CreatedModule); + public: + CreatedModule(PyModuleDef& mod_def) : PyObjectPointer<>( + Require(PyModule_Create(&mod_def))) + { + } + + // PyAddObject(): Add a reference to the object to the module. + // On return, the reference count of the object is unchanged. + // + // The docs warn that PyModule_AddObject only steals the + // reference on success, so if it fails after we've incref'd + // or allocated, we're responsible for the decref. + void PyAddObject(const char* name, const long new_bool) + { + OwnedObject p = OwnedObject::consuming(Require(PyBool_FromLong(new_bool))); + this->PyAddObject(name, p); + } + + void PyAddObject(const char* name, const OwnedObject& new_object) + { + // The caller already owns a reference they will decref + // when their variable goes out of scope, we still need to + // incref/decref. + this->PyAddObject(name, new_object.borrow()); + } + + void PyAddObject(const char* name, const ImmortalObject& new_object) + { + this->PyAddObject(name, new_object.borrow()); + } + + void PyAddObject(const char* name, PyTypeObject& type) + { + this->PyAddObject(name, reinterpret_cast(&type)); + } + + void PyAddObject(const char* name, PyObject* new_object) + { + Py_INCREF(new_object); + try { + Require(PyModule_AddObject(this->p, name, new_object)); + } + catch (const PyErrOccurred&) { + Py_DECREF(p); + throw; + } + } + }; + + class PyErrFetchParam : public PyObjectPointer<> + { + // Not an owned object, because we can't be initialized with + // one, and we only sometimes acquire ownership. + private: + G_NO_COPIES_OF_CLS(PyErrFetchParam); + public: + // To allow declaring these and passing them to + // PyErr_Fetch we implement the empty constructor, + // and the address operator. + PyErrFetchParam() : PyObjectPointer<>(nullptr) + { + } + + PyObject** operator&() + { + return &this->p; + } + + // This allows us to pass one directly without the &, + // BUT it has higher precedence than the bool operator + // if it's not explicit. + operator PyObject**() + { + return &this->p; + } + + // We don't want to be able to pass these to Py_DECREF and + // such so we don't have the implicit PyObject* conversion. + + inline PyObject* relinquish_ownership() + { + PyObject* result = this->p; + this->p = nullptr; + return result; + } + + ~PyErrFetchParam() + { + Py_XDECREF(p); + } + }; + + class OwnedErrPiece : public OwnedObject + { + private: + + public: + // Unlike OwnedObject, this increments the refcount. + OwnedErrPiece(PyObject* p=nullptr) : OwnedObject(p) + { + this->acquire(); + } + + PyObject** operator&() + { + return &this->p; + } + + inline operator PyObject*() const + { + return this->p; + } + + operator PyTypeObject*() const + { + return reinterpret_cast(this->p); + } + }; + + class PyErrPieces + { + private: + OwnedErrPiece type; + OwnedErrPiece instance; + OwnedErrPiece traceback; + bool restored; + public: + // Takes new references; if we're destroyed before + // restoring the error, we drop the references. + PyErrPieces(PyObject* t, PyObject* v, PyObject* tb) : + type(t), + instance(v), + traceback(tb), + restored(0) + { + this->normalize(); + } + + PyErrPieces() : + restored(0) + { + // PyErr_Fetch transfers ownership to us, so + // we don't actually need to INCREF; but we *do* + // need to DECREF if we're not restored. + PyErrFetchParam t, v, tb; + PyErr_Fetch(&t, &v, &tb); + type.steal(t.relinquish_ownership()); + instance.steal(v.relinquish_ownership()); + traceback.steal(tb.relinquish_ownership()); + } + + void PyErrRestore() + { + // can only do this once + assert(!this->restored); + this->restored = true; + PyErr_Restore( + this->type.relinquish_ownership(), + this->instance.relinquish_ownership(), + this->traceback.relinquish_ownership()); + assert(!this->type && !this->instance && !this->traceback); + } + + private: + void normalize() + { + // First, check the traceback argument, replacing None, + // with NULL + if (traceback.is_None()) { + traceback = nullptr; + } + + if (traceback && !PyTraceBack_Check(traceback.borrow())) { + throw PyErrOccurred(PyExc_TypeError, + "throw() third argument must be a traceback object"); + } + + if (PyExceptionClass_Check(type)) { + // If we just had a type, we'll now have a type and + // instance. + // The type's refcount will have gone up by one + // because of the instance and the instance will have + // a refcount of one. Either way, we owned, and still + // do own, exactly one reference. + PyErr_NormalizeException(&type, &instance, &traceback); + + } + else if (PyExceptionInstance_Check(type)) { + /* Raising an instance --- usually that means an + object that is a subclass of BaseException, but on + Python 2, that can also mean an arbitrary old-style + object. The value should be a dummy. */ + if (instance && !instance.is_None()) { + throw PyErrOccurred( + PyExc_TypeError, + "instance exception may not have a separate value"); + } + /* Normalize to raise , */ + this->instance = this->type; + this->type = PyExceptionInstance_Class(instance.borrow()); + + /* + It would be tempting to do this: + + Py_ssize_t type_count = Py_REFCNT(Py_TYPE(instance.borrow())); + this->type = PyExceptionInstance_Class(instance.borrow()); + assert(this->type.REFCNT() == type_count + 1); + + But that doesn't work on Python 2 in the case of + old-style instances: The result of Py_TYPE is going to + be the global shared that all + old-style classes have, while the return of Instance_Class() + will be the Python-level class object. The two are unrelated. + */ + } + else { + /* Not something you can raise. throw() fails. */ + PyErr_Format(PyExc_TypeError, + "exceptions must be classes, or instances, not %s", + Py_TYPE(type.borrow())->tp_name); + throw PyErrOccurred(); + } + } + }; + + // PyArg_Parse's O argument returns a borrowed reference. + class PyArgParseParam : public BorrowedObject + { + private: + G_NO_COPIES_OF_CLS(PyArgParseParam); + public: + explicit PyArgParseParam(PyObject* p=nullptr) : BorrowedObject(p) + { + } + + inline PyObject** operator&() + { + return &this->p; + } + }; + +};}; + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_slp_switch.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_slp_switch.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bd4b7ae1a6ea950b19fa890784021426822ea274 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_slp_switch.hpp @@ -0,0 +1,99 @@ +#ifndef GREENLET_SLP_SWITCH_HPP +#define GREENLET_SLP_SWITCH_HPP + +#include "greenlet_compiler_compat.hpp" +#include "greenlet_refs.hpp" + +/* + * the following macros are spliced into the OS/compiler + * specific code, in order to simplify maintenance. + */ +// We can save about 10% of the time it takes to switch greenlets if +// we thread the thread state through the slp_save_state() and the +// following slp_restore_state() calls from +// slp_switch()->g_switchstack() (which already needs to access it). +// +// However: +// +// that requires changing the prototypes and implementations of the +// switching functions. If we just change the prototype of +// slp_switch() to accept the argument and update the macros, without +// changing the implementation of slp_switch(), we get crashes on +// 64-bit Linux and 32-bit x86 (for reasons that aren't 100% clear); +// on the other hand, 64-bit macOS seems to be fine. Also, 64-bit +// windows is an issue because slp_switch is written fully in assembly +// and currently ignores its argument so some code would have to be +// adjusted there to pass the argument on to the +// ``slp_save_state_asm()`` function (but interestingly, because of +// the calling convention, the extra argument is just ignored and +// things function fine, albeit slower, if we just modify +// ``slp_save_state_asm`()` to fetch the pointer to pass to the +// macro.) +// +// Our compromise is to use a *glabal*, untracked, weak, pointer +// to the necessary thread state during the process of switching only. +// This is safe because we're protected by the GIL, and if we're +// running this code, the thread isn't exiting. This also nets us a +// 10-12% speed improvement. + +static greenlet::Greenlet* volatile switching_thread_state = nullptr; + + +extern "C" { +static int GREENLET_NOINLINE(slp_save_state_trampoline)(char* stackref); +static void GREENLET_NOINLINE(slp_restore_state_trampoline)(); +} + + +#define SLP_SAVE_STATE(stackref, stsizediff) \ +do { \ + assert(switching_thread_state); \ + stackref += STACK_MAGIC; \ + if (slp_save_state_trampoline((char*)stackref)) \ + return -1; \ + if (!switching_thread_state->active()) \ + return 1; \ + stsizediff = switching_thread_state->stack_start() - (char*)stackref; \ +} while (0) + +#define SLP_RESTORE_STATE() slp_restore_state_trampoline() + +#define SLP_EVAL +extern "C" { +#define slp_switch GREENLET_NOINLINE(slp_switch) +#include "slp_platformselect.h" +} +#undef slp_switch + +#ifndef STACK_MAGIC +# error \ + "greenlet needs to be ported to this platform, or taught how to detect your compiler properly." +#endif /* !STACK_MAGIC */ + + + +#ifdef EXTERNAL_ASM +/* CCP addition: Make these functions, to be called from assembler. + * The token include file for the given platform should enable the + * EXTERNAL_ASM define so that this is included. + */ +extern "C" { +intptr_t +slp_save_state_asm(intptr_t* ref) +{ + intptr_t diff; + SLP_SAVE_STATE(ref, diff); + return diff; +} + +void +slp_restore_state_asm(void) +{ + SLP_RESTORE_STATE(); +} + +extern int slp_switch(void); +}; +#endif + +#endif diff --git a/python_embeded/Lib/site-packages/greenlet/greenlet_thread_support.hpp b/python_embeded/Lib/site-packages/greenlet/greenlet_thread_support.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3ded7d2b730e79d15c95704491d7020cf58bb92f --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/greenlet_thread_support.hpp @@ -0,0 +1,31 @@ +#ifndef GREENLET_THREAD_SUPPORT_HPP +#define GREENLET_THREAD_SUPPORT_HPP + +/** + * Defines various utility functions to help greenlet integrate well + * with threads. This used to be needed when we supported Python + * 2.7 on Windows, which used a very old compiler. We wrote an + * alternative implementation using Python APIs and POSIX or Windows + * APIs, but that's no longer needed. So this file is a shadow of its + * former self --- but may be needed in the future. + */ + +#include +#include +#include + +#include "greenlet_compiler_compat.hpp" + +namespace greenlet { + typedef std::mutex Mutex; + typedef std::lock_guard LockGuard; + class LockInitError : public std::runtime_error + { + public: + LockInitError(const char* what) : std::runtime_error(what) + {}; + }; +}; + + +#endif /* GREENLET_THREAD_SUPPORT_HPP */ diff --git a/python_embeded/Lib/site-packages/greenlet/slp_platformselect.h b/python_embeded/Lib/site-packages/greenlet/slp_platformselect.h new file mode 100644 index 0000000000000000000000000000000000000000..d9b7d0a71696c45abe1c59f3a4c7f477b139ee06 --- /dev/null +++ b/python_embeded/Lib/site-packages/greenlet/slp_platformselect.h @@ -0,0 +1,77 @@ +/* + * Platform Selection for Stackless Python + */ +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(MS_WIN32) && !defined(MS_WIN64) && defined(_M_IX86) && defined(_MSC_VER) +# include "platform/switch_x86_msvc.h" /* MS Visual Studio on X86 */ +#elif defined(MS_WIN64) && defined(_M_X64) && defined(_MSC_VER) || defined(__MINGW64__) +# include "platform/switch_x64_msvc.h" /* MS Visual Studio on X64 */ +#elif defined(MS_WIN64) && defined(_M_ARM64) +# include "platform/switch_arm64_msvc.h" /* MS Visual Studio on ARM64 */ +#elif defined(__GNUC__) && defined(__amd64__) && defined(__ILP32__) +# include "platform/switch_x32_unix.h" /* gcc on amd64 with x32 ABI */ +#elif defined(__GNUC__) && defined(__amd64__) +# include "platform/switch_amd64_unix.h" /* gcc on amd64 */ +#elif defined(__GNUC__) && defined(__i386__) +# include "platform/switch_x86_unix.h" /* gcc on X86 */ +#elif defined(__GNUC__) && defined(__powerpc64__) && (defined(__linux__) || defined(__FreeBSD__)) +# include "platform/switch_ppc64_linux.h" /* gcc on PowerPC 64-bit */ +#elif defined(__GNUC__) && defined(__PPC__) && (defined(__linux__) || defined(__FreeBSD__)) +# include "platform/switch_ppc_linux.h" /* gcc on PowerPC */ +#elif defined(__GNUC__) && defined(__POWERPC__) && defined(__APPLE__) +# include "platform/switch_ppc_macosx.h" /* Apple MacOS X on 32-bit PowerPC */ +#elif defined(__GNUC__) && defined(__powerpc64__) && defined(_AIX) +# include "platform/switch_ppc64_aix.h" /* gcc on AIX/PowerPC 64-bit */ +#elif defined(__GNUC__) && defined(_ARCH_PPC) && defined(_AIX) +# include "platform/switch_ppc_aix.h" /* gcc on AIX/PowerPC */ +#elif defined(__GNUC__) && defined(__powerpc__) && defined(__NetBSD__) +#include "platform/switch_ppc_unix.h" /* gcc on NetBSD/powerpc */ +#elif defined(__GNUC__) && defined(sparc) +# include "platform/switch_sparc_sun_gcc.h" /* SunOS sparc with gcc */ +#elif defined(__GNUC__) && defined(__sparc__) +# include "platform/switch_sparc_sun_gcc.h" /* NetBSD sparc with gcc */ +#elif defined(__SUNPRO_C) && defined(sparc) && defined(sun) +# include "platform/switch_sparc_sun_gcc.h" /* SunStudio on amd64 */ +#elif defined(__SUNPRO_C) && defined(__amd64__) && defined(sun) +# include "platform/switch_amd64_unix.h" /* SunStudio on amd64 */ +#elif defined(__SUNPRO_C) && defined(__i386__) && defined(sun) +# include "platform/switch_x86_unix.h" /* SunStudio on x86 */ +#elif defined(__GNUC__) && defined(__s390__) && defined(__linux__) +# include "platform/switch_s390_unix.h" /* Linux/S390 */ +#elif defined(__GNUC__) && defined(__s390x__) && defined(__linux__) +# include "platform/switch_s390_unix.h" /* Linux/S390 zSeries (64-bit) */ +#elif defined(__GNUC__) && defined(__arm__) +# ifdef __APPLE__ +# include +# endif +# if TARGET_OS_IPHONE +# include "platform/switch_arm32_ios.h" /* iPhone OS on arm32 */ +# else +# include "platform/switch_arm32_gcc.h" /* gcc using arm32 */ +# endif +#elif defined(__GNUC__) && defined(__mips__) && defined(__linux__) +# include "platform/switch_mips_unix.h" /* Linux/MIPS */ +#elif defined(__GNUC__) && defined(__aarch64__) +# include "platform/switch_aarch64_gcc.h" /* Aarch64 ABI */ +#elif defined(__GNUC__) && defined(__mc68000__) +# include "platform/switch_m68k_gcc.h" /* gcc on m68k */ +#elif defined(__GNUC__) && defined(__csky__) +#include "platform/switch_csky_gcc.h" /* gcc on csky */ +# elif defined(__GNUC__) && defined(__riscv) +# include "platform/switch_riscv_unix.h" /* gcc on RISC-V */ +#elif defined(__GNUC__) && defined(__alpha__) +# include "platform/switch_alpha_unix.h" /* gcc on DEC Alpha */ +#elif defined(MS_WIN32) && defined(__llvm__) && defined(__aarch64__) +# include "platform/switch_aarch64_gcc.h" /* LLVM Aarch64 ABI for Windows */ +#elif defined(__GNUC__) && defined(__loongarch64) && defined(__linux__) +# include "platform/switch_loongarch64_linux.h" /* LoongArch64 */ +#elif defined(__GNUC__) && defined(__sh__) +# include "platform/switch_sh_gcc.h" /* SuperH */ +#endif + +#ifdef __cplusplus +}; +#endif diff --git a/python_embeded/Lib/site-packages/grpc/__init__.py b/python_embeded/Lib/site-packages/grpc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..635a351eb6de93ef04d766774270e12b2a01b793 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/__init__.py @@ -0,0 +1,2348 @@ +# Copyright 2015-2016 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""gRPC's Python API.""" + +import abc +import contextlib +import enum +import logging +import sys + +from grpc import _compression +from grpc._cython import cygrpc as _cygrpc +from grpc._runtime_protos import protos +from grpc._runtime_protos import protos_and_services +from grpc._runtime_protos import services + +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +try: + # pylint: disable=ungrouped-imports + from grpc._grpcio_metadata import __version__ +except ImportError: + __version__ = "dev0" + +############################## Future Interface ############################### + + +class FutureTimeoutError(Exception): + """Indicates that a method call on a Future timed out.""" + + +class FutureCancelledError(Exception): + """Indicates that the computation underlying a Future was cancelled.""" + + +class Future(abc.ABC): + """A representation of a computation in another control flow. + + Computations represented by a Future may be yet to be begun, + may be ongoing, or may have already completed. + """ + + @abc.abstractmethod + def cancel(self): + """Attempts to cancel the computation. + + This method does not block. + + Returns: + bool: + Returns True if the computation was canceled. + + Returns False under all other circumstances, for example: + + 1. computation has begun and could not be canceled. + 2. computation has finished + 3. computation is scheduled for execution and it is impossible + to determine its state without blocking. + """ + raise NotImplementedError() + + @abc.abstractmethod + def cancelled(self): + """Describes whether the computation was cancelled. + + This method does not block. + + Returns: + bool: + Returns True if the computation was cancelled before its result became + available. + + Returns False under all other circumstances, for example: + + 1. computation was not cancelled. + 2. computation's result is available. + """ + raise NotImplementedError() + + @abc.abstractmethod + def running(self): + """Describes whether the computation is taking place. + + This method does not block. + + Returns: + Returns True if the computation is scheduled for execution or + currently executing. + + Returns False if the computation already executed or was cancelled. + """ + raise NotImplementedError() + + @abc.abstractmethod + def done(self): + """Describes whether the computation has taken place. + + This method does not block. + + Returns: + bool: + Returns True if the computation already executed or was cancelled. + Returns False if the computation is scheduled for execution or + currently executing. + This is exactly opposite of the running() method's result. + """ + raise NotImplementedError() + + @abc.abstractmethod + def result(self, timeout=None): + """Returns the result of the computation or raises its exception. + + This method may return immediately or may block. + + Args: + timeout: The length of time in seconds to wait for the computation to + finish or be cancelled. If None, the call will block until the + computations's termination. + + Returns: + The return value of the computation. + + Raises: + FutureTimeoutError: If a timeout value is passed and the computation + does not terminate within the allotted time. + FutureCancelledError: If the computation was cancelled. + Exception: If the computation raised an exception, this call will + raise the same exception. + """ + raise NotImplementedError() + + @abc.abstractmethod + def exception(self, timeout=None): + """Return the exception raised by the computation. + + This method may return immediately or may block. + + Args: + timeout: The length of time in seconds to wait for the computation to + terminate or be cancelled. If None, the call will block until the + computations's termination. + + Returns: + The exception raised by the computation, or None if the computation + did not raise an exception. + + Raises: + FutureTimeoutError: If a timeout value is passed and the computation + does not terminate within the allotted time. + FutureCancelledError: If the computation was cancelled. + """ + raise NotImplementedError() + + @abc.abstractmethod + def traceback(self, timeout=None): + """Access the traceback of the exception raised by the computation. + + This method may return immediately or may block. + + Args: + timeout: The length of time in seconds to wait for the computation + to terminate or be cancelled. If None, the call will block until + the computation's termination. + + Returns: + The traceback of the exception raised by the computation, or None + if the computation did not raise an exception. + + Raises: + FutureTimeoutError: If a timeout value is passed and the computation + does not terminate within the allotted time. + FutureCancelledError: If the computation was cancelled. + """ + raise NotImplementedError() + + @abc.abstractmethod + def add_done_callback(self, fn): + """Adds a function to be called at completion of the computation. + + The callback will be passed this Future object describing the outcome + of the computation. Callbacks will be invoked after the future is + terminated, whether successfully or not. + + If the computation has already completed, the callback will be called + immediately. + + Exceptions raised in the callback will be logged at ERROR level, but + will not terminate any threads of execution. + + Args: + fn: A callable taking this Future object as its single parameter. + """ + raise NotImplementedError() + + +################################ gRPC Enums ################################## + + +@enum.unique +class ChannelConnectivity(enum.Enum): + """Mirrors grpc_connectivity_state in the gRPC Core. + + Attributes: + IDLE: The channel is idle. + CONNECTING: The channel is connecting. + READY: The channel is ready to conduct RPCs. + TRANSIENT_FAILURE: The channel has seen a failure from which it expects + to recover. + SHUTDOWN: The channel has seen a failure from which it cannot recover. + """ + + IDLE = (_cygrpc.ConnectivityState.idle, "idle") + CONNECTING = (_cygrpc.ConnectivityState.connecting, "connecting") + READY = (_cygrpc.ConnectivityState.ready, "ready") + TRANSIENT_FAILURE = ( + _cygrpc.ConnectivityState.transient_failure, + "transient failure", + ) + SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, "shutdown") + + +@enum.unique +class StatusCode(enum.Enum): + """Mirrors grpc_status_code in the gRPC Core. + + Attributes: + OK: Not an error; returned on success + CANCELLED: The operation was cancelled (typically by the caller). + UNKNOWN: Unknown error. + INVALID_ARGUMENT: Client specified an invalid argument. + DEADLINE_EXCEEDED: Deadline expired before operation could complete. + NOT_FOUND: Some requested entity (e.g., file or directory) was not found. + ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory) + already exists. + PERMISSION_DENIED: The caller does not have permission to execute the specified + operation. + UNAUTHENTICATED: The request does not have valid authentication credentials for the + operation. + RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or + perhaps the entire file system is out of space. + FAILED_PRECONDITION: Operation was rejected because the system is not in a state + required for the operation's execution. + ABORTED: The operation was aborted, typically due to a concurrency issue + like sequencer check failures, transaction aborts, etc. + UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service. + INTERNAL: Internal errors. Means some invariants expected by underlying + system has been broken. + UNAVAILABLE: The service is currently unavailable. + DATA_LOSS: Unrecoverable data loss or corruption. + """ + + OK = (_cygrpc.StatusCode.ok, "ok") + CANCELLED = (_cygrpc.StatusCode.cancelled, "cancelled") + UNKNOWN = (_cygrpc.StatusCode.unknown, "unknown") + INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, "invalid argument") + DEADLINE_EXCEEDED = ( + _cygrpc.StatusCode.deadline_exceeded, + "deadline exceeded", + ) + NOT_FOUND = (_cygrpc.StatusCode.not_found, "not found") + ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, "already exists") + PERMISSION_DENIED = ( + _cygrpc.StatusCode.permission_denied, + "permission denied", + ) + RESOURCE_EXHAUSTED = ( + _cygrpc.StatusCode.resource_exhausted, + "resource exhausted", + ) + FAILED_PRECONDITION = ( + _cygrpc.StatusCode.failed_precondition, + "failed precondition", + ) + ABORTED = (_cygrpc.StatusCode.aborted, "aborted") + OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, "out of range") + UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, "unimplemented") + INTERNAL = (_cygrpc.StatusCode.internal, "internal") + UNAVAILABLE = (_cygrpc.StatusCode.unavailable, "unavailable") + DATA_LOSS = (_cygrpc.StatusCode.data_loss, "data loss") + UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, "unauthenticated") + + +############################# gRPC Status ################################ + + +class Status(abc.ABC): + """Describes the status of an RPC. + + This is an EXPERIMENTAL API. + + Attributes: + code: A StatusCode object to be sent to the client. + details: A UTF-8-encodable string to be sent to the client upon + termination of the RPC. + trailing_metadata: The trailing :term:`metadata` in the RPC. + """ + + +############################# gRPC Exceptions ################################ + + +class RpcError(Exception): + """Raised by the gRPC library to indicate non-OK-status RPC termination.""" + + +############################## Shared Context ################################ + + +class RpcContext(abc.ABC): + """Provides RPC-related information and action.""" + + @abc.abstractmethod + def is_active(self): + """Describes whether the RPC is active or has terminated. + + Returns: + bool: + True if RPC is active, False otherwise. + """ + raise NotImplementedError() + + @abc.abstractmethod + def time_remaining(self): + """Describes the length of allowed time remaining for the RPC. + + Returns: + A nonnegative float indicating the length of allowed time in seconds + remaining for the RPC to complete before it is considered to have + timed out, or None if no deadline was specified for the RPC. + """ + raise NotImplementedError() + + @abc.abstractmethod + def cancel(self): + """Cancels the RPC. + + Idempotent and has no effect if the RPC has already terminated. + """ + raise NotImplementedError() + + @abc.abstractmethod + def add_callback(self, callback): + """Registers a callback to be called on RPC termination. + + Args: + callback: A no-parameter callable to be called on RPC termination. + + Returns: + True if the callback was added and will be called later; False if + the callback was not added and will not be called (because the RPC + already terminated or some other reason). + """ + raise NotImplementedError() + + +######################### Invocation-Side Context ############################ + + +class Call(RpcContext, metaclass=abc.ABCMeta): + """Invocation-side utility object for an RPC.""" + + @abc.abstractmethod + def initial_metadata(self): + """Accesses the initial metadata sent by the server. + + This method blocks until the value is available. + + Returns: + The initial :term:`metadata`. + """ + raise NotImplementedError() + + @abc.abstractmethod + def trailing_metadata(self): + """Accesses the trailing metadata sent by the server. + + This method blocks until the value is available. + + Returns: + The trailing :term:`metadata`. + """ + raise NotImplementedError() + + @abc.abstractmethod + def code(self): + """Accesses the status code sent by the server. + + This method blocks until the value is available. + + Returns: + The StatusCode value for the RPC. + """ + raise NotImplementedError() + + @abc.abstractmethod + def details(self): + """Accesses the details sent by the server. + + This method blocks until the value is available. + + Returns: + The details string of the RPC. + """ + raise NotImplementedError() + + +############## Invocation-Side Interceptor Interfaces & Classes ############## + + +class ClientCallDetails(abc.ABC): + """Describes an RPC to be invoked. + + Attributes: + method: The method name of the RPC. + timeout: An optional duration of time in seconds to allow for the RPC. + metadata: Optional :term:`metadata` to be transmitted to + the service-side of the RPC. + credentials: An optional CallCredentials for the RPC. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + """ + + +class UnaryUnaryClientInterceptor(abc.ABC): + """Affords intercepting unary-unary invocations.""" + + @abc.abstractmethod + def intercept_unary_unary(self, continuation, client_call_details, request): + """Intercepts a unary-unary invocation asynchronously. + + Args: + continuation: A function that proceeds with the invocation by + executing the next interceptor in chain or invoking the + actual RPC on the underlying Channel. It is the interceptor's + responsibility to call it if it decides to move the RPC forward. + The interceptor can use + `response_future = continuation(client_call_details, request)` + to continue with the RPC. `continuation` returns an object that is + both a Call for the RPC and a Future. In the event of RPC + completion, the return Call-Future's result value will be + the response message of the RPC. Should the event terminate + with non-OK status, the returned Call-Future's exception value + will be an RpcError. + client_call_details: A ClientCallDetails object describing the + outgoing RPC. + request: The request value for the RPC. + + Returns: + An object that is both a Call for the RPC and a Future. + In the event of RPC completion, the return Call-Future's + result value will be the response message of the RPC. + Should the event terminate with non-OK status, the returned + Call-Future's exception value will be an RpcError. + """ + raise NotImplementedError() + + +class UnaryStreamClientInterceptor(abc.ABC): + """Affords intercepting unary-stream invocations.""" + + @abc.abstractmethod + def intercept_unary_stream( + self, continuation, client_call_details, request + ): + """Intercepts a unary-stream invocation. + + Args: + continuation: A function that proceeds with the invocation by + executing the next interceptor in chain or invoking the + actual RPC on the underlying Channel. It is the interceptor's + responsibility to call it if it decides to move the RPC forward. + The interceptor can use + `response_iterator = continuation(client_call_details, request)` + to continue with the RPC. `continuation` returns an object that is + both a Call for the RPC and an iterator for response values. + Drawing response values from the returned Call-iterator may + raise RpcError indicating termination of the RPC with non-OK + status. + client_call_details: A ClientCallDetails object describing the + outgoing RPC. + request: The request value for the RPC. + + Returns: + An object that is both a Call for the RPC and an iterator of + response values. Drawing response values from the returned + Call-iterator may raise RpcError indicating termination of + the RPC with non-OK status. This object *should* also fulfill the + Future interface, though it may not. + """ + raise NotImplementedError() + + +class StreamUnaryClientInterceptor(abc.ABC): + """Affords intercepting stream-unary invocations.""" + + @abc.abstractmethod + def intercept_stream_unary( + self, continuation, client_call_details, request_iterator + ): + """Intercepts a stream-unary invocation asynchronously. + + Args: + continuation: A function that proceeds with the invocation by + executing the next interceptor in chain or invoking the + actual RPC on the underlying Channel. It is the interceptor's + responsibility to call it if it decides to move the RPC forward. + The interceptor can use + `response_future = continuation(client_call_details, request_iterator)` + to continue with the RPC. `continuation` returns an object that is + both a Call for the RPC and a Future. In the event of RPC completion, + the return Call-Future's result value will be the response message + of the RPC. Should the event terminate with non-OK status, the + returned Call-Future's exception value will be an RpcError. + client_call_details: A ClientCallDetails object describing the + outgoing RPC. + request_iterator: An iterator that yields request values for the RPC. + + Returns: + An object that is both a Call for the RPC and a Future. + In the event of RPC completion, the return Call-Future's + result value will be the response message of the RPC. + Should the event terminate with non-OK status, the returned + Call-Future's exception value will be an RpcError. + """ + raise NotImplementedError() + + +class StreamStreamClientInterceptor(abc.ABC): + """Affords intercepting stream-stream invocations.""" + + @abc.abstractmethod + def intercept_stream_stream( + self, continuation, client_call_details, request_iterator + ): + """Intercepts a stream-stream invocation. + + Args: + continuation: A function that proceeds with the invocation by + executing the next interceptor in chain or invoking the + actual RPC on the underlying Channel. It is the interceptor's + responsibility to call it if it decides to move the RPC forward. + The interceptor can use + `response_iterator = continuation(client_call_details, request_iterator)` + to continue with the RPC. `continuation` returns an object that is + both a Call for the RPC and an iterator for response values. + Drawing response values from the returned Call-iterator may + raise RpcError indicating termination of the RPC with non-OK + status. + client_call_details: A ClientCallDetails object describing the + outgoing RPC. + request_iterator: An iterator that yields request values for the RPC. + + Returns: + An object that is both a Call for the RPC and an iterator of + response values. Drawing response values from the returned + Call-iterator may raise RpcError indicating termination of + the RPC with non-OK status. This object *should* also fulfill the + Future interface, though it may not. + """ + raise NotImplementedError() + + +############ Authentication & Authorization Interfaces & Classes ############# + + +class ChannelCredentials(object): + """An encapsulation of the data required to create a secure Channel. + + This class has no supported interface - it exists to define the type of its + instances and its instances exist to be passed to other functions. For + example, ssl_channel_credentials returns an instance of this class and + secure_channel requires an instance of this class. + """ + + def __init__(self, credentials): + self._credentials = credentials + + +class CallCredentials(object): + """An encapsulation of the data required to assert an identity over a call. + + A CallCredentials has to be used with secure Channel, otherwise the + metadata will not be transmitted to the server. + + A CallCredentials may be composed with ChannelCredentials to always assert + identity for every call over that Channel. + + This class has no supported interface - it exists to define the type of its + instances and its instances exist to be passed to other functions. + """ + + def __init__(self, credentials): + self._credentials = credentials + + +class AuthMetadataContext(abc.ABC): + """Provides information to call credentials metadata plugins. + + Attributes: + service_url: A string URL of the service being called into. + method_name: A string of the fully qualified method name being called. + """ + + +class AuthMetadataPluginCallback(abc.ABC): + """Callback object received by a metadata plugin.""" + + def __call__(self, metadata, error): + """Passes to the gRPC runtime authentication metadata for an RPC. + + Args: + metadata: The :term:`metadata` used to construct the CallCredentials. + error: An Exception to indicate error or None to indicate success. + """ + raise NotImplementedError() + + +class AuthMetadataPlugin(abc.ABC): + """A specification for custom authentication.""" + + def __call__(self, context, callback): + """Implements authentication by passing metadata to a callback. + + This method will be invoked asynchronously in a separate thread. + + Args: + context: An AuthMetadataContext providing information on the RPC that + the plugin is being called to authenticate. + callback: An AuthMetadataPluginCallback to be invoked either + synchronously or asynchronously. + """ + raise NotImplementedError() + + +class ServerCredentials(object): + """An encapsulation of the data required to open a secure port on a Server. + + This class has no supported interface - it exists to define the type of its + instances and its instances exist to be passed to other functions. + """ + + def __init__(self, credentials): + self._credentials = credentials + + +class ServerCertificateConfiguration(object): + """A certificate configuration for use with an SSL-enabled Server. + + Instances of this class can be returned in the certificate configuration + fetching callback. + + This class has no supported interface -- it exists to define the + type of its instances and its instances exist to be passed to + other functions. + """ + + def __init__(self, certificate_configuration): + self._certificate_configuration = certificate_configuration + + +######################## Multi-Callable Interfaces ########################### + + +class UnaryUnaryMultiCallable(abc.ABC): + """Affords invoking a unary-unary RPC from client-side.""" + + @abc.abstractmethod + def __call__( + self, + request, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Synchronously invokes the underlying RPC. + + Args: + request: The request value for the RPC. + timeout: An optional duration of time in seconds to allow + for the RPC. + metadata: Optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + The response value for the RPC. + + Raises: + RpcError: Indicating that the RPC terminated with non-OK status. The + raised RpcError will also be a Call for the RPC affording the RPC's + metadata, status code, and details. + """ + raise NotImplementedError() + + @abc.abstractmethod + def with_call( + self, + request, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Synchronously invokes the underlying RPC. + + Args: + request: The request value for the RPC. + timeout: An optional durating of time in seconds to allow for + the RPC. + metadata: Optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + The response value for the RPC and a Call value for the RPC. + + Raises: + RpcError: Indicating that the RPC terminated with non-OK status. The + raised RpcError will also be a Call for the RPC affording the RPC's + metadata, status code, and details. + """ + raise NotImplementedError() + + @abc.abstractmethod + def future( + self, + request, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Asynchronously invokes the underlying RPC. + + Args: + request: The request value for the RPC. + timeout: An optional duration of time in seconds to allow for + the RPC. + metadata: Optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + An object that is both a Call for the RPC and a Future. + In the event of RPC completion, the return Call-Future's result + value will be the response message of the RPC. + Should the event terminate with non-OK status, + the returned Call-Future's exception value will be an RpcError. + """ + raise NotImplementedError() + + +class UnaryStreamMultiCallable(abc.ABC): + """Affords invoking a unary-stream RPC from client-side.""" + + @abc.abstractmethod + def __call__( + self, + request, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Invokes the underlying RPC. + + Args: + request: The request value for the RPC. + timeout: An optional duration of time in seconds to allow for + the RPC. If None, the timeout is considered infinite. + metadata: An optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + An object that is a Call for the RPC, an iterator of response + values, and a Future for the RPC. Drawing response values from the + returned Call-iterator may raise RpcError indicating termination of + the RPC with non-OK status. + """ + raise NotImplementedError() + + +class StreamUnaryMultiCallable(abc.ABC): + """Affords invoking a stream-unary RPC from client-side.""" + + @abc.abstractmethod + def __call__( + self, + request_iterator, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Synchronously invokes the underlying RPC. + + Args: + request_iterator: An iterator that yields request values for + the RPC. + timeout: An optional duration of time in seconds to allow for + the RPC. If None, the timeout is considered infinite. + metadata: Optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + The response value for the RPC. + + Raises: + RpcError: Indicating that the RPC terminated with non-OK status. The + raised RpcError will also implement grpc.Call, affording methods + such as metadata, code, and details. + """ + raise NotImplementedError() + + @abc.abstractmethod + def with_call( + self, + request_iterator, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Synchronously invokes the underlying RPC on the client. + + Args: + request_iterator: An iterator that yields request values for + the RPC. + timeout: An optional duration of time in seconds to allow for + the RPC. If None, the timeout is considered infinite. + metadata: Optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + The response value for the RPC and a Call object for the RPC. + + Raises: + RpcError: Indicating that the RPC terminated with non-OK status. The + raised RpcError will also be a Call for the RPC affording the RPC's + metadata, status code, and details. + """ + raise NotImplementedError() + + @abc.abstractmethod + def future( + self, + request_iterator, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Asynchronously invokes the underlying RPC on the client. + + Args: + request_iterator: An iterator that yields request values for the RPC. + timeout: An optional duration of time in seconds to allow for + the RPC. If None, the timeout is considered infinite. + metadata: Optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + An object that is both a Call for the RPC and a Future. + In the event of RPC completion, the return Call-Future's result value + will be the response message of the RPC. Should the event terminate + with non-OK status, the returned Call-Future's exception value will + be an RpcError. + """ + raise NotImplementedError() + + +class StreamStreamMultiCallable(abc.ABC): + """Affords invoking a stream-stream RPC on client-side.""" + + @abc.abstractmethod + def __call__( + self, + request_iterator, + timeout=None, + metadata=None, + credentials=None, + wait_for_ready=None, + compression=None, + ): + """Invokes the underlying RPC on the client. + + Args: + request_iterator: An iterator that yields request values for the RPC. + timeout: An optional duration of time in seconds to allow for + the RPC. If not specified, the timeout is considered infinite. + metadata: Optional :term:`metadata` to be transmitted to the + service-side of the RPC. + credentials: An optional CallCredentials for the RPC. Only valid for + secure Channel. + wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + + Returns: + An object that is a Call for the RPC, an iterator of response + values, and a Future for the RPC. Drawing response values from the + returned Call-iterator may raise RpcError indicating termination of + the RPC with non-OK status. + """ + raise NotImplementedError() + + +############################# Channel Interface ############################## + + +class Channel(abc.ABC): + """Affords RPC invocation via generic methods on client-side. + + Channel objects implement the Context Manager type, although they need not + support being entered and exited multiple times. + """ + + @abc.abstractmethod + def subscribe(self, callback, try_to_connect=False): + """Subscribe to this Channel's connectivity state machine. + + A Channel may be in any of the states described by ChannelConnectivity. + This method allows application to monitor the state transitions. + The typical use case is to debug or gain better visibility into gRPC + runtime's state. + + Args: + callback: A callable to be invoked with ChannelConnectivity argument. + ChannelConnectivity describes current state of the channel. + The callable will be invoked immediately upon subscription + and again for every change to ChannelConnectivity until it + is unsubscribed or this Channel object goes out of scope. + try_to_connect: A boolean indicating whether or not this Channel + should attempt to connect immediately. If set to False, gRPC + runtime decides when to connect. + """ + raise NotImplementedError() + + @abc.abstractmethod + def unsubscribe(self, callback): + """Unsubscribes a subscribed callback from this Channel's connectivity. + + Args: + callback: A callable previously registered with this Channel from + having been passed to its "subscribe" method. + """ + raise NotImplementedError() + + @abc.abstractmethod + def unary_unary( + self, + method, + request_serializer=None, + response_deserializer=None, + _registered_method=False, + ): + """Creates a UnaryUnaryMultiCallable for a unary-unary method. + + Args: + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the + response message. Response goes undeserialized in case None + is passed. + _registered_method: Implementation Private. A bool representing whether the method + is registered. + + Returns: + A UnaryUnaryMultiCallable value for the named unary-unary method. + """ + raise NotImplementedError() + + @abc.abstractmethod + def unary_stream( + self, + method, + request_serializer=None, + response_deserializer=None, + _registered_method=False, + ): + """Creates a UnaryStreamMultiCallable for a unary-stream method. + + Args: + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the + response message. Response goes undeserialized in case None is + passed. + _registered_method: Implementation Private. A bool representing whether the method + is registered. + + Returns: + A UnaryStreamMultiCallable value for the name unary-stream method. + """ + raise NotImplementedError() + + @abc.abstractmethod + def stream_unary( + self, + method, + request_serializer=None, + response_deserializer=None, + _registered_method=False, + ): + """Creates a StreamUnaryMultiCallable for a stream-unary method. + + Args: + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the + response message. Response goes undeserialized in case None is + passed. + _registered_method: Implementation Private. A bool representing whether the method + is registered. + + Returns: + A StreamUnaryMultiCallable value for the named stream-unary method. + """ + raise NotImplementedError() + + @abc.abstractmethod + def stream_stream( + self, + method, + request_serializer=None, + response_deserializer=None, + _registered_method=False, + ): + """Creates a StreamStreamMultiCallable for a stream-stream method. + + Args: + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the + response message. Response goes undeserialized in case None + is passed. + _registered_method: Implementation Private. A bool representing whether the method + is registered. + + Returns: + A StreamStreamMultiCallable value for the named stream-stream method. + """ + raise NotImplementedError() + + @abc.abstractmethod + def close(self): + """Closes this Channel and releases all resources held by it. + + Closing the Channel will immediately terminate all RPCs active with the + Channel and it is not valid to invoke new RPCs with the Channel. + + This method is idempotent. + """ + raise NotImplementedError() + + def __enter__(self): + """Enters the runtime context related to the channel object.""" + raise NotImplementedError() + + def __exit__(self, exc_type, exc_val, exc_tb): + """Exits the runtime context related to the channel object.""" + raise NotImplementedError() + + +########################## Service-Side Context ############################## + + +class ServicerContext(RpcContext, metaclass=abc.ABCMeta): + """A context object passed to method implementations.""" + + @abc.abstractmethod + def invocation_metadata(self): + """Accesses the metadata sent by the client. + + Returns: + The invocation :term:`metadata`. + """ + raise NotImplementedError() + + @abc.abstractmethod + def peer(self): + """Identifies the peer that invoked the RPC being serviced. + + Returns: + A string identifying the peer that invoked the RPC being serviced. + The string format is determined by gRPC runtime. + """ + raise NotImplementedError() + + @abc.abstractmethod + def peer_identities(self): + """Gets one or more peer identity(s). + + Equivalent to + servicer_context.auth_context().get(servicer_context.peer_identity_key()) + + Returns: + An iterable of the identities, or None if the call is not + authenticated. Each identity is returned as a raw bytes type. + """ + raise NotImplementedError() + + @abc.abstractmethod + def peer_identity_key(self): + """The auth property used to identify the peer. + + For example, "x509_common_name" or "x509_subject_alternative_name" are + used to identify an SSL peer. + + Returns: + The auth property (string) that indicates the + peer identity, or None if the call is not authenticated. + """ + raise NotImplementedError() + + @abc.abstractmethod + def auth_context(self): + """Gets the auth context for the call. + + Returns: + A map of strings to an iterable of bytes for each auth property. + """ + raise NotImplementedError() + + def set_compression(self, compression): + """Set the compression algorithm to be used for the entire call. + + Args: + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + """ + raise NotImplementedError() + + @abc.abstractmethod + def send_initial_metadata(self, initial_metadata): + """Sends the initial metadata value to the client. + + This method need not be called by implementations if they have no + metadata to add to what the gRPC runtime will transmit. + + Args: + initial_metadata: The initial :term:`metadata`. + """ + raise NotImplementedError() + + @abc.abstractmethod + def set_trailing_metadata(self, trailing_metadata): + """Sets the trailing metadata for the RPC. + + Sets the trailing metadata to be sent upon completion of the RPC. + + If this method is invoked multiple times throughout the lifetime of an + RPC, the value supplied in the final invocation will be the value sent + over the wire. + + This method need not be called by implementations if they have no + metadata to add to what the gRPC runtime will transmit. + + Args: + trailing_metadata: The trailing :term:`metadata`. + """ + raise NotImplementedError() + + def trailing_metadata(self): + """Access value to be used as trailing metadata upon RPC completion. + + This is an EXPERIMENTAL API. + + Returns: + The trailing :term:`metadata` for the RPC. + """ + raise NotImplementedError() + + @abc.abstractmethod + def abort(self, code, details): + """Raises an exception to terminate the RPC with a non-OK status. + + The code and details passed as arguments will supersede any existing + ones. + + Args: + code: A StatusCode object to be sent to the client. + It must not be StatusCode.OK. + details: A UTF-8-encodable string to be sent to the client upon + termination of the RPC. + + Raises: + Exception: An exception is always raised to signal the abortion the + RPC to the gRPC runtime. + """ + raise NotImplementedError() + + @abc.abstractmethod + def abort_with_status(self, status): + """Raises an exception to terminate the RPC with a non-OK status. + + The status passed as argument will supersede any existing status code, + status message and trailing metadata. + + This is an EXPERIMENTAL API. + + Args: + status: A grpc.Status object. The status code in it must not be + StatusCode.OK. + + Raises: + Exception: An exception is always raised to signal the abortion the + RPC to the gRPC runtime. + """ + raise NotImplementedError() + + @abc.abstractmethod + def set_code(self, code): + """Sets the value to be used as status code upon RPC completion. + + This method need not be called by method implementations if they wish + the gRPC runtime to determine the status code of the RPC. + + Args: + code: A StatusCode object to be sent to the client. + """ + raise NotImplementedError() + + @abc.abstractmethod + def set_details(self, details): + """Sets the value to be used as detail string upon RPC completion. + + This method need not be called by method implementations if they have + no details to transmit. + + Args: + details: A UTF-8-encodable string to be sent to the client upon + termination of the RPC. + """ + raise NotImplementedError() + + def code(self): + """Accesses the value to be used as status code upon RPC completion. + + This is an EXPERIMENTAL API. + + Returns: + The StatusCode value for the RPC. + """ + raise NotImplementedError() + + def details(self): + """Accesses the value to be used as detail string upon RPC completion. + + This is an EXPERIMENTAL API. + + Returns: + The details string of the RPC. + """ + raise NotImplementedError() + + def disable_next_message_compression(self): + """Disables compression for the next response message. + + This method will override any compression configuration set during + server creation or set on the call. + """ + raise NotImplementedError() + + +##################### Service-Side Handler Interfaces ######################## + + +class RpcMethodHandler(abc.ABC): + """An implementation of a single RPC method. + + Attributes: + request_streaming: Whether the RPC supports exactly one request message + or any arbitrary number of request messages. + response_streaming: Whether the RPC supports exactly one response message + or any arbitrary number of response messages. + request_deserializer: A callable :term:`deserializer` that accepts a byte string and + returns an object suitable to be passed to this object's business + logic, or None to indicate that this object's business logic should be + passed the raw request bytes. + response_serializer: A callable :term:`serializer` that accepts an object produced + by this object's business logic and returns a byte string, or None to + indicate that the byte strings produced by this object's business logic + should be transmitted on the wire as they are. + unary_unary: This object's application-specific business logic as a + callable value that takes a request value and a ServicerContext object + and returns a response value. Only non-None if both request_streaming + and response_streaming are False. + unary_stream: This object's application-specific business logic as a + callable value that takes a request value and a ServicerContext object + and returns an iterator of response values. Only non-None if + request_streaming is False and response_streaming is True. + stream_unary: This object's application-specific business logic as a + callable value that takes an iterator of request values and a + ServicerContext object and returns a response value. Only non-None if + request_streaming is True and response_streaming is False. + stream_stream: This object's application-specific business logic as a + callable value that takes an iterator of request values and a + ServicerContext object and returns an iterator of response values. + Only non-None if request_streaming and response_streaming are both + True. + """ + + +class HandlerCallDetails(abc.ABC): + """Describes an RPC that has just arrived for service. + + Attributes: + method: The method name of the RPC. + invocation_metadata: The :term:`metadata` sent by the client. + """ + + +class GenericRpcHandler(abc.ABC): + """An implementation of arbitrarily many RPC methods.""" + + @abc.abstractmethod + def service(self, handler_call_details): + """Returns the handler for servicing the RPC. + + Args: + handler_call_details: A HandlerCallDetails describing the RPC. + + Returns: + An RpcMethodHandler with which the RPC may be serviced if the + implementation chooses to service this RPC, or None otherwise. + """ + raise NotImplementedError() + + +class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta): + """An implementation of RPC methods belonging to a service. + + A service handles RPC methods with structured names of the form + '/Service.Name/Service.Method', where 'Service.Name' is the value + returned by service_name(), and 'Service.Method' is the method + name. A service can have multiple method names, but only a single + service name. + """ + + @abc.abstractmethod + def service_name(self): + """Returns this service's name. + + Returns: + The service name. + """ + raise NotImplementedError() + + +#################### Service-Side Interceptor Interfaces ##################### + + +class ServerInterceptor(abc.ABC): + """Affords intercepting incoming RPCs on the service-side.""" + + @abc.abstractmethod + def intercept_service(self, continuation, handler_call_details): + """Intercepts incoming RPCs before handing them over to a handler. + + State can be passed from an interceptor to downstream interceptors + via contextvars. The first interceptor is called from an empty + contextvars.Context, and the same Context is used for downstream + interceptors and for the final handler call. Note that there are no + guarantees that interceptors and handlers will be called from the + same thread. + + Args: + continuation: A function that takes a HandlerCallDetails and + proceeds to invoke the next interceptor in the chain, if any, + or the RPC handler lookup logic, with the call details passed + as an argument, and returns an RpcMethodHandler instance if + the RPC is considered serviced, or None otherwise. + handler_call_details: A HandlerCallDetails describing the RPC. + + Returns: + An RpcMethodHandler with which the RPC may be serviced if the + interceptor chooses to service this RPC, or None otherwise. + """ + raise NotImplementedError() + + +############################# Server Interface ############################### + + +class Server(abc.ABC): + """Services RPCs.""" + + @abc.abstractmethod + def add_generic_rpc_handlers(self, generic_rpc_handlers): + """Registers GenericRpcHandlers with this Server. + + This method is only safe to call before the server is started. + + Args: + generic_rpc_handlers: An iterable of GenericRpcHandlers that will be + used to service RPCs. + """ + raise NotImplementedError() + + def add_registered_method_handlers(self, service_name, method_handlers): + """Registers GenericRpcHandlers with this Server. + + This method is only safe to call before the server is started. + + If the same method have both generic and registered handler, + registered handler will take precedence. + + Args: + service_name: The service name. + method_handlers: A dictionary that maps method names to corresponding + RpcMethodHandler. + """ + + @abc.abstractmethod + def add_insecure_port(self, address): + """Opens an insecure port for accepting RPCs. + + This method may only be called before starting the server. + + Args: + address: The address for which to open a port. If the port is 0, + or not specified in the address, then gRPC runtime will choose a port. + + Returns: + An integer port on which server will accept RPC requests. + """ + raise NotImplementedError() + + @abc.abstractmethod + def add_secure_port(self, address, server_credentials): + """Opens a secure port for accepting RPCs. + + This method may only be called before starting the server. + + Args: + address: The address for which to open a port. + if the port is 0, or not specified in the address, then gRPC + runtime will choose a port. + server_credentials: A ServerCredentials object. + + Returns: + An integer port on which server will accept RPC requests. + """ + raise NotImplementedError() + + @abc.abstractmethod + def start(self): + """Starts this Server. + + This method may only be called once. (i.e. it is not idempotent). + """ + raise NotImplementedError() + + @abc.abstractmethod + def stop(self, grace): + """Stops this Server. + + This method immediately stop service of new RPCs in all cases. + + If a grace period is specified, this method waits until all active + RPCs are finished or until the grace period is reached. RPCs that haven't + been terminated within the grace period are aborted. + If a grace period is not specified (by passing None for `grace`), + all existing RPCs are aborted immediately and this method + blocks until the last RPC handler terminates. + + This method is idempotent and may be called at any time. + Passing a smaller grace value in a subsequent call will have + the effect of stopping the Server sooner (passing None will + have the effect of stopping the server immediately). Passing + a larger grace value in a subsequent call *will not* have the + effect of stopping the server later (i.e. the most restrictive + grace value is used). + + Args: + grace: A duration of time in seconds or None. + + Returns: + A threading.Event that will be set when this Server has completely + stopped, i.e. when running RPCs either complete or are aborted and + all handlers have terminated. + """ + raise NotImplementedError() + + def wait_for_termination(self, timeout=None): + """Block current thread until the server stops. + + This is an EXPERIMENTAL API. + + The wait will not consume computational resources during blocking, and + it will block until one of the two following conditions are met: + + 1) The server is stopped or terminated; + 2) A timeout occurs if timeout is not `None`. + + The timeout argument works in the same way as `threading.Event.wait()`. + https://docs.python.org/3/library/threading.html#threading.Event.wait + + Args: + timeout: A floating point number specifying a timeout for the + operation in seconds. + + Returns: + A bool indicates if the operation times out. + """ + raise NotImplementedError() + + +################################# Functions ################################ + + +def unary_unary_rpc_method_handler( + behavior, request_deserializer=None, response_serializer=None +): + """Creates an RpcMethodHandler for a unary-unary RPC method. + + Args: + behavior: The implementation of an RPC that accepts one request + and returns one response. + request_deserializer: An optional :term:`deserializer` for request deserialization. + response_serializer: An optional :term:`serializer` for response serialization. + + Returns: + An RpcMethodHandler object that is typically used by grpc.Server. + """ + from grpc import _utilities # pylint: disable=cyclic-import + + return _utilities.RpcMethodHandler( + False, + False, + request_deserializer, + response_serializer, + behavior, + None, + None, + None, + ) + + +def unary_stream_rpc_method_handler( + behavior, request_deserializer=None, response_serializer=None +): + """Creates an RpcMethodHandler for a unary-stream RPC method. + + Args: + behavior: The implementation of an RPC that accepts one request + and returns an iterator of response values. + request_deserializer: An optional :term:`deserializer` for request deserialization. + response_serializer: An optional :term:`serializer` for response serialization. + + Returns: + An RpcMethodHandler object that is typically used by grpc.Server. + """ + from grpc import _utilities # pylint: disable=cyclic-import + + return _utilities.RpcMethodHandler( + False, + True, + request_deserializer, + response_serializer, + None, + behavior, + None, + None, + ) + + +def stream_unary_rpc_method_handler( + behavior, request_deserializer=None, response_serializer=None +): + """Creates an RpcMethodHandler for a stream-unary RPC method. + + Args: + behavior: The implementation of an RPC that accepts an iterator of + request values and returns a single response value. + request_deserializer: An optional :term:`deserializer` for request deserialization. + response_serializer: An optional :term:`serializer` for response serialization. + + Returns: + An RpcMethodHandler object that is typically used by grpc.Server. + """ + from grpc import _utilities # pylint: disable=cyclic-import + + return _utilities.RpcMethodHandler( + True, + False, + request_deserializer, + response_serializer, + None, + None, + behavior, + None, + ) + + +def stream_stream_rpc_method_handler( + behavior, request_deserializer=None, response_serializer=None +): + """Creates an RpcMethodHandler for a stream-stream RPC method. + + Args: + behavior: The implementation of an RPC that accepts an iterator of + request values and returns an iterator of response values. + request_deserializer: An optional :term:`deserializer` for request deserialization. + response_serializer: An optional :term:`serializer` for response serialization. + + Returns: + An RpcMethodHandler object that is typically used by grpc.Server. + """ + from grpc import _utilities # pylint: disable=cyclic-import + + return _utilities.RpcMethodHandler( + True, + True, + request_deserializer, + response_serializer, + None, + None, + None, + behavior, + ) + + +def method_handlers_generic_handler(service, method_handlers): + """Creates a GenericRpcHandler from RpcMethodHandlers. + + Args: + service: The name of the service that is implemented by the + method_handlers. + method_handlers: A dictionary that maps method names to corresponding + RpcMethodHandler. + + Returns: + A GenericRpcHandler. This is typically added to the grpc.Server object + with add_generic_rpc_handlers() before starting the server. + """ + from grpc import _utilities # pylint: disable=cyclic-import + + return _utilities.DictionaryGenericHandler(service, method_handlers) + + +def ssl_channel_credentials( + root_certificates=None, private_key=None, certificate_chain=None +): + """Creates a ChannelCredentials for use with an SSL-enabled Channel. + + Args: + root_certificates: The PEM-encoded root certificates as a byte string, + or None to retrieve them from a default location chosen by gRPC + runtime. + private_key: The PEM-encoded private key as a byte string, or None if no + private key should be used. + certificate_chain: The PEM-encoded certificate chain as a byte string + to use or None if no certificate chain should be used. + + Returns: + A ChannelCredentials for use with an SSL-enabled Channel. + """ + return ChannelCredentials( + _cygrpc.SSLChannelCredentials( + root_certificates, private_key, certificate_chain + ) + ) + + +def xds_channel_credentials(fallback_credentials=None): + """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL + API. + + Args: + fallback_credentials: Credentials to use in case it is not possible to + establish a secure connection via xDS. If no fallback_credentials + argument is supplied, a default SSLChannelCredentials is used. + """ + fallback_credentials = ( + ssl_channel_credentials() + if fallback_credentials is None + else fallback_credentials + ) + return ChannelCredentials( + _cygrpc.XDSChannelCredentials(fallback_credentials._credentials) + ) + + +def metadata_call_credentials(metadata_plugin, name=None): + """Construct CallCredentials from an AuthMetadataPlugin. + + Args: + metadata_plugin: An AuthMetadataPlugin to use for authentication. + name: An optional name for the plugin. + + Returns: + A CallCredentials. + """ + from grpc import _plugin_wrapping # pylint: disable=cyclic-import + + return _plugin_wrapping.metadata_plugin_call_credentials( + metadata_plugin, name + ) + + +def access_token_call_credentials(access_token): + """Construct CallCredentials from an access token. + + Args: + access_token: A string to place directly in the http request + authorization header, for example + "authorization: Bearer ". + + Returns: + A CallCredentials. + """ + from grpc import _auth # pylint: disable=cyclic-import + from grpc import _plugin_wrapping # pylint: disable=cyclic-import + + return _plugin_wrapping.metadata_plugin_call_credentials( + _auth.AccessTokenAuthMetadataPlugin(access_token), None + ) + + +def composite_call_credentials(*call_credentials): + """Compose multiple CallCredentials to make a new CallCredentials. + + Args: + *call_credentials: At least two CallCredentials objects. + + Returns: + A CallCredentials object composed of the given CallCredentials objects. + """ + return CallCredentials( + _cygrpc.CompositeCallCredentials( + tuple( + single_call_credentials._credentials + for single_call_credentials in call_credentials + ) + ) + ) + + +def composite_channel_credentials(channel_credentials, *call_credentials): + """Compose a ChannelCredentials and one or more CallCredentials objects. + + Args: + channel_credentials: A ChannelCredentials object. + *call_credentials: One or more CallCredentials objects. + + Returns: + A ChannelCredentials composed of the given ChannelCredentials and + CallCredentials objects. + """ + return ChannelCredentials( + _cygrpc.CompositeChannelCredentials( + tuple( + single_call_credentials._credentials + for single_call_credentials in call_credentials + ), + channel_credentials._credentials, + ) + ) + + +def ssl_server_credentials( + private_key_certificate_chain_pairs, + root_certificates=None, + require_client_auth=False, +): + """Creates a ServerCredentials for use with an SSL-enabled Server. + + Args: + private_key_certificate_chain_pairs: A list of pairs of the form + [PEM-encoded private key, PEM-encoded certificate chain]. + root_certificates: An optional byte string of PEM-encoded client root + certificates that the server will use to verify client authentication. + If omitted, require_client_auth must also be False. + require_client_auth: A boolean indicating whether or not to require + clients to be authenticated. May only be True if root_certificates + is not None. + + Returns: + A ServerCredentials for use with an SSL-enabled Server. Typically, this + object is an argument to add_secure_port() method during server setup. + """ + if not private_key_certificate_chain_pairs: + raise ValueError( + "At least one private key-certificate chain pair is required!" + ) + elif require_client_auth and root_certificates is None: + raise ValueError( + "Illegal to require client auth without providing root" + " certificates!" + ) + else: + return ServerCredentials( + _cygrpc.server_credentials_ssl( + root_certificates, + [ + _cygrpc.SslPemKeyCertPair(key, pem) + for key, pem in private_key_certificate_chain_pairs + ], + require_client_auth, + ) + ) + + +def xds_server_credentials(fallback_credentials): + """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL + API. + + Args: + fallback_credentials: Credentials to use in case it is not possible to + establish a secure connection via xDS. No default value is provided. + """ + return ServerCredentials( + _cygrpc.xds_server_credentials(fallback_credentials._credentials) + ) + + +def insecure_server_credentials(): + """Creates a credentials object directing the server to use no credentials. + This is an EXPERIMENTAL API. + + This object cannot be used directly in a call to `add_secure_port`. + Instead, it should be used to construct other credentials objects, e.g. + with xds_server_credentials. + """ + return ServerCredentials(_cygrpc.insecure_server_credentials()) + + +def ssl_server_certificate_configuration( + private_key_certificate_chain_pairs, root_certificates=None +): + """Creates a ServerCertificateConfiguration for use with a Server. + + Args: + private_key_certificate_chain_pairs: A collection of pairs of + the form [PEM-encoded private key, PEM-encoded certificate + chain]. + root_certificates: An optional byte string of PEM-encoded client root + certificates that the server will use to verify client authentication. + + Returns: + A ServerCertificateConfiguration that can be returned in the certificate + configuration fetching callback. + """ + if private_key_certificate_chain_pairs: + return ServerCertificateConfiguration( + _cygrpc.server_certificate_config_ssl( + root_certificates, + [ + _cygrpc.SslPemKeyCertPair(key, pem) + for key, pem in private_key_certificate_chain_pairs + ], + ) + ) + else: + raise ValueError( + "At least one private key-certificate chain pair is required!" + ) + + +def dynamic_ssl_server_credentials( + initial_certificate_configuration, + certificate_configuration_fetcher, + require_client_authentication=False, +): + """Creates a ServerCredentials for use with an SSL-enabled Server. + + Args: + initial_certificate_configuration (ServerCertificateConfiguration): The + certificate configuration with which the server will be initialized. + certificate_configuration_fetcher (callable): A callable that takes no + arguments and should return a ServerCertificateConfiguration to + replace the server's current certificate, or None for no change + (i.e., the server will continue its current certificate + config). The library will call this callback on *every* new + client connection before starting the TLS handshake with the + client, thus allowing the user application to optionally + return a new ServerCertificateConfiguration that the server will then + use for the handshake. + require_client_authentication: A boolean indicating whether or not to + require clients to be authenticated. + + Returns: + A ServerCredentials. + """ + return ServerCredentials( + _cygrpc.server_credentials_ssl_dynamic_cert_config( + initial_certificate_configuration, + certificate_configuration_fetcher, + require_client_authentication, + ) + ) + + +@enum.unique +class LocalConnectionType(enum.Enum): + """Types of local connection for local credential creation. + + Attributes: + UDS: Unix domain socket connections + LOCAL_TCP: Local TCP connections. + """ + + UDS = _cygrpc.LocalConnectionType.uds + LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp + + +def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): + """Creates a local ChannelCredentials used for local connections. + + This is an EXPERIMENTAL API. + + Local credentials are used by local TCP endpoints (e.g. localhost:10000) + also UDS connections. + + The connections created by local channel credentials are not + encrypted, but will be checked if they are local or not. + The UDS connections are considered secure by providing peer authentication + and data confidentiality while TCP connections are considered insecure. + + It is allowed to transmit call credentials over connections created by + local channel credentials. + + Local channel credentials are useful for 1) eliminating insecure_channel usage; + 2) enable unit testing for call credentials without setting up secrets. + + Args: + local_connect_type: Local connection type (either + grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) + + Returns: + A ChannelCredentials for use with a local Channel + """ + return ChannelCredentials( + _cygrpc.channel_credentials_local(local_connect_type.value) + ) + + +def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP): + """Creates a local ServerCredentials used for local connections. + + This is an EXPERIMENTAL API. + + Local credentials are used by local TCP endpoints (e.g. localhost:10000) + also UDS connections. + + The connections created by local server credentials are not + encrypted, but will be checked if they are local or not. + The UDS connections are considered secure by providing peer authentication + and data confidentiality while TCP connections are considered insecure. + + It is allowed to transmit call credentials over connections created by local + server credentials. + + Local server credentials are useful for 1) eliminating insecure_channel usage; + 2) enable unit testing for call credentials without setting up secrets. + + Args: + local_connect_type: Local connection type (either + grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP) + + Returns: + A ServerCredentials for use with a local Server + """ + return ServerCredentials( + _cygrpc.server_credentials_local(local_connect_type.value) + ) + + +def alts_channel_credentials(service_accounts=None): + """Creates a ChannelCredentials for use with an ALTS-enabled Channel. + + This is an EXPERIMENTAL API. + ALTS credentials API can only be used in GCP environment as it relies on + handshaker service being available. For more info about ALTS see + https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security + + Args: + service_accounts: A list of server identities accepted by the client. + If target service accounts are provided and none of them matches the + peer identity of the server, handshake will fail. The arg can be empty + if the client does not have any information about trusted server + identity. + Returns: + A ChannelCredentials for use with an ALTS-enabled Channel + """ + return ChannelCredentials( + _cygrpc.channel_credentials_alts(service_accounts or []) + ) + + +def alts_server_credentials(): + """Creates a ServerCredentials for use with an ALTS-enabled connection. + + This is an EXPERIMENTAL API. + ALTS credentials API can only be used in GCP environment as it relies on + handshaker service being available. For more info about ALTS see + https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security + + Returns: + A ServerCredentials for use with an ALTS-enabled Server + """ + return ServerCredentials(_cygrpc.server_credentials_alts()) + + +def compute_engine_channel_credentials(call_credentials): + """Creates a compute engine channel credential. + + This credential can only be used in a GCP environment as it relies on + a handshaker service. For more info about ALTS, see + https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security + + This channel credential is expected to be used as part of a composite + credential in conjunction with a call credentials that authenticates the + VM's default service account. If used with any other sort of call + credential, the connection may suddenly and unexpectedly begin failing RPCs. + """ + return ChannelCredentials( + _cygrpc.channel_credentials_compute_engine( + call_credentials._credentials + ) + ) + + +def channel_ready_future(channel): + """Creates a Future that tracks when a Channel is ready. + + Cancelling the Future does not affect the channel's state machine. + It merely decouples the Future from channel state machine. + + Args: + channel: A Channel object. + + Returns: + A Future object that matures when the channel connectivity is + ChannelConnectivity.READY. + """ + from grpc import _utilities # pylint: disable=cyclic-import + + return _utilities.channel_ready_future(channel) + + +def insecure_channel(target, options=None, compression=None): + """Creates an insecure Channel to a server. + + The returned Channel is thread-safe. + + Args: + target: The server address + options: An optional list of key-value pairs (:term:`channel_arguments` + in gRPC Core runtime) to configure the channel. + compression: An optional value indicating the compression method to be + used over the lifetime of the channel. + + Returns: + A Channel. + """ + from grpc import _channel # pylint: disable=cyclic-import + + return _channel.Channel( + target, () if options is None else options, None, compression + ) + + +def secure_channel(target, credentials, options=None, compression=None): + """Creates a secure Channel to a server. + + The returned Channel is thread-safe. + + Args: + target: The server address. + credentials: A ChannelCredentials instance. + options: An optional list of key-value pairs (:term:`channel_arguments` + in gRPC Core runtime) to configure the channel. + compression: An optional value indicating the compression method to be + used over the lifetime of the channel. + + Returns: + A Channel. + """ + from grpc import _channel # pylint: disable=cyclic-import + from grpc.experimental import _insecure_channel_credentials + + if credentials._credentials is _insecure_channel_credentials: + raise ValueError( + "secure_channel cannot be called with insecure credentials." + + " Call insecure_channel instead." + ) + return _channel.Channel( + target, + () if options is None else options, + credentials._credentials, + compression, + ) + + +def intercept_channel(channel, *interceptors): + """Intercepts a channel through a set of interceptors. + + Args: + channel: A Channel. + interceptors: Zero or more objects of type + UnaryUnaryClientInterceptor, + UnaryStreamClientInterceptor, + StreamUnaryClientInterceptor, or + StreamStreamClientInterceptor. + Interceptors are given control in the order they are listed. + + Returns: + A Channel that intercepts each invocation via the provided interceptors. + + Raises: + TypeError: If interceptor does not derive from any of + UnaryUnaryClientInterceptor, + UnaryStreamClientInterceptor, + StreamUnaryClientInterceptor, or + StreamStreamClientInterceptor. + """ + from grpc import _interceptor # pylint: disable=cyclic-import + + return _interceptor.intercept_channel(channel, *interceptors) + + +def server( + thread_pool, + handlers=None, + interceptors=None, + options=None, + maximum_concurrent_rpcs=None, + compression=None, + xds=False, +): + """Creates a Server with which RPCs can be serviced. + + Args: + thread_pool: A futures.ThreadPoolExecutor to be used by the Server + to execute RPC handlers. + handlers: An optional list of GenericRpcHandlers used for executing RPCs. + More handlers may be added by calling add_generic_rpc_handlers any time + before the server is started. + interceptors: An optional list of ServerInterceptor objects that observe + and optionally manipulate the incoming RPCs before handing them over to + handlers. The interceptors are given control in the order they are + specified. This is an EXPERIMENTAL API. + options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) + to configure the channel. + maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server + will service before returning RESOURCE_EXHAUSTED status, or None to + indicate no limit. + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. This compression algorithm will be used for the + lifetime of the server unless overridden. + xds: If set to true, retrieves server configuration via xDS. This is an + EXPERIMENTAL option. + + Returns: + A Server object. + """ + from grpc import _server # pylint: disable=cyclic-import + + return _server.create_server( + thread_pool, + () if handlers is None else handlers, + () if interceptors is None else interceptors, + () if options is None else options, + maximum_concurrent_rpcs, + compression, + xds, + ) + + +@contextlib.contextmanager +def _create_servicer_context(rpc_event, state, request_deserializer): + from grpc import _server # pylint: disable=cyclic-import + + context = _server._Context(rpc_event, state, request_deserializer) + yield context + context._finalize_state() # pylint: disable=protected-access + + +@enum.unique +class Compression(enum.IntEnum): + """Indicates the compression method to be used for an RPC. + + Attributes: + NoCompression: Do not use compression algorithm. + Deflate: Use "Deflate" compression algorithm. + Gzip: Use "Gzip" compression algorithm. + """ + + NoCompression = _compression.NoCompression + Deflate = _compression.Deflate + Gzip = _compression.Gzip + + +################################### __all__ ################################# + +__all__ = ( + "FutureTimeoutError", + "FutureCancelledError", + "Future", + "ChannelConnectivity", + "StatusCode", + "Status", + "RpcError", + "RpcContext", + "Call", + "ChannelCredentials", + "CallCredentials", + "AuthMetadataContext", + "AuthMetadataPluginCallback", + "AuthMetadataPlugin", + "Compression", + "ClientCallDetails", + "ServerCertificateConfiguration", + "ServerCredentials", + "LocalConnectionType", + "UnaryUnaryMultiCallable", + "UnaryStreamMultiCallable", + "StreamUnaryMultiCallable", + "StreamStreamMultiCallable", + "UnaryUnaryClientInterceptor", + "UnaryStreamClientInterceptor", + "StreamUnaryClientInterceptor", + "StreamStreamClientInterceptor", + "Channel", + "ServicerContext", + "RpcMethodHandler", + "HandlerCallDetails", + "GenericRpcHandler", + "ServiceRpcHandler", + "Server", + "ServerInterceptor", + "unary_unary_rpc_method_handler", + "unary_stream_rpc_method_handler", + "stream_unary_rpc_method_handler", + "stream_stream_rpc_method_handler", + "method_handlers_generic_handler", + "ssl_channel_credentials", + "metadata_call_credentials", + "access_token_call_credentials", + "composite_call_credentials", + "composite_channel_credentials", + "compute_engine_channel_credentials", + "local_channel_credentials", + "local_server_credentials", + "alts_channel_credentials", + "alts_server_credentials", + "ssl_server_credentials", + "ssl_server_certificate_configuration", + "dynamic_ssl_server_credentials", + "channel_ready_future", + "insecure_channel", + "secure_channel", + "intercept_channel", + "server", + "protos", + "services", + "protos_and_services", + "xds_channel_credentials", + "xds_server_credentials", + "insecure_server_credentials", +) + +############################### Extension Shims ################################ + +# Here to maintain backwards compatibility; avoid using these in new code! +try: + import grpc_tools + + sys.modules.update({"grpc.tools": grpc_tools}) +except ImportError: + pass +try: + import grpc_health + + sys.modules.update({"grpc.health": grpc_health}) +except ImportError: + pass +try: + import grpc_reflection + + sys.modules.update({"grpc.reflection": grpc_reflection}) +except ImportError: + pass + +# Prevents import order issue in the case of renamed path. +if sys.version_info >= (3, 6) and __name__ == "grpc": + from grpc import aio # pylint: disable=ungrouped-imports + + sys.modules.update({"grpc.aio": aio}) diff --git a/python_embeded/Lib/site-packages/grpc/_auth.py b/python_embeded/Lib/site-packages/grpc/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..0af206f7f56a0b9faf8f2f4506b99b1f0fed647c --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_auth.py @@ -0,0 +1,80 @@ +# Copyright 2016 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""GRPCAuthMetadataPlugins for standard authentication.""" + +import inspect +from typing import Any, Optional + +import grpc + + +def _sign_request( + callback: grpc.AuthMetadataPluginCallback, + token: Optional[str], + error: Optional[Exception], +): + metadata = (("authorization", "Bearer {}".format(token)),) + callback(metadata, error) + + +class GoogleCallCredentials(grpc.AuthMetadataPlugin): + """Metadata wrapper for GoogleCredentials from the oauth2client library.""" + + _is_jwt: bool + _credentials: Any + + # TODO(xuanwn): Give credentials an actual type. + def __init__(self, credentials: Any): + self._credentials = credentials + # Hack to determine if these are JWT creds and we need to pass + # additional_claims when getting a token + self._is_jwt = ( + "additional_claims" + in inspect.getfullargspec(credentials.get_access_token).args + ) + + def __call__( + self, + context: grpc.AuthMetadataContext, + callback: grpc.AuthMetadataPluginCallback, + ): + try: + if self._is_jwt: + access_token = self._credentials.get_access_token( + additional_claims={ + "aud": context.service_url # pytype: disable=attribute-error + } + ).access_token + else: + access_token = self._credentials.get_access_token().access_token + except Exception as exception: # pylint: disable=broad-except + _sign_request(callback, None, exception) + else: + _sign_request(callback, access_token, None) + + +class AccessTokenAuthMetadataPlugin(grpc.AuthMetadataPlugin): + """Metadata wrapper for raw access token credentials.""" + + _access_token: str + + def __init__(self, access_token: str): + self._access_token = access_token + + def __call__( + self, + context: grpc.AuthMetadataContext, + callback: grpc.AuthMetadataPluginCallback, + ): + _sign_request(callback, self._access_token, None) diff --git a/python_embeded/Lib/site-packages/grpc/_channel.py b/python_embeded/Lib/site-packages/grpc/_channel.py new file mode 100644 index 0000000000000000000000000000000000000000..30ba1361f0da821fb2706ad3e4cbae245b66bd68 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_channel.py @@ -0,0 +1,2267 @@ +# Copyright 2016 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Invocation-side implementation of gRPC Python.""" + +import copy +import functools +import logging +import os +import sys +import threading +import time +import types +from typing import ( + Any, + Callable, + Dict, + Iterator, + List, + Optional, + Sequence, + Set, + Tuple, + Union, +) + +import grpc # pytype: disable=pyi-error +from grpc import _common # pytype: disable=pyi-error +from grpc import _compression # pytype: disable=pyi-error +from grpc import _grpcio_metadata # pytype: disable=pyi-error +from grpc import _observability # pytype: disable=pyi-error +from grpc._cython import cygrpc +from grpc._typing import ChannelArgumentType +from grpc._typing import DeserializingFunction +from grpc._typing import IntegratedCallFactory +from grpc._typing import MetadataType +from grpc._typing import NullaryCallbackType +from grpc._typing import ResponseType +from grpc._typing import SerializingFunction +from grpc._typing import UserTag +import grpc.experimental # pytype: disable=pyi-error + +_LOGGER = logging.getLogger(__name__) + +_USER_AGENT = "grpc-python/{}".format(_grpcio_metadata.__version__) + +_EMPTY_FLAGS = 0 + +# NOTE(rbellevi): No guarantees are given about the maintenance of this +# environment variable. +_DEFAULT_SINGLE_THREADED_UNARY_STREAM = ( + os.getenv("GRPC_SINGLE_THREADED_UNARY_STREAM") is not None +) + +_UNARY_UNARY_INITIAL_DUE = ( + cygrpc.OperationType.send_initial_metadata, + cygrpc.OperationType.send_message, + cygrpc.OperationType.send_close_from_client, + cygrpc.OperationType.receive_initial_metadata, + cygrpc.OperationType.receive_message, + cygrpc.OperationType.receive_status_on_client, +) +_UNARY_STREAM_INITIAL_DUE = ( + cygrpc.OperationType.send_initial_metadata, + cygrpc.OperationType.send_message, + cygrpc.OperationType.send_close_from_client, + cygrpc.OperationType.receive_initial_metadata, + cygrpc.OperationType.receive_status_on_client, +) +_STREAM_UNARY_INITIAL_DUE = ( + cygrpc.OperationType.send_initial_metadata, + cygrpc.OperationType.receive_initial_metadata, + cygrpc.OperationType.receive_message, + cygrpc.OperationType.receive_status_on_client, +) +_STREAM_STREAM_INITIAL_DUE = ( + cygrpc.OperationType.send_initial_metadata, + cygrpc.OperationType.receive_initial_metadata, + cygrpc.OperationType.receive_status_on_client, +) + +_CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = ( + "Exception calling channel subscription callback!" +) + +_OK_RENDEZVOUS_REPR_FORMAT = ( + '<{} of RPC that terminated with:\n\tstatus = {}\n\tdetails = "{}"\n>' +) + +_NON_OK_RENDEZVOUS_REPR_FORMAT = ( + "<{} of RPC that terminated with:\n" + "\tstatus = {}\n" + '\tdetails = "{}"\n' + '\tdebug_error_string = "{}"\n' + ">" +) + + +def _deadline(timeout: Optional[float]) -> Optional[float]: + return None if timeout is None else time.time() + timeout + + +def _unknown_code_details( + unknown_cygrpc_code: Optional[grpc.StatusCode], details: Optional[str] +) -> str: + return 'Server sent unknown code {} and details "{}"'.format( + unknown_cygrpc_code, details + ) + + +class _RPCState(object): + condition: threading.Condition + due: Set[cygrpc.OperationType] + initial_metadata: Optional[MetadataType] + response: Any + trailing_metadata: Optional[MetadataType] + code: Optional[grpc.StatusCode] + details: Optional[str] + debug_error_string: Optional[str] + cancelled: bool + callbacks: List[NullaryCallbackType] + fork_epoch: Optional[int] + rpc_start_time: Optional[float] # In relative seconds + rpc_end_time: Optional[float] # In relative seconds + method: Optional[str] + target: Optional[str] + + def __init__( + self, + due: Sequence[cygrpc.OperationType], + initial_metadata: Optional[MetadataType], + trailing_metadata: Optional[MetadataType], + code: Optional[grpc.StatusCode], + details: Optional[str], + ): + # `condition` guards all members of _RPCState. `notify_all` is called on + # `condition` when the state of the RPC has changed. + self.condition = threading.Condition() + + # The cygrpc.OperationType objects representing events due from the RPC's + # completion queue. If an operation is in `due`, it is guaranteed that + # `operate()` has been called on a corresponding operation. But the + # converse is not true. That is, in the case of failed `operate()` + # calls, there may briefly be events in `due` that do not correspond to + # operations submitted to Core. + self.due = set(due) + self.initial_metadata = initial_metadata + self.response = None + self.trailing_metadata = trailing_metadata + self.code = code + self.details = details + self.debug_error_string = None + # The following three fields are used for observability. + # Updates to those fields do not trigger self.condition. + self.rpc_start_time = None + self.rpc_end_time = None + self.method = None + self.target = None + + # The semantics of grpc.Future.cancel and grpc.Future.cancelled are + # slightly wonky, so they have to be tracked separately from the rest of the + # result of the RPC. This field tracks whether cancellation was requested + # prior to termination of the RPC. + self.cancelled = False + self.callbacks = [] + self.fork_epoch = cygrpc.get_fork_epoch() + + def reset_postfork_child(self): + self.condition = threading.Condition() + + +def _abort(state: _RPCState, code: grpc.StatusCode, details: str) -> None: + if state.code is None: + state.code = code + state.details = details + if state.initial_metadata is None: + state.initial_metadata = () + state.trailing_metadata = () + + +def _handle_event( + event: cygrpc.BaseEvent, + state: _RPCState, + response_deserializer: Optional[DeserializingFunction], +) -> List[NullaryCallbackType]: + callbacks = [] + for batch_operation in event.batch_operations: + operation_type = batch_operation.type() + state.due.remove(operation_type) + if operation_type == cygrpc.OperationType.receive_initial_metadata: + state.initial_metadata = batch_operation.initial_metadata() + elif operation_type == cygrpc.OperationType.receive_message: + serialized_response = batch_operation.message() + if serialized_response is not None: + response = _common.deserialize( + serialized_response, response_deserializer + ) + if response is None: + details = "Exception deserializing response!" + _abort(state, grpc.StatusCode.INTERNAL, details) + else: + state.response = response + elif operation_type == cygrpc.OperationType.receive_status_on_client: + state.trailing_metadata = batch_operation.trailing_metadata() + if state.code is None: + code = _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE.get( + batch_operation.code() + ) + if code is None: + state.code = grpc.StatusCode.UNKNOWN + state.details = _unknown_code_details( + code, batch_operation.details() + ) + else: + state.code = code + state.details = batch_operation.details() + state.debug_error_string = batch_operation.error_string() + state.rpc_end_time = time.perf_counter() + _observability.maybe_record_rpc_latency(state) + callbacks.extend(state.callbacks) + state.callbacks = None + return callbacks + + +def _event_handler( + state: _RPCState, response_deserializer: Optional[DeserializingFunction] +) -> UserTag: + def handle_event(event): + with state.condition: + callbacks = _handle_event(event, state, response_deserializer) + state.condition.notify_all() + done = not state.due + for callback in callbacks: + try: + callback() + except Exception as e: # pylint: disable=broad-except + # NOTE(rbellevi): We suppress but log errors here so as not to + # kill the channel spin thread. + logging.error( + "Exception in callback %s: %s", repr(callback.func), repr(e) + ) + return done and state.fork_epoch >= cygrpc.get_fork_epoch() + + return handle_event + + +# TODO(xuanwn): Create a base class for IntegratedCall and SegregatedCall. +# pylint: disable=too-many-statements +def _consume_request_iterator( + request_iterator: Iterator, + state: _RPCState, + call: Union[cygrpc.IntegratedCall, cygrpc.SegregatedCall], + request_serializer: SerializingFunction, + event_handler: Optional[UserTag], +) -> None: + """Consume a request supplied by the user.""" + + def consume_request_iterator(): # pylint: disable=too-many-branches + # Iterate over the request iterator until it is exhausted or an error + # condition is encountered. + while True: + return_from_user_request_generator_invoked = False + try: + # The thread may die in user-code. Do not block fork for this. + cygrpc.enter_user_request_generator() + request = next(request_iterator) + except StopIteration: + break + except Exception: # pylint: disable=broad-except + cygrpc.return_from_user_request_generator() + return_from_user_request_generator_invoked = True + code = grpc.StatusCode.UNKNOWN + details = "Exception iterating requests!" + _LOGGER.exception(details) + call.cancel( + _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details + ) + _abort(state, code, details) + return + finally: + if not return_from_user_request_generator_invoked: + cygrpc.return_from_user_request_generator() + serialized_request = _common.serialize(request, request_serializer) + with state.condition: + if state.code is None and not state.cancelled: + if serialized_request is None: + code = grpc.StatusCode.INTERNAL + details = "Exception serializing request!" + call.cancel( + _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], + details, + ) + _abort(state, code, details) + return + else: + state.due.add(cygrpc.OperationType.send_message) + operations = ( + cygrpc.SendMessageOperation( + serialized_request, _EMPTY_FLAGS + ), + ) + operating = call.operate(operations, event_handler) + if not operating: + state.due.remove(cygrpc.OperationType.send_message) + return + + def _done(): + return ( + state.code is not None + or cygrpc.OperationType.send_message + not in state.due + ) + + _common.wait( + state.condition.wait, + _done, + spin_cb=functools.partial( + cygrpc.block_if_fork_in_progress, state + ), + ) + if state.code is not None: + return + else: + return + with state.condition: + if state.code is None: + state.due.add(cygrpc.OperationType.send_close_from_client) + operations = ( + cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS), + ) + operating = call.operate(operations, event_handler) + if not operating: + state.due.remove( + cygrpc.OperationType.send_close_from_client + ) + + consumption_thread = cygrpc.ForkManagedThread( + target=consume_request_iterator + ) + consumption_thread.setDaemon(True) + consumption_thread.start() + + +def _rpc_state_string(class_name: str, rpc_state: _RPCState) -> str: + """Calculates error string for RPC.""" + with rpc_state.condition: + if rpc_state.code is None: + return "<{} object>".format(class_name) + elif rpc_state.code is grpc.StatusCode.OK: + return _OK_RENDEZVOUS_REPR_FORMAT.format( + class_name, rpc_state.code, rpc_state.details + ) + else: + return _NON_OK_RENDEZVOUS_REPR_FORMAT.format( + class_name, + rpc_state.code, + rpc_state.details, + rpc_state.debug_error_string, + ) + + +class _InactiveRpcError(grpc.RpcError, grpc.Call, grpc.Future): + """An RPC error not tied to the execution of a particular RPC. + + The RPC represented by the state object must not be in-progress or + cancelled. + + Attributes: + _state: An instance of _RPCState. + """ + + _state: _RPCState + + def __init__(self, state: _RPCState): + with state.condition: + self._state = _RPCState( + (), + copy.deepcopy(state.initial_metadata), + copy.deepcopy(state.trailing_metadata), + state.code, + copy.deepcopy(state.details), + ) + self._state.response = copy.copy(state.response) + self._state.debug_error_string = copy.copy(state.debug_error_string) + + def initial_metadata(self) -> Optional[MetadataType]: + return self._state.initial_metadata + + def trailing_metadata(self) -> Optional[MetadataType]: + return self._state.trailing_metadata + + def code(self) -> Optional[grpc.StatusCode]: + return self._state.code + + def details(self) -> Optional[str]: + return _common.decode(self._state.details) + + def debug_error_string(self) -> Optional[str]: + return _common.decode(self._state.debug_error_string) + + def _repr(self) -> str: + return _rpc_state_string(self.__class__.__name__, self._state) + + def __repr__(self) -> str: + return self._repr() + + def __str__(self) -> str: + return self._repr() + + def cancel(self) -> bool: + """See grpc.Future.cancel.""" + return False + + def cancelled(self) -> bool: + """See grpc.Future.cancelled.""" + return False + + def running(self) -> bool: + """See grpc.Future.running.""" + return False + + def done(self) -> bool: + """See grpc.Future.done.""" + return True + + def result( + self, timeout: Optional[float] = None + ) -> Any: # pylint: disable=unused-argument + """See grpc.Future.result.""" + raise self + + def exception( + self, timeout: Optional[float] = None # pylint: disable=unused-argument + ) -> Optional[Exception]: + """See grpc.Future.exception.""" + return self + + def traceback( + self, timeout: Optional[float] = None # pylint: disable=unused-argument + ) -> Optional[types.TracebackType]: + """See grpc.Future.traceback.""" + try: + raise self + except grpc.RpcError: + return sys.exc_info()[2] + + def add_done_callback( + self, + fn: Callable[[grpc.Future], None], + timeout: Optional[float] = None, # pylint: disable=unused-argument + ) -> None: + """See grpc.Future.add_done_callback.""" + fn(self) + + +class _Rendezvous(grpc.RpcError, grpc.RpcContext): + """An RPC iterator. + + Attributes: + _state: An instance of _RPCState. + _call: An instance of SegregatedCall or IntegratedCall. + In either case, the _call object is expected to have operate, cancel, + and next_event methods. + _response_deserializer: A callable taking bytes and return a Python + object. + _deadline: A float representing the deadline of the RPC in seconds. Or + possibly None, to represent an RPC with no deadline at all. + """ + + _state: _RPCState + _call: Union[cygrpc.SegregatedCall, cygrpc.IntegratedCall] + _response_deserializer: Optional[DeserializingFunction] + _deadline: Optional[float] + + def __init__( + self, + state: _RPCState, + call: Union[cygrpc.SegregatedCall, cygrpc.IntegratedCall], + response_deserializer: Optional[DeserializingFunction], + deadline: Optional[float], + ): + super(_Rendezvous, self).__init__() + self._state = state + self._call = call + self._response_deserializer = response_deserializer + self._deadline = deadline + + def is_active(self) -> bool: + """See grpc.RpcContext.is_active""" + with self._state.condition: + return self._state.code is None + + def time_remaining(self) -> Optional[float]: + """See grpc.RpcContext.time_remaining""" + with self._state.condition: + if self._deadline is None: + return None + else: + return max(self._deadline - time.time(), 0) + + def cancel(self) -> bool: + """See grpc.RpcContext.cancel""" + with self._state.condition: + if self._state.code is None: + code = grpc.StatusCode.CANCELLED + details = "Locally cancelled by application!" + self._call.cancel( + _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details + ) + self._state.cancelled = True + _abort(self._state, code, details) + self._state.condition.notify_all() + return True + else: + return False + + def add_callback(self, callback: NullaryCallbackType) -> bool: + """See grpc.RpcContext.add_callback""" + with self._state.condition: + if self._state.callbacks is None: + return False + else: + self._state.callbacks.append(callback) + return True + + def __iter__(self): + return self + + def next(self): + return self._next() + + def __next__(self): + return self._next() + + def _next(self): + raise NotImplementedError() + + def debug_error_string(self) -> Optional[str]: + raise NotImplementedError() + + def _repr(self) -> str: + return _rpc_state_string(self.__class__.__name__, self._state) + + def __repr__(self) -> str: + return self._repr() + + def __str__(self) -> str: + return self._repr() + + def __del__(self) -> None: + with self._state.condition: + if self._state.code is None: + self._state.code = grpc.StatusCode.CANCELLED + self._state.details = "Cancelled upon garbage collection!" + self._state.cancelled = True + self._call.cancel( + _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[self._state.code], + self._state.details, + ) + self._state.condition.notify_all() + + +class _SingleThreadedRendezvous( + _Rendezvous, grpc.Call, grpc.Future +): # pylint: disable=too-many-ancestors + """An RPC iterator operating entirely on a single thread. + + The __next__ method of _SingleThreadedRendezvous does not depend on the + existence of any other thread, including the "channel spin thread". + However, this means that its interface is entirely synchronous. So this + class cannot completely fulfill the grpc.Future interface. The result, + exception, and traceback methods will never block and will instead raise + an exception if calling the method would result in blocking. + + This means that these methods are safe to call from add_done_callback + handlers. + """ + + _state: _RPCState + + def _is_complete(self) -> bool: + return self._state.code is not None + + def cancelled(self) -> bool: + with self._state.condition: + return self._state.cancelled + + def running(self) -> bool: + with self._state.condition: + return self._state.code is None + + def done(self) -> bool: + with self._state.condition: + return self._state.code is not None + + def result(self, timeout: Optional[float] = None) -> Any: + """Returns the result of the computation or raises its exception. + + This method will never block. Instead, it will raise an exception + if calling this method would otherwise result in blocking. + + Since this method will never block, any `timeout` argument passed will + be ignored. + """ + del timeout + with self._state.condition: + if not self._is_complete(): + raise grpc.experimental.UsageError( + "_SingleThreadedRendezvous only supports result() when the" + " RPC is complete." + ) + if self._state.code is grpc.StatusCode.OK: + return self._state.response + elif self._state.cancelled: + raise grpc.FutureCancelledError() + else: + raise self + + def exception(self, timeout: Optional[float] = None) -> Optional[Exception]: + """Return the exception raised by the computation. + + This method will never block. Instead, it will raise an exception + if calling this method would otherwise result in blocking. + + Since this method will never block, any `timeout` argument passed will + be ignored. + """ + del timeout + with self._state.condition: + if not self._is_complete(): + raise grpc.experimental.UsageError( + "_SingleThreadedRendezvous only supports exception() when" + " the RPC is complete." + ) + if self._state.code is grpc.StatusCode.OK: + return None + elif self._state.cancelled: + raise grpc.FutureCancelledError() + else: + return self + + def traceback( + self, timeout: Optional[float] = None + ) -> Optional[types.TracebackType]: + """Access the traceback of the exception raised by the computation. + + This method will never block. Instead, it will raise an exception + if calling this method would otherwise result in blocking. + + Since this method will never block, any `timeout` argument passed will + be ignored. + """ + del timeout + with self._state.condition: + if not self._is_complete(): + raise grpc.experimental.UsageError( + "_SingleThreadedRendezvous only supports traceback() when" + " the RPC is complete." + ) + if self._state.code is grpc.StatusCode.OK: + return None + elif self._state.cancelled: + raise grpc.FutureCancelledError() + else: + try: + raise self + except grpc.RpcError: + return sys.exc_info()[2] + + def add_done_callback(self, fn: Callable[[grpc.Future], None]) -> None: + with self._state.condition: + if self._state.code is None: + self._state.callbacks.append(functools.partial(fn, self)) + return + + fn(self) + + def initial_metadata(self) -> Optional[MetadataType]: + """See grpc.Call.initial_metadata""" + with self._state.condition: + # NOTE(gnossen): Based on our initial call batch, we are guaranteed + # to receive initial metadata before any messages. + while self._state.initial_metadata is None: + self._consume_next_event() + return self._state.initial_metadata + + def trailing_metadata(self) -> Optional[MetadataType]: + """See grpc.Call.trailing_metadata""" + with self._state.condition: + if self._state.trailing_metadata is None: + raise grpc.experimental.UsageError( + "Cannot get trailing metadata until RPC is completed." + ) + return self._state.trailing_metadata + + def code(self) -> Optional[grpc.StatusCode]: + """See grpc.Call.code""" + with self._state.condition: + if self._state.code is None: + raise grpc.experimental.UsageError( + "Cannot get code until RPC is completed." + ) + return self._state.code + + def details(self) -> Optional[str]: + """See grpc.Call.details""" + with self._state.condition: + if self._state.details is None: + raise grpc.experimental.UsageError( + "Cannot get details until RPC is completed." + ) + return _common.decode(self._state.details) + + def _consume_next_event(self) -> Optional[cygrpc.BaseEvent]: + event = self._call.next_event() + with self._state.condition: + callbacks = _handle_event( + event, self._state, self._response_deserializer + ) + for callback in callbacks: + # NOTE(gnossen): We intentionally allow exceptions to bubble up + # to the user when running on a single thread. + callback() + return event + + def _next_response(self) -> Any: + while True: + self._consume_next_event() + with self._state.condition: + if self._state.response is not None: + response = self._state.response + self._state.response = None + return response + elif ( + cygrpc.OperationType.receive_message not in self._state.due + ): + if self._state.code is grpc.StatusCode.OK: + raise StopIteration() + elif self._state.code is not None: + raise self + + def _next(self) -> Any: + with self._state.condition: + if self._state.code is None: + # We tentatively add the operation as expected and remove + # it if the enqueue operation fails. This allows us to guarantee that + # if an event has been submitted to the core completion queue, + # it is in `due`. If we waited until after a successful + # enqueue operation then a signal could interrupt this + # thread between the enqueue operation and the addition of the + # operation to `due`. This would cause an exception on the + # channel spin thread when the operation completes and no + # corresponding operation would be present in state.due. + # Note that, since `condition` is held through this block, there is + # no data race on `due`. + self._state.due.add(cygrpc.OperationType.receive_message) + operating = self._call.operate( + (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), None + ) + if not operating: + self._state.due.remove(cygrpc.OperationType.receive_message) + elif self._state.code is grpc.StatusCode.OK: + raise StopIteration() + else: + raise self + return self._next_response() + + def debug_error_string(self) -> Optional[str]: + with self._state.condition: + if self._state.debug_error_string is None: + raise grpc.experimental.UsageError( + "Cannot get debug error string until RPC is completed." + ) + return _common.decode(self._state.debug_error_string) + + +class _MultiThreadedRendezvous( + _Rendezvous, grpc.Call, grpc.Future +): # pylint: disable=too-many-ancestors + """An RPC iterator that depends on a channel spin thread. + + This iterator relies upon a per-channel thread running in the background, + dequeueing events from the completion queue, and notifying threads waiting + on the threading.Condition object in the _RPCState object. + + This extra thread allows _MultiThreadedRendezvous to fulfill the grpc.Future interface + and to mediate a bidirection streaming RPC. + """ + + _state: _RPCState + + def initial_metadata(self) -> Optional[MetadataType]: + """See grpc.Call.initial_metadata""" + with self._state.condition: + + def _done(): + return self._state.initial_metadata is not None + + _common.wait(self._state.condition.wait, _done) + return self._state.initial_metadata + + def trailing_metadata(self) -> Optional[MetadataType]: + """See grpc.Call.trailing_metadata""" + with self._state.condition: + + def _done(): + return self._state.trailing_metadata is not None + + _common.wait(self._state.condition.wait, _done) + return self._state.trailing_metadata + + def code(self) -> Optional[grpc.StatusCode]: + """See grpc.Call.code""" + with self._state.condition: + + def _done(): + return self._state.code is not None + + _common.wait(self._state.condition.wait, _done) + return self._state.code + + def details(self) -> Optional[str]: + """See grpc.Call.details""" + with self._state.condition: + + def _done(): + return self._state.details is not None + + _common.wait(self._state.condition.wait, _done) + return _common.decode(self._state.details) + + def debug_error_string(self) -> Optional[str]: + with self._state.condition: + + def _done(): + return self._state.debug_error_string is not None + + _common.wait(self._state.condition.wait, _done) + return _common.decode(self._state.debug_error_string) + + def cancelled(self) -> bool: + with self._state.condition: + return self._state.cancelled + + def running(self) -> bool: + with self._state.condition: + return self._state.code is None + + def done(self) -> bool: + with self._state.condition: + return self._state.code is not None + + def _is_complete(self) -> bool: + return self._state.code is not None + + def result(self, timeout: Optional[float] = None) -> Any: + """Returns the result of the computation or raises its exception. + + See grpc.Future.result for the full API contract. + """ + with self._state.condition: + timed_out = _common.wait( + self._state.condition.wait, self._is_complete, timeout=timeout + ) + if timed_out: + raise grpc.FutureTimeoutError() + else: + if self._state.code is grpc.StatusCode.OK: + return self._state.response + elif self._state.cancelled: + raise grpc.FutureCancelledError() + else: + raise self + + def exception(self, timeout: Optional[float] = None) -> Optional[Exception]: + """Return the exception raised by the computation. + + See grpc.Future.exception for the full API contract. + """ + with self._state.condition: + timed_out = _common.wait( + self._state.condition.wait, self._is_complete, timeout=timeout + ) + if timed_out: + raise grpc.FutureTimeoutError() + else: + if self._state.code is grpc.StatusCode.OK: + return None + elif self._state.cancelled: + raise grpc.FutureCancelledError() + else: + return self + + def traceback( + self, timeout: Optional[float] = None + ) -> Optional[types.TracebackType]: + """Access the traceback of the exception raised by the computation. + + See grpc.future.traceback for the full API contract. + """ + with self._state.condition: + timed_out = _common.wait( + self._state.condition.wait, self._is_complete, timeout=timeout + ) + if timed_out: + raise grpc.FutureTimeoutError() + else: + if self._state.code is grpc.StatusCode.OK: + return None + elif self._state.cancelled: + raise grpc.FutureCancelledError() + else: + try: + raise self + except grpc.RpcError: + return sys.exc_info()[2] + + def add_done_callback(self, fn: Callable[[grpc.Future], None]) -> None: + with self._state.condition: + if self._state.code is None: + self._state.callbacks.append(functools.partial(fn, self)) + return + + fn(self) + + def _next(self) -> Any: + with self._state.condition: + if self._state.code is None: + event_handler = _event_handler( + self._state, self._response_deserializer + ) + self._state.due.add(cygrpc.OperationType.receive_message) + operating = self._call.operate( + (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), + event_handler, + ) + if not operating: + self._state.due.remove(cygrpc.OperationType.receive_message) + elif self._state.code is grpc.StatusCode.OK: + raise StopIteration() + else: + raise self + + def _response_ready(): + return self._state.response is not None or ( + cygrpc.OperationType.receive_message not in self._state.due + and self._state.code is not None + ) + + _common.wait(self._state.condition.wait, _response_ready) + if self._state.response is not None: + response = self._state.response + self._state.response = None + return response + elif cygrpc.OperationType.receive_message not in self._state.due: + if self._state.code is grpc.StatusCode.OK: + raise StopIteration() + elif self._state.code is not None: + raise self + + +def _start_unary_request( + request: Any, + timeout: Optional[float], + request_serializer: SerializingFunction, +) -> Tuple[Optional[float], Optional[bytes], Optional[grpc.RpcError]]: + deadline = _deadline(timeout) + serialized_request = _common.serialize(request, request_serializer) + if serialized_request is None: + state = _RPCState( + (), + (), + (), + grpc.StatusCode.INTERNAL, + "Exception serializing request!", + ) + error = _InactiveRpcError(state) + return deadline, None, error + else: + return deadline, serialized_request, None + + +def _end_unary_response_blocking( + state: _RPCState, + call: cygrpc.SegregatedCall, + with_call: bool, + deadline: Optional[float], +) -> Union[ResponseType, Tuple[ResponseType, grpc.Call]]: + if state.code is grpc.StatusCode.OK: + if with_call: + rendezvous = _MultiThreadedRendezvous(state, call, None, deadline) + return state.response, rendezvous + else: + return state.response + else: + raise _InactiveRpcError(state) # pytype: disable=not-instantiable + + +def _stream_unary_invocation_operations( + metadata: Optional[MetadataType], initial_metadata_flags: int +) -> Sequence[Sequence[cygrpc.Operation]]: + return ( + ( + cygrpc.SendInitialMetadataOperation( + metadata, initial_metadata_flags + ), + cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS), + cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS), + ), + (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),), + ) + + +def _stream_unary_invocation_operations_and_tags( + metadata: Optional[MetadataType], initial_metadata_flags: int +) -> Sequence[Tuple[Sequence[cygrpc.Operation], Optional[UserTag]]]: + return tuple( + ( + operations, + None, + ) + for operations in _stream_unary_invocation_operations( + metadata, initial_metadata_flags + ) + ) + + +def _determine_deadline(user_deadline: Optional[float]) -> Optional[float]: + parent_deadline = cygrpc.get_deadline_from_context() + if parent_deadline is None and user_deadline is None: + return None + elif parent_deadline is not None and user_deadline is None: + return parent_deadline + elif user_deadline is not None and parent_deadline is None: + return user_deadline + else: + return min(parent_deadline, user_deadline) + + +class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): + _channel: cygrpc.Channel + _managed_call: IntegratedCallFactory + _method: bytes + _target: bytes + _request_serializer: Optional[SerializingFunction] + _response_deserializer: Optional[DeserializingFunction] + _context: Any + _registered_call_handle: Optional[int] + + __slots__ = [ + "_channel", + "_managed_call", + "_method", + "_target", + "_request_serializer", + "_response_deserializer", + "_context", + ] + + # pylint: disable=too-many-arguments + def __init__( + self, + channel: cygrpc.Channel, + managed_call: IntegratedCallFactory, + method: bytes, + target: bytes, + request_serializer: Optional[SerializingFunction], + response_deserializer: Optional[DeserializingFunction], + _registered_call_handle: Optional[int], + ): + self._channel = channel + self._managed_call = managed_call + self._method = method + self._target = target + self._request_serializer = request_serializer + self._response_deserializer = response_deserializer + self._context = cygrpc.build_census_context() + self._registered_call_handle = _registered_call_handle + + def _prepare( + self, + request: Any, + timeout: Optional[float], + metadata: Optional[MetadataType], + wait_for_ready: Optional[bool], + compression: Optional[grpc.Compression], + ) -> Tuple[ + Optional[_RPCState], + Optional[Sequence[cygrpc.Operation]], + Optional[float], + Optional[grpc.RpcError], + ]: + deadline, serialized_request, rendezvous = _start_unary_request( + request, timeout, self._request_serializer + ) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready + ) + augmented_metadata = _compression.augment_metadata( + metadata, compression + ) + if serialized_request is None: + return None, None, None, rendezvous + else: + state = _RPCState(_UNARY_UNARY_INITIAL_DUE, None, None, None, None) + operations = ( + cygrpc.SendInitialMetadataOperation( + augmented_metadata, initial_metadata_flags + ), + cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS), + cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS), + cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS), + cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS), + cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS), + ) + return state, operations, deadline, None + + def _blocking( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Tuple[_RPCState, cygrpc.SegregatedCall]: + state, operations, deadline, rendezvous = self._prepare( + request, timeout, metadata, wait_for_ready, compression + ) + if state is None: + raise rendezvous # pylint: disable-msg=raising-bad-type + else: + state.rpc_start_time = time.perf_counter() + state.method = _common.decode(self._method) + state.target = _common.decode(self._target) + call = self._channel.segregated_call( + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + self._method, + None, + _determine_deadline(deadline), + metadata, + None if credentials is None else credentials._credentials, + ( + ( + operations, + None, + ), + ), + self._context, + self._registered_call_handle, + ) + event = call.next_event() + _handle_event(event, state, self._response_deserializer) + return state, call + + def __call__( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Any: + ( + state, + call, + ) = self._blocking( + request, timeout, metadata, credentials, wait_for_ready, compression + ) + return _end_unary_response_blocking(state, call, False, None) + + def with_call( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Tuple[Any, grpc.Call]: + ( + state, + call, + ) = self._blocking( + request, timeout, metadata, credentials, wait_for_ready, compression + ) + return _end_unary_response_blocking(state, call, True, None) + + def future( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> _MultiThreadedRendezvous: + state, operations, deadline, rendezvous = self._prepare( + request, timeout, metadata, wait_for_ready, compression + ) + if state is None: + raise rendezvous # pylint: disable-msg=raising-bad-type + else: + event_handler = _event_handler(state, self._response_deserializer) + state.rpc_start_time = time.perf_counter() + state.method = _common.decode(self._method) + state.target = _common.decode(self._target) + call = self._managed_call( + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + self._method, + None, + deadline, + metadata, + None if credentials is None else credentials._credentials, + (operations,), + event_handler, + self._context, + self._registered_call_handle, + ) + return _MultiThreadedRendezvous( + state, call, self._response_deserializer, deadline + ) + + +class _SingleThreadedUnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): + _channel: cygrpc.Channel + _method: bytes + _target: bytes + _request_serializer: Optional[SerializingFunction] + _response_deserializer: Optional[DeserializingFunction] + _context: Any + _registered_call_handle: Optional[int] + + __slots__ = [ + "_channel", + "_method", + "_target", + "_request_serializer", + "_response_deserializer", + "_context", + ] + + # pylint: disable=too-many-arguments + def __init__( + self, + channel: cygrpc.Channel, + method: bytes, + target: bytes, + request_serializer: SerializingFunction, + response_deserializer: DeserializingFunction, + _registered_call_handle: Optional[int], + ): + self._channel = channel + self._method = method + self._target = target + self._request_serializer = request_serializer + self._response_deserializer = response_deserializer + self._context = cygrpc.build_census_context() + self._registered_call_handle = _registered_call_handle + + def __call__( # pylint: disable=too-many-locals + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> _SingleThreadedRendezvous: + deadline = _deadline(timeout) + serialized_request = _common.serialize( + request, self._request_serializer + ) + if serialized_request is None: + state = _RPCState( + (), + (), + (), + grpc.StatusCode.INTERNAL, + "Exception serializing request!", + ) + raise _InactiveRpcError(state) + + state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None) + call_credentials = ( + None if credentials is None else credentials._credentials + ) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready + ) + augmented_metadata = _compression.augment_metadata( + metadata, compression + ) + operations = ( + ( + cygrpc.SendInitialMetadataOperation( + augmented_metadata, initial_metadata_flags + ), + cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS), + cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS), + ), + (cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),), + (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),), + ) + operations_and_tags = tuple((ops, None) for ops in operations) + state.rpc_start_time = time.perf_counter() + state.method = _common.decode(self._method) + state.target = _common.decode(self._target) + call = self._channel.segregated_call( + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + self._method, + None, + _determine_deadline(deadline), + metadata, + call_credentials, + operations_and_tags, + self._context, + self._registered_call_handle, + ) + return _SingleThreadedRendezvous( + state, call, self._response_deserializer, deadline + ) + + +class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): + _channel: cygrpc.Channel + _managed_call: IntegratedCallFactory + _method: bytes + _target: bytes + _request_serializer: Optional[SerializingFunction] + _response_deserializer: Optional[DeserializingFunction] + _context: Any + _registered_call_handle: Optional[int] + + __slots__ = [ + "_channel", + "_managed_call", + "_method", + "_target", + "_request_serializer", + "_response_deserializer", + "_context", + ] + + # pylint: disable=too-many-arguments + def __init__( + self, + channel: cygrpc.Channel, + managed_call: IntegratedCallFactory, + method: bytes, + target: bytes, + request_serializer: SerializingFunction, + response_deserializer: DeserializingFunction, + _registered_call_handle: Optional[int], + ): + self._channel = channel + self._managed_call = managed_call + self._method = method + self._target = target + self._request_serializer = request_serializer + self._response_deserializer = response_deserializer + self._context = cygrpc.build_census_context() + self._registered_call_handle = _registered_call_handle + + def __call__( # pylint: disable=too-many-locals + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> _MultiThreadedRendezvous: + deadline, serialized_request, rendezvous = _start_unary_request( + request, timeout, self._request_serializer + ) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready + ) + if serialized_request is None: + raise rendezvous # pylint: disable-msg=raising-bad-type + else: + augmented_metadata = _compression.augment_metadata( + metadata, compression + ) + state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None) + operations = ( + ( + cygrpc.SendInitialMetadataOperation( + augmented_metadata, initial_metadata_flags + ), + cygrpc.SendMessageOperation( + serialized_request, _EMPTY_FLAGS + ), + cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS), + cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS), + ), + (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),), + ) + state.rpc_start_time = time.perf_counter() + state.method = _common.decode(self._method) + state.target = _common.decode(self._target) + call = self._managed_call( + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + self._method, + None, + _determine_deadline(deadline), + metadata, + None if credentials is None else credentials._credentials, + operations, + _event_handler(state, self._response_deserializer), + self._context, + self._registered_call_handle, + ) + return _MultiThreadedRendezvous( + state, call, self._response_deserializer, deadline + ) + + +class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): + _channel: cygrpc.Channel + _managed_call: IntegratedCallFactory + _method: bytes + _target: bytes + _request_serializer: Optional[SerializingFunction] + _response_deserializer: Optional[DeserializingFunction] + _context: Any + _registered_call_handle: Optional[int] + + __slots__ = [ + "_channel", + "_managed_call", + "_method", + "_target", + "_request_serializer", + "_response_deserializer", + "_context", + ] + + # pylint: disable=too-many-arguments + def __init__( + self, + channel: cygrpc.Channel, + managed_call: IntegratedCallFactory, + method: bytes, + target: bytes, + request_serializer: Optional[SerializingFunction], + response_deserializer: Optional[DeserializingFunction], + _registered_call_handle: Optional[int], + ): + self._channel = channel + self._managed_call = managed_call + self._method = method + self._target = target + self._request_serializer = request_serializer + self._response_deserializer = response_deserializer + self._context = cygrpc.build_census_context() + self._registered_call_handle = _registered_call_handle + + def _blocking( + self, + request_iterator: Iterator, + timeout: Optional[float], + metadata: Optional[MetadataType], + credentials: Optional[grpc.CallCredentials], + wait_for_ready: Optional[bool], + compression: Optional[grpc.Compression], + ) -> Tuple[_RPCState, cygrpc.SegregatedCall]: + deadline = _deadline(timeout) + state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready + ) + augmented_metadata = _compression.augment_metadata( + metadata, compression + ) + state.rpc_start_time = time.perf_counter() + state.method = _common.decode(self._method) + state.target = _common.decode(self._target) + call = self._channel.segregated_call( + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + self._method, + None, + _determine_deadline(deadline), + augmented_metadata, + None if credentials is None else credentials._credentials, + _stream_unary_invocation_operations_and_tags( + augmented_metadata, initial_metadata_flags + ), + self._context, + self._registered_call_handle, + ) + _consume_request_iterator( + request_iterator, state, call, self._request_serializer, None + ) + while True: + event = call.next_event() + with state.condition: + _handle_event(event, state, self._response_deserializer) + state.condition.notify_all() + if not state.due: + break + return state, call + + def __call__( + self, + request_iterator: Iterator, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Any: + ( + state, + call, + ) = self._blocking( + request_iterator, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + return _end_unary_response_blocking(state, call, False, None) + + def with_call( + self, + request_iterator: Iterator, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Tuple[Any, grpc.Call]: + ( + state, + call, + ) = self._blocking( + request_iterator, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + return _end_unary_response_blocking(state, call, True, None) + + def future( + self, + request_iterator: Iterator, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> _MultiThreadedRendezvous: + deadline = _deadline(timeout) + state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None) + event_handler = _event_handler(state, self._response_deserializer) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready + ) + augmented_metadata = _compression.augment_metadata( + metadata, compression + ) + state.rpc_start_time = time.perf_counter() + state.method = _common.decode(self._method) + state.target = _common.decode(self._target) + call = self._managed_call( + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + self._method, + None, + deadline, + augmented_metadata, + None if credentials is None else credentials._credentials, + _stream_unary_invocation_operations( + metadata, initial_metadata_flags + ), + event_handler, + self._context, + self._registered_call_handle, + ) + _consume_request_iterator( + request_iterator, + state, + call, + self._request_serializer, + event_handler, + ) + return _MultiThreadedRendezvous( + state, call, self._response_deserializer, deadline + ) + + +class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): + _channel: cygrpc.Channel + _managed_call: IntegratedCallFactory + _method: bytes + _target: bytes + _request_serializer: Optional[SerializingFunction] + _response_deserializer: Optional[DeserializingFunction] + _context: Any + _registered_call_handle: Optional[int] + + __slots__ = [ + "_channel", + "_managed_call", + "_method", + "_target", + "_request_serializer", + "_response_deserializer", + "_context", + ] + + # pylint: disable=too-many-arguments + def __init__( + self, + channel: cygrpc.Channel, + managed_call: IntegratedCallFactory, + method: bytes, + target: bytes, + request_serializer: Optional[SerializingFunction], + response_deserializer: Optional[DeserializingFunction], + _registered_call_handle: Optional[int], + ): + self._channel = channel + self._managed_call = managed_call + self._method = method + self._target = target + self._request_serializer = request_serializer + self._response_deserializer = response_deserializer + self._context = cygrpc.build_census_context() + self._registered_call_handle = _registered_call_handle + + def __call__( + self, + request_iterator: Iterator, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> _MultiThreadedRendezvous: + deadline = _deadline(timeout) + state = _RPCState(_STREAM_STREAM_INITIAL_DUE, None, None, None, None) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready + ) + augmented_metadata = _compression.augment_metadata( + metadata, compression + ) + operations = ( + ( + cygrpc.SendInitialMetadataOperation( + augmented_metadata, initial_metadata_flags + ), + cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS), + ), + (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),), + ) + event_handler = _event_handler(state, self._response_deserializer) + state.rpc_start_time = time.perf_counter() + state.method = _common.decode(self._method) + state.target = _common.decode(self._target) + call = self._managed_call( + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + self._method, + None, + _determine_deadline(deadline), + augmented_metadata, + None if credentials is None else credentials._credentials, + operations, + event_handler, + self._context, + self._registered_call_handle, + ) + _consume_request_iterator( + request_iterator, + state, + call, + self._request_serializer, + event_handler, + ) + return _MultiThreadedRendezvous( + state, call, self._response_deserializer, deadline + ) + + +class _InitialMetadataFlags(int): + """Stores immutable initial metadata flags""" + + def __new__(cls, value: int = _EMPTY_FLAGS): + value &= cygrpc.InitialMetadataFlags.used_mask + return super(_InitialMetadataFlags, cls).__new__(cls, value) + + def with_wait_for_ready(self, wait_for_ready: Optional[bool]) -> int: + if wait_for_ready is not None: + if wait_for_ready: + return self.__class__( + self + | cygrpc.InitialMetadataFlags.wait_for_ready + | cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set + ) + elif not wait_for_ready: + return self.__class__( + self & ~cygrpc.InitialMetadataFlags.wait_for_ready + | cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set + ) + return self + + +class _ChannelCallState(object): + channel: cygrpc.Channel + managed_calls: int + threading: bool + + def __init__(self, channel: cygrpc.Channel): + self.lock = threading.Lock() + self.channel = channel + self.managed_calls = 0 + self.threading = False + + def reset_postfork_child(self) -> None: + self.managed_calls = 0 + + def __del__(self): + try: + self.channel.close( + cygrpc.StatusCode.cancelled, "Channel deallocated!" + ) + except (TypeError, AttributeError): + pass + + +def _run_channel_spin_thread(state: _ChannelCallState) -> None: + def channel_spin(): + while True: + cygrpc.block_if_fork_in_progress(state) + event = state.channel.next_call_event() + if event.completion_type == cygrpc.CompletionType.queue_timeout: + continue + call_completed = event.tag(event) + if call_completed: + with state.lock: + state.managed_calls -= 1 + if state.managed_calls == 0: + return + + channel_spin_thread = cygrpc.ForkManagedThread(target=channel_spin) + channel_spin_thread.setDaemon(True) + channel_spin_thread.start() + + +def _channel_managed_call_management(state: _ChannelCallState): + # pylint: disable=too-many-arguments + def create( + flags: int, + method: bytes, + host: Optional[str], + deadline: Optional[float], + metadata: Optional[MetadataType], + credentials: Optional[cygrpc.CallCredentials], + operations: Sequence[Sequence[cygrpc.Operation]], + event_handler: UserTag, + context: Any, + _registered_call_handle: Optional[int], + ) -> cygrpc.IntegratedCall: + """Creates a cygrpc.IntegratedCall. + + Args: + flags: An integer bitfield of call flags. + method: The RPC method. + host: A host string for the created call. + deadline: A float to be the deadline of the created call or None if + the call is to have an infinite deadline. + metadata: The metadata for the call or None. + credentials: A cygrpc.CallCredentials or None. + operations: A sequence of sequences of cygrpc.Operations to be + started on the call. + event_handler: A behavior to call to handle the events resultant from + the operations on the call. + context: Context object for distributed tracing. + _registered_call_handle: An int representing the call handle of the + method, or None if the method is not registered. + Returns: + A cygrpc.IntegratedCall with which to conduct an RPC. + """ + operations_and_tags = tuple( + ( + operation, + event_handler, + ) + for operation in operations + ) + with state.lock: + call = state.channel.integrated_call( + flags, + method, + host, + deadline, + metadata, + credentials, + operations_and_tags, + context, + _registered_call_handle, + ) + if state.managed_calls == 0: + state.managed_calls = 1 + _run_channel_spin_thread(state) + else: + state.managed_calls += 1 + return call + + return create + + +class _ChannelConnectivityState(object): + lock: threading.RLock + channel: grpc.Channel + polling: bool + connectivity: grpc.ChannelConnectivity + try_to_connect: bool + # TODO(xuanwn): Refactor this: https://github.com/grpc/grpc/issues/31704 + callbacks_and_connectivities: List[ + Sequence[ + Union[ + Callable[[grpc.ChannelConnectivity], None], + Optional[grpc.ChannelConnectivity], + ] + ] + ] + delivering: bool + + def __init__(self, channel: grpc.Channel): + self.lock = threading.RLock() + self.channel = channel + self.polling = False + self.connectivity = None + self.try_to_connect = False + self.callbacks_and_connectivities = [] + self.delivering = False + + def reset_postfork_child(self) -> None: + self.polling = False + self.connectivity = None + self.try_to_connect = False + self.callbacks_and_connectivities = [] + self.delivering = False + + +def _deliveries( + state: _ChannelConnectivityState, +) -> List[Callable[[grpc.ChannelConnectivity], None]]: + callbacks_needing_update = [] + for callback_and_connectivity in state.callbacks_and_connectivities: + ( + callback, + callback_connectivity, + ) = callback_and_connectivity + if callback_connectivity is not state.connectivity: + callbacks_needing_update.append(callback) + callback_and_connectivity[1] = state.connectivity + return callbacks_needing_update + + +def _deliver( + state: _ChannelConnectivityState, + initial_connectivity: grpc.ChannelConnectivity, + initial_callbacks: Sequence[Callable[[grpc.ChannelConnectivity], None]], +) -> None: + connectivity = initial_connectivity + callbacks = initial_callbacks + while True: + for callback in callbacks: + cygrpc.block_if_fork_in_progress(state) + try: + callback(connectivity) + except Exception: # pylint: disable=broad-except + _LOGGER.exception( + _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE + ) + with state.lock: + callbacks = _deliveries(state) + if callbacks: + connectivity = state.connectivity + else: + state.delivering = False + return + + +def _spawn_delivery( + state: _ChannelConnectivityState, + callbacks: Sequence[Callable[[grpc.ChannelConnectivity], None]], +) -> None: + delivering_thread = cygrpc.ForkManagedThread( + target=_deliver, + args=( + state, + state.connectivity, + callbacks, + ), + ) + delivering_thread.setDaemon(True) + delivering_thread.start() + state.delivering = True + + +# NOTE(https://github.com/grpc/grpc/issues/3064): We'd rather not poll. +def _poll_connectivity( + state: _ChannelConnectivityState, + channel: grpc.Channel, + initial_try_to_connect: bool, +) -> None: + try_to_connect = initial_try_to_connect + connectivity = channel.check_connectivity_state(try_to_connect) + with state.lock: + state.connectivity = ( + _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[ + connectivity + ] + ) + callbacks = tuple( + callback for callback, _ in state.callbacks_and_connectivities + ) + for callback_and_connectivity in state.callbacks_and_connectivities: + callback_and_connectivity[1] = state.connectivity + if callbacks: + _spawn_delivery(state, callbacks) + while True: + event = channel.watch_connectivity_state( + connectivity, time.time() + 0.2 + ) + cygrpc.block_if_fork_in_progress(state) + with state.lock: + if ( + not state.callbacks_and_connectivities + and not state.try_to_connect + ): + state.polling = False + state.connectivity = None + break + try_to_connect = state.try_to_connect + state.try_to_connect = False + if event.success or try_to_connect: + connectivity = channel.check_connectivity_state(try_to_connect) + with state.lock: + state.connectivity = ( + _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[ + connectivity + ] + ) + if not state.delivering: + callbacks = _deliveries(state) + if callbacks: + _spawn_delivery(state, callbacks) + + +def _subscribe( + state: _ChannelConnectivityState, + callback: Callable[[grpc.ChannelConnectivity], None], + try_to_connect: bool, +) -> None: + with state.lock: + if not state.callbacks_and_connectivities and not state.polling: + polling_thread = cygrpc.ForkManagedThread( + target=_poll_connectivity, + args=(state, state.channel, bool(try_to_connect)), + ) + polling_thread.setDaemon(True) + polling_thread.start() + state.polling = True + state.callbacks_and_connectivities.append([callback, None]) + elif not state.delivering and state.connectivity is not None: + _spawn_delivery(state, (callback,)) + state.try_to_connect |= bool(try_to_connect) + state.callbacks_and_connectivities.append( + [callback, state.connectivity] + ) + else: + state.try_to_connect |= bool(try_to_connect) + state.callbacks_and_connectivities.append([callback, None]) + + +def _unsubscribe( + state: _ChannelConnectivityState, + callback: Callable[[grpc.ChannelConnectivity], None], +) -> None: + with state.lock: + for index, (subscribed_callback, unused_connectivity) in enumerate( + state.callbacks_and_connectivities + ): + if callback == subscribed_callback: + state.callbacks_and_connectivities.pop(index) + break + + +def _augment_options( + base_options: Sequence[ChannelArgumentType], + compression: Optional[grpc.Compression], +) -> Sequence[ChannelArgumentType]: + compression_option = _compression.create_channel_option(compression) + return ( + tuple(base_options) + + compression_option + + ( + ( + cygrpc.ChannelArgKey.primary_user_agent_string, + _USER_AGENT, + ), + ) + ) + + +def _separate_channel_options( + options: Sequence[ChannelArgumentType], +) -> Tuple[Sequence[ChannelArgumentType], Sequence[ChannelArgumentType]]: + """Separates core channel options from Python channel options.""" + core_options = [] + python_options = [] + for pair in options: + if ( + pair[0] + == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream + ): + python_options.append(pair) + else: + core_options.append(pair) + return python_options, core_options + + +class Channel(grpc.Channel): + """A cygrpc.Channel-backed implementation of grpc.Channel.""" + + _single_threaded_unary_stream: bool + _channel: cygrpc.Channel + _call_state: _ChannelCallState + _connectivity_state: _ChannelConnectivityState + _target: str + _registered_call_handles: Dict[str, int] + + def __init__( + self, + target: str, + options: Sequence[ChannelArgumentType], + credentials: Optional[grpc.ChannelCredentials], + compression: Optional[grpc.Compression], + ): + """Constructor. + + Args: + target: The target to which to connect. + options: Configuration options for the channel. + credentials: A cygrpc.ChannelCredentials or None. + compression: An optional value indicating the compression method to be + used over the lifetime of the channel. + """ + python_options, core_options = _separate_channel_options(options) + self._single_threaded_unary_stream = ( + _DEFAULT_SINGLE_THREADED_UNARY_STREAM + ) + self._process_python_options(python_options) + self._channel = cygrpc.Channel( + _common.encode(target), + _augment_options(core_options, compression), + credentials, + ) + self._target = target + self._call_state = _ChannelCallState(self._channel) + self._connectivity_state = _ChannelConnectivityState(self._channel) + cygrpc.fork_register_channel(self) + if cygrpc.g_gevent_activated: + cygrpc.gevent_increment_channel_count() + + def _get_registered_call_handle(self, method: str) -> int: + """ + Get the registered call handle for a method. + + This is a semi-private method. It is intended for use only by gRPC generated code. + + This method is not thread-safe. + + Args: + method: Required, the method name for the RPC. + + Returns: + The registered call handle pointer in the form of a Python Long. + """ + return self._channel.get_registered_call_handle(_common.encode(method)) + + def _process_python_options( + self, python_options: Sequence[ChannelArgumentType] + ) -> None: + """Sets channel attributes according to python-only channel options.""" + for pair in python_options: + if ( + pair[0] + == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream + ): + self._single_threaded_unary_stream = True + + def subscribe( + self, + callback: Callable[[grpc.ChannelConnectivity], None], + try_to_connect: Optional[bool] = None, + ) -> None: + _subscribe(self._connectivity_state, callback, try_to_connect) + + def unsubscribe( + self, callback: Callable[[grpc.ChannelConnectivity], None] + ) -> None: + _unsubscribe(self._connectivity_state, callback) + + # pylint: disable=arguments-differ + def unary_unary( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.UnaryUnaryMultiCallable: + _registered_call_handle = None + if _registered_method: + _registered_call_handle = self._get_registered_call_handle(method) + return _UnaryUnaryMultiCallable( + self._channel, + _channel_managed_call_management(self._call_state), + _common.encode(method), + _common.encode(self._target), + request_serializer, + response_deserializer, + _registered_call_handle, + ) + + # pylint: disable=arguments-differ + def unary_stream( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.UnaryStreamMultiCallable: + _registered_call_handle = None + if _registered_method: + _registered_call_handle = self._get_registered_call_handle(method) + # NOTE(rbellevi): Benchmarks have shown that running a unary-stream RPC + # on a single Python thread results in an appreciable speed-up. However, + # due to slight differences in capability, the multi-threaded variant + # remains the default. + if self._single_threaded_unary_stream: + return _SingleThreadedUnaryStreamMultiCallable( + self._channel, + _common.encode(method), + _common.encode(self._target), + request_serializer, + response_deserializer, + _registered_call_handle, + ) + else: + return _UnaryStreamMultiCallable( + self._channel, + _channel_managed_call_management(self._call_state), + _common.encode(method), + _common.encode(self._target), + request_serializer, + response_deserializer, + _registered_call_handle, + ) + + # pylint: disable=arguments-differ + def stream_unary( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.StreamUnaryMultiCallable: + _registered_call_handle = None + if _registered_method: + _registered_call_handle = self._get_registered_call_handle(method) + return _StreamUnaryMultiCallable( + self._channel, + _channel_managed_call_management(self._call_state), + _common.encode(method), + _common.encode(self._target), + request_serializer, + response_deserializer, + _registered_call_handle, + ) + + # pylint: disable=arguments-differ + def stream_stream( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.StreamStreamMultiCallable: + _registered_call_handle = None + if _registered_method: + _registered_call_handle = self._get_registered_call_handle(method) + return _StreamStreamMultiCallable( + self._channel, + _channel_managed_call_management(self._call_state), + _common.encode(method), + _common.encode(self._target), + request_serializer, + response_deserializer, + _registered_call_handle, + ) + + def _unsubscribe_all(self) -> None: + state = self._connectivity_state + if state: + with state.lock: + del state.callbacks_and_connectivities[:] + + def _close(self) -> None: + self._unsubscribe_all() + self._channel.close(cygrpc.StatusCode.cancelled, "Channel closed!") + cygrpc.fork_unregister_channel(self) + if cygrpc.g_gevent_activated: + cygrpc.gevent_decrement_channel_count() + + def _close_on_fork(self) -> None: + self._unsubscribe_all() + self._channel.close_on_fork( + cygrpc.StatusCode.cancelled, "Channel closed due to fork" + ) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self._close() + return False + + def close(self) -> None: + self._close() + + def __del__(self): + # TODO(https://github.com/grpc/grpc/issues/12531): Several releases + # after 1.12 (1.16 or thereabouts?) add a "self._channel.close" call + # here (or more likely, call self._close() here). We don't do this today + # because many valid use cases today allow the channel to be deleted + # immediately after stubs are created. After a sufficient period of time + # has passed for all users to be trusted to freeze out to their channels + # for as long as they are in use and to close them after using them, + # then deletion of this grpc._channel.Channel instance can be made to + # effect closure of the underlying cygrpc.Channel instance. + try: + self._unsubscribe_all() + except: # pylint: disable=bare-except + # Exceptions in __del__ are ignored by Python anyway, but they can + # keep spamming logs. Just silence them. + pass diff --git a/python_embeded/Lib/site-packages/grpc/_common.py b/python_embeded/Lib/site-packages/grpc/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..be4d9754ec638f641b56f017a9ae09f60e3ad1cb --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_common.py @@ -0,0 +1,183 @@ +# Copyright 2016 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Shared implementation.""" + +import logging +import time +from typing import Any, AnyStr, Callable, Optional, Union + +import grpc +from grpc._cython import cygrpc +from grpc._typing import DeserializingFunction +from grpc._typing import SerializingFunction + +_LOGGER = logging.getLogger(__name__) + +CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY = { + cygrpc.ConnectivityState.idle: grpc.ChannelConnectivity.IDLE, + cygrpc.ConnectivityState.connecting: grpc.ChannelConnectivity.CONNECTING, + cygrpc.ConnectivityState.ready: grpc.ChannelConnectivity.READY, + cygrpc.ConnectivityState.transient_failure: grpc.ChannelConnectivity.TRANSIENT_FAILURE, + cygrpc.ConnectivityState.shutdown: grpc.ChannelConnectivity.SHUTDOWN, +} + +CYGRPC_STATUS_CODE_TO_STATUS_CODE = { + cygrpc.StatusCode.ok: grpc.StatusCode.OK, + cygrpc.StatusCode.cancelled: grpc.StatusCode.CANCELLED, + cygrpc.StatusCode.unknown: grpc.StatusCode.UNKNOWN, + cygrpc.StatusCode.invalid_argument: grpc.StatusCode.INVALID_ARGUMENT, + cygrpc.StatusCode.deadline_exceeded: grpc.StatusCode.DEADLINE_EXCEEDED, + cygrpc.StatusCode.not_found: grpc.StatusCode.NOT_FOUND, + cygrpc.StatusCode.already_exists: grpc.StatusCode.ALREADY_EXISTS, + cygrpc.StatusCode.permission_denied: grpc.StatusCode.PERMISSION_DENIED, + cygrpc.StatusCode.unauthenticated: grpc.StatusCode.UNAUTHENTICATED, + cygrpc.StatusCode.resource_exhausted: grpc.StatusCode.RESOURCE_EXHAUSTED, + cygrpc.StatusCode.failed_precondition: grpc.StatusCode.FAILED_PRECONDITION, + cygrpc.StatusCode.aborted: grpc.StatusCode.ABORTED, + cygrpc.StatusCode.out_of_range: grpc.StatusCode.OUT_OF_RANGE, + cygrpc.StatusCode.unimplemented: grpc.StatusCode.UNIMPLEMENTED, + cygrpc.StatusCode.internal: grpc.StatusCode.INTERNAL, + cygrpc.StatusCode.unavailable: grpc.StatusCode.UNAVAILABLE, + cygrpc.StatusCode.data_loss: grpc.StatusCode.DATA_LOSS, +} +STATUS_CODE_TO_CYGRPC_STATUS_CODE = { + grpc_code: cygrpc_code + for cygrpc_code, grpc_code in CYGRPC_STATUS_CODE_TO_STATUS_CODE.items() +} + +MAXIMUM_WAIT_TIMEOUT = 0.1 + +_ERROR_MESSAGE_PORT_BINDING_FAILED = ( + "Failed to bind to address %s; set " + "GRPC_VERBOSITY=debug environment variable to see detailed error message." +) + + +def encode(s: AnyStr) -> bytes: + if isinstance(s, bytes): + return s + else: + return s.encode("utf8") + + +def decode(b: AnyStr) -> str: + if isinstance(b, bytes): + return b.decode("utf-8", "replace") + return b + + +def _transform( + message: Any, + transformer: Union[SerializingFunction, DeserializingFunction, None], + exception_message: str, +) -> Any: + if transformer is None: + return message + else: + try: + return transformer(message) + except Exception: # pylint: disable=broad-except + _LOGGER.exception(exception_message) + return None + + +def serialize(message: Any, serializer: Optional[SerializingFunction]) -> bytes: + return _transform(message, serializer, "Exception serializing message!") + + +def deserialize( + serialized_message: bytes, deserializer: Optional[DeserializingFunction] +) -> Any: + return _transform( + serialized_message, deserializer, "Exception deserializing message!" + ) + + +def fully_qualified_method(group: str, method: str) -> str: + return "/{}/{}".format(group, method) + + +def _wait_once( + wait_fn: Callable[..., bool], + timeout: float, + spin_cb: Optional[Callable[[], None]], +): + wait_fn(timeout=timeout) + if spin_cb is not None: + spin_cb() + + +def wait( + wait_fn: Callable[..., bool], + wait_complete_fn: Callable[[], bool], + timeout: Optional[float] = None, + spin_cb: Optional[Callable[[], None]] = None, +) -> bool: + """Blocks waiting for an event without blocking the thread indefinitely. + + See https://github.com/grpc/grpc/issues/19464 for full context. CPython's + `threading.Event.wait` and `threading.Condition.wait` methods, if invoked + without a timeout kwarg, may block the calling thread indefinitely. If the + call is made from the main thread, this means that signal handlers may not + run for an arbitrarily long period of time. + + This wrapper calls the supplied wait function with an arbitrary short + timeout to ensure that no signal handler has to wait longer than + MAXIMUM_WAIT_TIMEOUT before executing. + + Args: + wait_fn: A callable acceptable a single float-valued kwarg named + `timeout`. This function is expected to be one of `threading.Event.wait` + or `threading.Condition.wait`. + wait_complete_fn: A callable taking no arguments and returning a bool. + When this function returns true, it indicates that waiting should cease. + timeout: An optional float-valued number of seconds after which the wait + should cease. + spin_cb: An optional Callable taking no arguments and returning nothing. + This callback will be called on each iteration of the spin. This may be + used for, e.g. work related to forking. + + Returns: + True if a timeout was supplied and it was reached. False otherwise. + """ + if timeout is None: + while not wait_complete_fn(): + _wait_once(wait_fn, MAXIMUM_WAIT_TIMEOUT, spin_cb) + else: + end = time.time() + timeout + while not wait_complete_fn(): + remaining = min(end - time.time(), MAXIMUM_WAIT_TIMEOUT) + if remaining < 0: + return True + _wait_once(wait_fn, remaining, spin_cb) + return False + + +def validate_port_binding_result(address: str, port: int) -> int: + """Validates if the port binding succeed. + + If the port returned by Core is 0, the binding is failed. However, in that + case, the Core API doesn't return a detailed failing reason. The best we + can do is raising an exception to prevent further confusion. + + Args: + address: The address string to be bound. + port: An int returned by core + """ + if port == 0: + # The Core API doesn't return a failure message. The best we can do + # is raising an exception to prevent further confusion. + raise RuntimeError(_ERROR_MESSAGE_PORT_BINDING_FAILED % address) + else: + return port diff --git a/python_embeded/Lib/site-packages/grpc/_compression.py b/python_embeded/Lib/site-packages/grpc/_compression.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa9f328ba9497df867a8cc0fd9c50daa6b1fdea --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_compression.py @@ -0,0 +1,71 @@ +# Copyright 2019 The gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Optional + +import grpc +from grpc._cython import cygrpc +from grpc._typing import MetadataType + +NoCompression = cygrpc.CompressionAlgorithm.none +Deflate = cygrpc.CompressionAlgorithm.deflate +Gzip = cygrpc.CompressionAlgorithm.gzip + +_METADATA_STRING_MAPPING = { + NoCompression: "identity", + Deflate: "deflate", + Gzip: "gzip", +} + + +def _compression_algorithm_to_metadata_value( + compression: grpc.Compression, +) -> str: + return _METADATA_STRING_MAPPING[compression] + + +def compression_algorithm_to_metadata(compression: grpc.Compression): + return ( + cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, + _compression_algorithm_to_metadata_value(compression), + ) + + +def create_channel_option(compression: Optional[grpc.Compression]): + return ( + ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, int(compression)),) + if compression + else () + ) + + +def augment_metadata( + metadata: Optional[MetadataType], compression: Optional[grpc.Compression] +): + if not metadata and not compression: + return None + base_metadata = tuple(metadata) if metadata else () + compression_metadata = ( + (compression_algorithm_to_metadata(compression),) if compression else () + ) + return base_metadata + compression_metadata + + +__all__ = ( + "NoCompression", + "Deflate", + "Gzip", +) diff --git a/python_embeded/Lib/site-packages/grpc/_grpcio_metadata.py b/python_embeded/Lib/site-packages/grpc/_grpcio_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc9754b74e854eeba8a80fb3e919925f98d9158 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_grpcio_metadata.py @@ -0,0 +1 @@ +__version__ = """1.73.1""" \ No newline at end of file diff --git a/python_embeded/Lib/site-packages/grpc/_interceptor.py b/python_embeded/Lib/site-packages/grpc/_interceptor.py new file mode 100644 index 0000000000000000000000000000000000000000..21a4e5ee073d8b9a03ae97993b905c78dfd2ed17 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_interceptor.py @@ -0,0 +1,813 @@ +# Copyright 2017 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Implementation of gRPC Python interceptors.""" + +import collections +import sys +import types +from typing import Any, Callable, Optional, Sequence, Tuple, Union + +import grpc + +from ._typing import DeserializingFunction +from ._typing import DoneCallbackType +from ._typing import MetadataType +from ._typing import RequestIterableType +from ._typing import SerializingFunction + + +class _ServicePipeline(object): + interceptors: Tuple[grpc.ServerInterceptor] + + def __init__(self, interceptors: Sequence[grpc.ServerInterceptor]): + self.interceptors = tuple(interceptors) + + def _continuation(self, thunk: Callable, index: int) -> Callable: + return lambda context: self._intercept_at(thunk, index, context) + + def _intercept_at( + self, thunk: Callable, index: int, context: grpc.HandlerCallDetails + ) -> grpc.RpcMethodHandler: + if index < len(self.interceptors): + interceptor = self.interceptors[index] + thunk = self._continuation(thunk, index + 1) + return interceptor.intercept_service(thunk, context) + else: + return thunk(context) + + def execute( + self, thunk: Callable, context: grpc.HandlerCallDetails + ) -> grpc.RpcMethodHandler: + return self._intercept_at(thunk, 0, context) + + +def service_pipeline( + interceptors: Optional[Sequence[grpc.ServerInterceptor]], +) -> Optional[_ServicePipeline]: + return _ServicePipeline(interceptors) if interceptors else None + + +class _ClientCallDetails( + collections.namedtuple( + "_ClientCallDetails", + ( + "method", + "timeout", + "metadata", + "credentials", + "wait_for_ready", + "compression", + ), + ), + grpc.ClientCallDetails, +): + pass + + +def _unwrap_client_call_details( + call_details: grpc.ClientCallDetails, + default_details: grpc.ClientCallDetails, +) -> Tuple[ + str, float, MetadataType, grpc.CallCredentials, bool, grpc.Compression +]: + try: + method = call_details.method # pytype: disable=attribute-error + except AttributeError: + method = default_details.method # pytype: disable=attribute-error + + try: + timeout = call_details.timeout # pytype: disable=attribute-error + except AttributeError: + timeout = default_details.timeout # pytype: disable=attribute-error + + try: + metadata = call_details.metadata # pytype: disable=attribute-error + except AttributeError: + metadata = default_details.metadata # pytype: disable=attribute-error + + try: + credentials = ( + call_details.credentials + ) # pytype: disable=attribute-error + except AttributeError: + credentials = ( + default_details.credentials + ) # pytype: disable=attribute-error + + try: + wait_for_ready = ( + call_details.wait_for_ready + ) # pytype: disable=attribute-error + except AttributeError: + wait_for_ready = ( + default_details.wait_for_ready + ) # pytype: disable=attribute-error + + try: + compression = ( + call_details.compression + ) # pytype: disable=attribute-error + except AttributeError: + compression = ( + default_details.compression + ) # pytype: disable=attribute-error + + return method, timeout, metadata, credentials, wait_for_ready, compression + + +class _FailureOutcome( + grpc.RpcError, grpc.Future, grpc.Call +): # pylint: disable=too-many-ancestors + _exception: Exception + _traceback: types.TracebackType + + def __init__(self, exception: Exception, traceback: types.TracebackType): + super(_FailureOutcome, self).__init__() + self._exception = exception + self._traceback = traceback + + def initial_metadata(self) -> Optional[MetadataType]: + return None + + def trailing_metadata(self) -> Optional[MetadataType]: + return None + + def code(self) -> Optional[grpc.StatusCode]: + return grpc.StatusCode.INTERNAL + + def details(self) -> Optional[str]: + return "Exception raised while intercepting the RPC" + + def cancel(self) -> bool: + return False + + def cancelled(self) -> bool: + return False + + def is_active(self) -> bool: + return False + + def time_remaining(self) -> Optional[float]: + return None + + def running(self) -> bool: + return False + + def done(self) -> bool: + return True + + def result(self, ignored_timeout: Optional[float] = None): + raise self._exception + + def exception( + self, ignored_timeout: Optional[float] = None + ) -> Optional[Exception]: + return self._exception + + def traceback( + self, ignored_timeout: Optional[float] = None + ) -> Optional[types.TracebackType]: + return self._traceback + + def add_callback(self, unused_callback) -> bool: + return False + + def add_done_callback(self, fn: DoneCallbackType) -> None: + fn(self) + + def __iter__(self): + return self + + def __next__(self): + raise self._exception + + def next(self): + return self.__next__() + + +class _UnaryOutcome(grpc.Call, grpc.Future): + _response: Any + _call: grpc.Call + + def __init__(self, response: Any, call: grpc.Call): + self._response = response + self._call = call + + def initial_metadata(self) -> Optional[MetadataType]: + return self._call.initial_metadata() + + def trailing_metadata(self) -> Optional[MetadataType]: + return self._call.trailing_metadata() + + def code(self) -> Optional[grpc.StatusCode]: + return self._call.code() + + def details(self) -> Optional[str]: + return self._call.details() + + def is_active(self) -> bool: + return self._call.is_active() + + def time_remaining(self) -> Optional[float]: + return self._call.time_remaining() + + def cancel(self) -> bool: + return self._call.cancel() + + def add_callback(self, callback) -> bool: + return self._call.add_callback(callback) + + def cancelled(self) -> bool: + return False + + def running(self) -> bool: + return False + + def done(self) -> bool: + return True + + def result(self, ignored_timeout: Optional[float] = None): + return self._response + + def exception(self, ignored_timeout: Optional[float] = None): + return None + + def traceback(self, ignored_timeout: Optional[float] = None): + return None + + def add_done_callback(self, fn: DoneCallbackType) -> None: + fn(self) + + +class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): + _thunk: Callable + _method: str + _interceptor: grpc.UnaryUnaryClientInterceptor + + def __init__( + self, + thunk: Callable, + method: str, + interceptor: grpc.UnaryUnaryClientInterceptor, + ): + self._thunk = thunk + self._method = method + self._interceptor = interceptor + + def __call__( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Any: + response, ignored_call = self._with_call( + request, + timeout=timeout, + metadata=metadata, + credentials=credentials, + wait_for_ready=wait_for_ready, + compression=compression, + ) + return response + + def _with_call( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Tuple[Any, grpc.Call]: + client_call_details = _ClientCallDetails( + self._method, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + + def continuation(new_details, request): + ( + new_method, + new_timeout, + new_metadata, + new_credentials, + new_wait_for_ready, + new_compression, + ) = _unwrap_client_call_details(new_details, client_call_details) + try: + response, call = self._thunk(new_method).with_call( + request, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, + wait_for_ready=new_wait_for_ready, + compression=new_compression, + ) + return _UnaryOutcome(response, call) + except grpc.RpcError as rpc_error: + return rpc_error + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + + call = self._interceptor.intercept_unary_unary( + continuation, client_call_details, request + ) + return call.result(), call + + def with_call( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Tuple[Any, grpc.Call]: + return self._with_call( + request, + timeout=timeout, + metadata=metadata, + credentials=credentials, + wait_for_ready=wait_for_ready, + compression=compression, + ) + + def future( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Any: + client_call_details = _ClientCallDetails( + self._method, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + + def continuation(new_details, request): + ( + new_method, + new_timeout, + new_metadata, + new_credentials, + new_wait_for_ready, + new_compression, + ) = _unwrap_client_call_details(new_details, client_call_details) + return self._thunk(new_method).future( + request, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, + wait_for_ready=new_wait_for_ready, + compression=new_compression, + ) + + try: + return self._interceptor.intercept_unary_unary( + continuation, client_call_details, request + ) + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + + +class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): + _thunk: Callable + _method: str + _interceptor: grpc.UnaryStreamClientInterceptor + + def __init__( + self, + thunk: Callable, + method: str, + interceptor: grpc.UnaryStreamClientInterceptor, + ): + self._thunk = thunk + self._method = method + self._interceptor = interceptor + + def __call__( + self, + request: Any, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ): + client_call_details = _ClientCallDetails( + self._method, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + + def continuation(new_details, request): + ( + new_method, + new_timeout, + new_metadata, + new_credentials, + new_wait_for_ready, + new_compression, + ) = _unwrap_client_call_details(new_details, client_call_details) + return self._thunk(new_method)( + request, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, + wait_for_ready=new_wait_for_ready, + compression=new_compression, + ) + + try: + return self._interceptor.intercept_unary_stream( + continuation, client_call_details, request + ) + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + + +class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): + _thunk: Callable + _method: str + _interceptor: grpc.StreamUnaryClientInterceptor + + def __init__( + self, + thunk: Callable, + method: str, + interceptor: grpc.StreamUnaryClientInterceptor, + ): + self._thunk = thunk + self._method = method + self._interceptor = interceptor + + def __call__( + self, + request_iterator: RequestIterableType, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Any: + response, ignored_call = self._with_call( + request_iterator, + timeout=timeout, + metadata=metadata, + credentials=credentials, + wait_for_ready=wait_for_ready, + compression=compression, + ) + return response + + def _with_call( + self, + request_iterator: RequestIterableType, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Tuple[Any, grpc.Call]: + client_call_details = _ClientCallDetails( + self._method, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + + def continuation(new_details, request_iterator): + ( + new_method, + new_timeout, + new_metadata, + new_credentials, + new_wait_for_ready, + new_compression, + ) = _unwrap_client_call_details(new_details, client_call_details) + try: + response, call = self._thunk(new_method).with_call( + request_iterator, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, + wait_for_ready=new_wait_for_ready, + compression=new_compression, + ) + return _UnaryOutcome(response, call) + except grpc.RpcError as rpc_error: + return rpc_error + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + + call = self._interceptor.intercept_stream_unary( + continuation, client_call_details, request_iterator + ) + return call.result(), call + + def with_call( + self, + request_iterator: RequestIterableType, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Tuple[Any, grpc.Call]: + return self._with_call( + request_iterator, + timeout=timeout, + metadata=metadata, + credentials=credentials, + wait_for_ready=wait_for_ready, + compression=compression, + ) + + def future( + self, + request_iterator: RequestIterableType, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ) -> Any: + client_call_details = _ClientCallDetails( + self._method, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + + def continuation(new_details, request_iterator): + ( + new_method, + new_timeout, + new_metadata, + new_credentials, + new_wait_for_ready, + new_compression, + ) = _unwrap_client_call_details(new_details, client_call_details) + return self._thunk(new_method).future( + request_iterator, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, + wait_for_ready=new_wait_for_ready, + compression=new_compression, + ) + + try: + return self._interceptor.intercept_stream_unary( + continuation, client_call_details, request_iterator + ) + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + + +class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): + _thunk: Callable + _method: str + _interceptor: grpc.StreamStreamClientInterceptor + + def __init__( + self, + thunk: Callable, + method: str, + interceptor: grpc.StreamStreamClientInterceptor, + ): + self._thunk = thunk + self._method = method + self._interceptor = interceptor + + def __call__( + self, + request_iterator: RequestIterableType, + timeout: Optional[float] = None, + metadata: Optional[MetadataType] = None, + credentials: Optional[grpc.CallCredentials] = None, + wait_for_ready: Optional[bool] = None, + compression: Optional[grpc.Compression] = None, + ): + client_call_details = _ClientCallDetails( + self._method, + timeout, + metadata, + credentials, + wait_for_ready, + compression, + ) + + def continuation(new_details, request_iterator): + ( + new_method, + new_timeout, + new_metadata, + new_credentials, + new_wait_for_ready, + new_compression, + ) = _unwrap_client_call_details(new_details, client_call_details) + return self._thunk(new_method)( + request_iterator, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, + wait_for_ready=new_wait_for_ready, + compression=new_compression, + ) + + try: + return self._interceptor.intercept_stream_stream( + continuation, client_call_details, request_iterator + ) + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + + +class _Channel(grpc.Channel): + _channel: grpc.Channel + _interceptor: Union[ + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + ] + + def __init__( + self, + channel: grpc.Channel, + interceptor: Union[ + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + ], + ): + self._channel = channel + self._interceptor = interceptor + + def subscribe( + self, callback: Callable, try_to_connect: Optional[bool] = False + ): + self._channel.subscribe(callback, try_to_connect=try_to_connect) + + def unsubscribe(self, callback: Callable): + self._channel.unsubscribe(callback) + + # pylint: disable=arguments-differ + def unary_unary( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.UnaryUnaryMultiCallable: + # pytype: disable=wrong-arg-count + thunk = lambda m: self._channel.unary_unary( + m, + request_serializer, + response_deserializer, + _registered_method, + ) + # pytype: enable=wrong-arg-count + if isinstance(self._interceptor, grpc.UnaryUnaryClientInterceptor): + return _UnaryUnaryMultiCallable(thunk, method, self._interceptor) + else: + return thunk(method) + + # pylint: disable=arguments-differ + def unary_stream( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.UnaryStreamMultiCallable: + # pytype: disable=wrong-arg-count + thunk = lambda m: self._channel.unary_stream( + m, + request_serializer, + response_deserializer, + _registered_method, + ) + # pytype: enable=wrong-arg-count + if isinstance(self._interceptor, grpc.UnaryStreamClientInterceptor): + return _UnaryStreamMultiCallable(thunk, method, self._interceptor) + else: + return thunk(method) + + # pylint: disable=arguments-differ + def stream_unary( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.StreamUnaryMultiCallable: + # pytype: disable=wrong-arg-count + thunk = lambda m: self._channel.stream_unary( + m, + request_serializer, + response_deserializer, + _registered_method, + ) + # pytype: enable=wrong-arg-count + if isinstance(self._interceptor, grpc.StreamUnaryClientInterceptor): + return _StreamUnaryMultiCallable(thunk, method, self._interceptor) + else: + return thunk(method) + + # pylint: disable=arguments-differ + def stream_stream( + self, + method: str, + request_serializer: Optional[SerializingFunction] = None, + response_deserializer: Optional[DeserializingFunction] = None, + _registered_method: Optional[bool] = False, + ) -> grpc.StreamStreamMultiCallable: + # pytype: disable=wrong-arg-count + thunk = lambda m: self._channel.stream_stream( + m, + request_serializer, + response_deserializer, + _registered_method, + ) + # pytype: enable=wrong-arg-count + if isinstance(self._interceptor, grpc.StreamStreamClientInterceptor): + return _StreamStreamMultiCallable(thunk, method, self._interceptor) + else: + return thunk(method) + + def _close(self): + self._channel.close() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self._close() + return False + + def close(self): + self._channel.close() + + +def intercept_channel( + channel: grpc.Channel, + *interceptors: Optional[ + Sequence[ + Union[ + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + ] + ] + ], +) -> grpc.Channel: + for interceptor in reversed(list(interceptors)): + if ( + not isinstance(interceptor, grpc.UnaryUnaryClientInterceptor) + and not isinstance(interceptor, grpc.UnaryStreamClientInterceptor) + and not isinstance(interceptor, grpc.StreamUnaryClientInterceptor) + and not isinstance(interceptor, grpc.StreamStreamClientInterceptor) + ): + raise TypeError( + "interceptor must be " + "grpc.UnaryUnaryClientInterceptor or " + "grpc.UnaryStreamClientInterceptor or " + "grpc.StreamUnaryClientInterceptor or " + "grpc.StreamStreamClientInterceptor or " + ) + channel = _Channel(channel, interceptor) + return channel diff --git a/python_embeded/Lib/site-packages/grpc/_observability.py b/python_embeded/Lib/site-packages/grpc/_observability.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3216556a857ad8fe2f486d2bbab93573197901 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_observability.py @@ -0,0 +1,299 @@ +# Copyright 2023 The gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import abc +import contextlib +import logging +import threading +from typing import Any, Generator, Generic, List, Optional, TypeVar + +from grpc._cython import cygrpc as _cygrpc +from grpc._typing import ChannelArgumentType + +_LOGGER = logging.getLogger(__name__) + +_channel = Any # _channel.py imports this module. +ClientCallTracerCapsule = TypeVar("ClientCallTracerCapsule") +ServerCallTracerFactoryCapsule = TypeVar("ServerCallTracerFactoryCapsule") + +_plugin_lock: threading.RLock = threading.RLock() +_OBSERVABILITY_PLUGIN: Optional["ObservabilityPlugin"] = None +_SERVICES_TO_EXCLUDE: List[bytes] = [ + b"google.monitoring.v3.MetricService", + b"google.devtools.cloudtrace.v2.TraceService", +] + + +class ServerCallTracerFactory: + """An encapsulation of a ServerCallTracerFactory. + + Instances of this class can be passed to a Channel as values for the + grpc.experimental.server_call_tracer_factory option + """ + + def __init__(self, address): + self._address = address + + def __int__(self): + return self._address + + +class ObservabilityPlugin( + Generic[ClientCallTracerCapsule, ServerCallTracerFactoryCapsule], + metaclass=abc.ABCMeta, +): + """Abstract base class for observability plugin. + + *This is a semi-private class that was intended for the exclusive use of + the gRPC team.* + + The ClientCallTracerCapsule and ClientCallTracerCapsule created by this + plugin should be injected to gRPC core using observability_init at the + start of a program, before any channels/servers are built. + + Any future methods added to this interface cannot have the + @abc.abstractmethod annotation. + + Attributes: + _stats_enabled: A bool indicates whether tracing is enabled. + _tracing_enabled: A bool indicates whether stats(metrics) is enabled. + _registered_methods: A set which stores the registered method names in + bytes. + """ + + _tracing_enabled: bool = False + _stats_enabled: bool = False + + @abc.abstractmethod + def create_client_call_tracer( + self, method_name: bytes, target: bytes + ) -> ClientCallTracerCapsule: + """Creates a ClientCallTracerCapsule. + + After register the plugin, if tracing or stats is enabled, this method + will be called after a call was created, the ClientCallTracer created + by this method will be saved to call context. + + The ClientCallTracer is an object which implements `grpc_core::ClientCallTracer` + interface and wrapped in a PyCapsule using `client_call_tracer` as name. + + Args: + method_name: The method name of the call in byte format. + target: The channel target of the call in byte format. + registered_method: Whether this method is pre-registered. + + Returns: + A PyCapsule which stores a ClientCallTracer object. + """ + raise NotImplementedError() + + @abc.abstractmethod + def save_trace_context( + self, trace_id: str, span_id: str, is_sampled: bool + ) -> None: + """Saves the trace_id and span_id related to the current span. + + After register the plugin, if tracing is enabled, this method will be + called after the server finished sending response. + + This method can be used to propagate census context. + + Args: + trace_id: The identifier for the trace associated with the span as a + 32-character hexadecimal encoded string, + e.g. 26ed0036f2eff2b7317bccce3e28d01f + span_id: The identifier for the span as a 16-character hexadecimal encoded + string. e.g. 113ec879e62583bc + is_sampled: A bool indicates whether the span is sampled. + """ + raise NotImplementedError() + + @abc.abstractmethod + def create_server_call_tracer_factory( + self, + *, + xds: bool = False, + ) -> Optional[ServerCallTracerFactoryCapsule]: + """Creates a ServerCallTracerFactoryCapsule. + + This method will be called at server initialization time to create a + ServerCallTracerFactory, which will be registered to gRPC core. + + The ServerCallTracerFactory is an object which implements + `grpc_core::ServerCallTracerFactory` interface and wrapped in a PyCapsule + using `server_call_tracer_factory` as name. + + Args: + xds: Whether the server is xds server. + Returns: + A PyCapsule which stores a ServerCallTracerFactory object. Or None if + plugin decides not to create ServerCallTracerFactory. + """ + raise NotImplementedError() + + @abc.abstractmethod + def record_rpc_latency( + self, method: str, target: str, rpc_latency: float, status_code: Any + ) -> None: + """Record the latency of the RPC. + + After register the plugin, if stats is enabled, this method will be + called at the end of each RPC. + + Args: + method: The fully-qualified name of the RPC method being invoked. + target: The target name of the RPC method being invoked. + rpc_latency: The latency for the RPC in seconds, equals to the time between + when the client invokes the RPC and when the client receives the status. + status_code: An element of grpc.StatusCode in string format representing the + final status for the RPC. + """ + raise NotImplementedError() + + def set_tracing(self, enable: bool) -> None: + """Enable or disable tracing. + + Args: + enable: A bool indicates whether tracing should be enabled. + """ + self._tracing_enabled = enable + + def set_stats(self, enable: bool) -> None: + """Enable or disable stats(metrics). + + Args: + enable: A bool indicates whether stats should be enabled. + """ + self._stats_enabled = enable + + def save_registered_method(self, method_name: bytes) -> None: + """Saves the method name to registered_method list. + + When exporting metrics, method name for unregistered methods will be replaced + with 'other' by default. + + Args: + method_name: The method name in bytes. + """ + raise NotImplementedError() + + @property + def tracing_enabled(self) -> bool: + return self._tracing_enabled + + @property + def stats_enabled(self) -> bool: + return self._stats_enabled + + @property + def observability_enabled(self) -> bool: + return self.tracing_enabled or self.stats_enabled + + +@contextlib.contextmanager +def get_plugin() -> Generator[Optional[ObservabilityPlugin], None, None]: + """Get the ObservabilityPlugin in _observability module. + + Returns: + The ObservabilityPlugin currently registered with the _observability + module. Or None if no plugin exists at the time of calling this method. + """ + with _plugin_lock: + yield _OBSERVABILITY_PLUGIN + + +def set_plugin(observability_plugin: Optional[ObservabilityPlugin]) -> None: + """Save ObservabilityPlugin to _observability module. + + Args: + observability_plugin: The ObservabilityPlugin to save. + + Raises: + ValueError: If an ObservabilityPlugin was already registered at the + time of calling this method. + """ + global _OBSERVABILITY_PLUGIN # pylint: disable=global-statement + with _plugin_lock: + if observability_plugin and _OBSERVABILITY_PLUGIN: + raise ValueError("observability_plugin was already set!") + _OBSERVABILITY_PLUGIN = observability_plugin + + +def observability_init(observability_plugin: ObservabilityPlugin) -> None: + """Initialize observability with provided ObservabilityPlugin. + + This method have to be called at the start of a program, before any + channels/servers are built. + + Args: + observability_plugin: The ObservabilityPlugin to use. + + Raises: + ValueError: If an ObservabilityPlugin was already registered at the + time of calling this method. + """ + set_plugin(observability_plugin) + + +def observability_deinit() -> None: + """Clear the observability context, including ObservabilityPlugin and + ServerCallTracerFactory + + This method have to be called after exit observability context so that + it's possible to re-initialize again. + """ + set_plugin(None) + _cygrpc.clear_server_call_tracer_factory() + + +def maybe_record_rpc_latency(state: "_channel._RPCState") -> None: + """Record the latency of the RPC, if the plugin is registered and stats is enabled. + + This method will be called at the end of each RPC. + + Args: + state: a grpc._channel._RPCState object which contains the stats related to the + RPC. + """ + # TODO(xuanwn): use channel args to exclude those metrics. + for exclude_prefix in _SERVICES_TO_EXCLUDE: + if exclude_prefix in state.method.encode("utf8"): + return + with get_plugin() as plugin: + if plugin and plugin.stats_enabled: + rpc_latency_s = state.rpc_end_time - state.rpc_start_time + rpc_latency_ms = rpc_latency_s * 1000 + plugin.record_rpc_latency( + state.method, state.target, rpc_latency_ms, state.code + ) + + +def create_server_call_tracer_factory_option(xds: bool) -> ChannelArgumentType: + with get_plugin() as plugin: + if plugin and plugin.stats_enabled: + server_call_tracer_factory_address = ( + _cygrpc.get_server_call_tracer_factory_address(plugin, xds) + ) + if server_call_tracer_factory_address: + return ( + ( + "grpc.experimental.server_call_tracer_factory", + ServerCallTracerFactory( + server_call_tracer_factory_address + ), + ), + ) + return () diff --git a/python_embeded/Lib/site-packages/grpc/_plugin_wrapping.py b/python_embeded/Lib/site-packages/grpc/_plugin_wrapping.py new file mode 100644 index 0000000000000000000000000000000000000000..3522a60f7d86fac6cebdc134be13f713b7bc7cc6 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_plugin_wrapping.py @@ -0,0 +1,136 @@ +# Copyright 2015 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import collections +import logging +import threading +from typing import Callable, Optional, Type + +import grpc +from grpc import _common +from grpc._cython import cygrpc +from grpc._typing import MetadataType + +_LOGGER = logging.getLogger(__name__) + + +class _AuthMetadataContext( + collections.namedtuple( + "AuthMetadataContext", + ( + "service_url", + "method_name", + ), + ), + grpc.AuthMetadataContext, +): + pass + + +class _CallbackState(object): + def __init__(self): + self.lock = threading.Lock() + self.called = False + self.exception = None + + +class _AuthMetadataPluginCallback(grpc.AuthMetadataPluginCallback): + _state: _CallbackState + _callback: Callable + + def __init__(self, state: _CallbackState, callback: Callable): + self._state = state + self._callback = callback + + def __call__( + self, metadata: MetadataType, error: Optional[Type[BaseException]] + ): + with self._state.lock: + if self._state.exception is None: + if self._state.called: + raise RuntimeError( + "AuthMetadataPluginCallback invoked more than once!" + ) + else: + self._state.called = True + else: + raise RuntimeError( + 'AuthMetadataPluginCallback raised exception "{}"!'.format( + self._state.exception + ) + ) + if error is None: + self._callback(metadata, cygrpc.StatusCode.ok, None) + else: + self._callback( + None, cygrpc.StatusCode.internal, _common.encode(str(error)) + ) + + +class _Plugin(object): + _metadata_plugin: grpc.AuthMetadataPlugin + + def __init__(self, metadata_plugin: grpc.AuthMetadataPlugin): + self._metadata_plugin = metadata_plugin + self._stored_ctx = None + + try: + import contextvars # pylint: disable=wrong-import-position + + # The plugin may be invoked on a thread created by Core, which will not + # have the context propagated. This context is stored and installed in + # the thread invoking the plugin. + self._stored_ctx = contextvars.copy_context() + except ImportError: + # Support versions predating contextvars. + pass + + def __call__(self, service_url: str, method_name: str, callback: Callable): + context = _AuthMetadataContext( + _common.decode(service_url), _common.decode(method_name) + ) + callback_state = _CallbackState() + try: + self._metadata_plugin( + context, _AuthMetadataPluginCallback(callback_state, callback) + ) + except Exception as exception: # pylint: disable=broad-except + _LOGGER.exception( + 'AuthMetadataPluginCallback "%s" raised exception!', + self._metadata_plugin, + ) + with callback_state.lock: + callback_state.exception = exception + if callback_state.called: + return + callback( + None, cygrpc.StatusCode.internal, _common.encode(str(exception)) + ) + + +def metadata_plugin_call_credentials( + metadata_plugin: grpc.AuthMetadataPlugin, name: Optional[str] +) -> grpc.CallCredentials: + if name is None: + try: + effective_name = metadata_plugin.__name__ + except AttributeError: + effective_name = metadata_plugin.__class__.__name__ + else: + effective_name = name + return grpc.CallCredentials( + cygrpc.MetadataPluginCallCredentials( + _Plugin(metadata_plugin), _common.encode(effective_name) + ) + ) diff --git a/python_embeded/Lib/site-packages/grpc/_runtime_protos.py b/python_embeded/Lib/site-packages/grpc/_runtime_protos.py new file mode 100644 index 0000000000000000000000000000000000000000..04d527128eccd425c20f0db73b57763bf816c5a4 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_runtime_protos.py @@ -0,0 +1,165 @@ +# Copyright 2020 The gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys +import types +from typing import Tuple, Union + +_REQUIRED_SYMBOLS = ("_protos", "_services", "_protos_and_services") +_MINIMUM_VERSION = (3, 5, 0) + +_UNINSTALLED_TEMPLATE = ( + "Install the grpcio-tools package (1.32.0+) to use the {} function." +) +_VERSION_ERROR_TEMPLATE = ( + "The {} function is only on available on Python 3.X interpreters." +) + + +def _has_runtime_proto_symbols(mod: types.ModuleType) -> bool: + return all(hasattr(mod, sym) for sym in _REQUIRED_SYMBOLS) + + +def _is_grpc_tools_importable() -> bool: + try: + import grpc_tools # pylint: disable=unused-import # pytype: disable=import-error + + return True + except ImportError as e: + # NOTE: It's possible that we're encountering a transitive ImportError, so + # we check for that and re-raise if so. + if "grpc_tools" not in e.args[0]: + raise + return False + + +def _call_with_lazy_import( + fn_name: str, protobuf_path: str +) -> Union[types.ModuleType, Tuple[types.ModuleType, types.ModuleType]]: + """Calls one of the three functions, lazily importing grpc_tools. + + Args: + fn_name: The name of the function to import from grpc_tools.protoc. + protobuf_path: The path to import. + + Returns: + The appropriate module object. + """ + if sys.version_info < _MINIMUM_VERSION: + raise NotImplementedError(_VERSION_ERROR_TEMPLATE.format(fn_name)) + else: + if not _is_grpc_tools_importable(): + raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name)) + import grpc_tools.protoc # pytype: disable=import-error + + if _has_runtime_proto_symbols(grpc_tools.protoc): + fn = getattr(grpc_tools.protoc, "_" + fn_name) + return fn(protobuf_path) + else: + raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name)) + + +def protos(protobuf_path): # pylint: disable=unused-argument + """Returns a module generated by the indicated .proto file. + + THIS IS AN EXPERIMENTAL API. + + Use this function to retrieve classes corresponding to message + definitions in the .proto file. + + To inspect the contents of the returned module, use the dir function. + For example: + + ``` + protos = grpc.protos("foo.proto") + print(dir(protos)) + ``` + + The returned module object corresponds to the _pb2.py file generated + by protoc. The path is expected to be relative to an entry on sys.path + and all transitive dependencies of the file should also be resolvable + from an entry on sys.path. + + To completely disable the machinery behind this function, set the + GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true". + + Args: + protobuf_path: The path to the .proto file on the filesystem. This path + must be resolvable from an entry on sys.path and so must all of its + transitive dependencies. + + Returns: + A module object corresponding to the message code for the indicated + .proto file. Equivalent to a generated _pb2.py file. + """ + return _call_with_lazy_import("protos", protobuf_path) + + +def services(protobuf_path): # pylint: disable=unused-argument + """Returns a module generated by the indicated .proto file. + + THIS IS AN EXPERIMENTAL API. + + Use this function to retrieve classes and functions corresponding to + service definitions in the .proto file, including both stub and servicer + definitions. + + To inspect the contents of the returned module, use the dir function. + For example: + + ``` + services = grpc.services("foo.proto") + print(dir(services)) + ``` + + The returned module object corresponds to the _pb2_grpc.py file generated + by protoc. The path is expected to be relative to an entry on sys.path + and all transitive dependencies of the file should also be resolvable + from an entry on sys.path. + + To completely disable the machinery behind this function, set the + GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true". + + Args: + protobuf_path: The path to the .proto file on the filesystem. This path + must be resolvable from an entry on sys.path and so must all of its + transitive dependencies. + + Returns: + A module object corresponding to the stub/service code for the indicated + .proto file. Equivalent to a generated _pb2_grpc.py file. + """ + return _call_with_lazy_import("services", protobuf_path) + + +def protos_and_services(protobuf_path): # pylint: disable=unused-argument + """Returns a 2-tuple of modules corresponding to protos and services. + + THIS IS AN EXPERIMENTAL API. + + The return value of this function is equivalent to a call to protos and a + call to services. + + To completely disable the machinery behind this function, set the + GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true". + + Args: + protobuf_path: The path to the .proto file on the filesystem. This path + must be resolvable from an entry on sys.path and so must all of its + transitive dependencies. + + Returns: + A 2-tuple of module objects corresponding to (protos(path), services(path)). + """ + return _call_with_lazy_import("protos_and_services", protobuf_path) diff --git a/python_embeded/Lib/site-packages/grpc/_server.py b/python_embeded/Lib/site-packages/grpc/_server.py new file mode 100644 index 0000000000000000000000000000000000000000..76356bd5fce760cb6040c701b2e88a16d5aca744 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_server.py @@ -0,0 +1,1528 @@ +# Copyright 2016 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Service-side implementation of gRPC Python.""" + +from __future__ import annotations + +import abc +import collections +from concurrent import futures +import contextvars +import enum +import logging +import threading +import time +import traceback +from typing import ( + Any, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Set, + Tuple, + Union, +) + +import grpc # pytype: disable=pyi-error +from grpc import _common # pytype: disable=pyi-error +from grpc import _compression # pytype: disable=pyi-error +from grpc import _interceptor # pytype: disable=pyi-error +from grpc import _observability # pytype: disable=pyi-error +from grpc._cython import cygrpc +from grpc._typing import ArityAgnosticMethodHandler +from grpc._typing import ChannelArgumentType +from grpc._typing import DeserializingFunction +from grpc._typing import MetadataType +from grpc._typing import NullaryCallbackType +from grpc._typing import ResponseType +from grpc._typing import SerializingFunction +from grpc._typing import ServerCallbackTag +from grpc._typing import ServerTagCallbackType + +_LOGGER = logging.getLogger(__name__) + +_SHUTDOWN_TAG = "shutdown" +_REQUEST_CALL_TAG = "request_call" + +_RECEIVE_CLOSE_ON_SERVER_TOKEN = "receive_close_on_server" +_SEND_INITIAL_METADATA_TOKEN = "send_initial_metadata" +_RECEIVE_MESSAGE_TOKEN = "receive_message" +_SEND_MESSAGE_TOKEN = "send_message" +_SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN = ( + "send_initial_metadata * send_message" +) +_SEND_STATUS_FROM_SERVER_TOKEN = "send_status_from_server" +_SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN = ( + "send_initial_metadata * send_status_from_server" +) + +_OPEN = "open" +_CLOSED = "closed" +_CANCELLED = "cancelled" + +_EMPTY_FLAGS = 0 + +_DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0 +_INF_TIMEOUT = 1e9 + + +def _serialized_request(request_event: cygrpc.BaseEvent) -> bytes: + return request_event.batch_operations[0].message() + + +def _application_code(code: grpc.StatusCode) -> cygrpc.StatusCode: + cygrpc_code = _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE.get(code) + return cygrpc.StatusCode.unknown if cygrpc_code is None else cygrpc_code + + +def _completion_code(state: _RPCState) -> cygrpc.StatusCode: + if state.code is None: + return cygrpc.StatusCode.ok + else: + return _application_code(state.code) + + +def _abortion_code( + state: _RPCState, code: cygrpc.StatusCode +) -> cygrpc.StatusCode: + if state.code is None: + return code + else: + return _application_code(state.code) + + +def _details(state: _RPCState) -> bytes: + return b"" if state.details is None else state.details + + +class _HandlerCallDetails( + collections.namedtuple( + "_HandlerCallDetails", + ( + "method", + "invocation_metadata", + ), + ), + grpc.HandlerCallDetails, +): + pass + + +class _Method(abc.ABC): + @abc.abstractmethod + def name(self) -> Optional[str]: + raise NotImplementedError() + + @abc.abstractmethod + def handler( + self, handler_call_details: _HandlerCallDetails + ) -> Optional[grpc.RpcMethodHandler]: + raise NotImplementedError() + + +class _RegisteredMethod(_Method): + def __init__( + self, + name: str, + registered_handler: Optional[grpc.RpcMethodHandler], + ): + self._name = name + self._registered_handler = registered_handler + + def name(self) -> Optional[str]: + return self._name + + def handler( + self, handler_call_details: _HandlerCallDetails + ) -> Optional[grpc.RpcMethodHandler]: + return self._registered_handler + + +class _GenericMethod(_Method): + def __init__( + self, + generic_handlers: List[grpc.GenericRpcHandler], + ): + self._generic_handlers = generic_handlers + + def name(self) -> Optional[str]: + return None + + def handler( + self, handler_call_details: _HandlerCallDetails + ) -> Optional[grpc.RpcMethodHandler]: + # If the same method have both generic and registered handler, + # registered handler will take precedence. + for generic_handler in self._generic_handlers: + method_handler = generic_handler.service(handler_call_details) + if method_handler is not None: + return method_handler + return None + + +class _RPCState(object): + context: contextvars.Context + condition: threading.Condition + due = Set[str] + request: Any + client: str + initial_metadata_allowed: bool + compression_algorithm: Optional[grpc.Compression] + disable_next_compression: bool + trailing_metadata: Optional[MetadataType] + code: Optional[grpc.StatusCode] + details: Optional[bytes] + statused: bool + rpc_errors: List[Exception] + callbacks: Optional[List[NullaryCallbackType]] + aborted: bool + + def __init__(self): + self.context = contextvars.Context() + self.condition = threading.Condition() + self.due = set() + self.request = None + self.client = _OPEN + self.initial_metadata_allowed = True + self.compression_algorithm = None + self.disable_next_compression = False + self.trailing_metadata = None + self.code = None + self.details = None + self.statused = False + self.rpc_errors = [] + self.callbacks = [] + self.aborted = False + + +def _raise_rpc_error(state: _RPCState) -> None: + rpc_error = grpc.RpcError() + state.rpc_errors.append(rpc_error) + raise rpc_error + + +def _possibly_finish_call( + state: _RPCState, token: str +) -> ServerTagCallbackType: + state.due.remove(token) + if not _is_rpc_state_active(state) and not state.due: + callbacks = state.callbacks + state.callbacks = None + return state, callbacks + else: + return None, () + + +def _send_status_from_server(state: _RPCState, token: str) -> ServerCallbackTag: + def send_status_from_server(unused_send_status_from_server_event): + with state.condition: + return _possibly_finish_call(state, token) + + return send_status_from_server + + +def _get_initial_metadata( + state: _RPCState, metadata: Optional[MetadataType] +) -> Optional[MetadataType]: + with state.condition: + if state.compression_algorithm: + compression_metadata = ( + _compression.compression_algorithm_to_metadata( + state.compression_algorithm + ), + ) + if metadata is None: + return compression_metadata + else: + return compression_metadata + tuple(metadata) + else: + return metadata + + +def _get_initial_metadata_operation( + state: _RPCState, metadata: Optional[MetadataType] +) -> cygrpc.Operation: + operation = cygrpc.SendInitialMetadataOperation( + _get_initial_metadata(state, metadata), _EMPTY_FLAGS + ) + return operation + + +def _abort( + state: _RPCState, call: cygrpc.Call, code: cygrpc.StatusCode, details: bytes +) -> None: + if state.client is not _CANCELLED: + effective_code = _abortion_code(state, code) + effective_details = details if state.details is None else state.details + if state.initial_metadata_allowed: + operations = ( + _get_initial_metadata_operation(state, None), + cygrpc.SendStatusFromServerOperation( + state.trailing_metadata, + effective_code, + effective_details, + _EMPTY_FLAGS, + ), + ) + token = _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN + else: + operations = ( + cygrpc.SendStatusFromServerOperation( + state.trailing_metadata, + effective_code, + effective_details, + _EMPTY_FLAGS, + ), + ) + token = _SEND_STATUS_FROM_SERVER_TOKEN + call.start_server_batch( + operations, _send_status_from_server(state, token) + ) + state.statused = True + state.due.add(token) + + +def _receive_close_on_server(state: _RPCState) -> ServerCallbackTag: + def receive_close_on_server(receive_close_on_server_event): + with state.condition: + if receive_close_on_server_event.batch_operations[0].cancelled(): + state.client = _CANCELLED + elif state.client is _OPEN: + state.client = _CLOSED + state.condition.notify_all() + return _possibly_finish_call(state, _RECEIVE_CLOSE_ON_SERVER_TOKEN) + + return receive_close_on_server + + +def _receive_message( + state: _RPCState, + call: cygrpc.Call, + request_deserializer: Optional[DeserializingFunction], +) -> ServerCallbackTag: + def receive_message(receive_message_event): + serialized_request = _serialized_request(receive_message_event) + if serialized_request is None: + with state.condition: + if state.client is _OPEN: + state.client = _CLOSED + state.condition.notify_all() + return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN) + else: + request = _common.deserialize( + serialized_request, request_deserializer + ) + with state.condition: + if request is None: + _abort( + state, + call, + cygrpc.StatusCode.internal, + b"Exception deserializing request!", + ) + else: + state.request = request + state.condition.notify_all() + return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN) + + return receive_message + + +def _send_initial_metadata(state: _RPCState) -> ServerCallbackTag: + def send_initial_metadata(unused_send_initial_metadata_event): + with state.condition: + return _possibly_finish_call(state, _SEND_INITIAL_METADATA_TOKEN) + + return send_initial_metadata + + +def _send_message(state: _RPCState, token: str) -> ServerCallbackTag: + def send_message(unused_send_message_event): + with state.condition: + state.condition.notify_all() + return _possibly_finish_call(state, token) + + return send_message + + +class _Context(grpc.ServicerContext): + _rpc_event: cygrpc.BaseEvent + _state: _RPCState + request_deserializer: Optional[DeserializingFunction] + + def __init__( + self, + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + request_deserializer: Optional[DeserializingFunction], + ): + self._rpc_event = rpc_event + self._state = state + self._request_deserializer = request_deserializer + + def is_active(self) -> bool: + with self._state.condition: + return _is_rpc_state_active(self._state) + + def time_remaining(self) -> float: + return max(self._rpc_event.call_details.deadline - time.time(), 0) + + def cancel(self) -> None: + self._rpc_event.call.cancel() + + def add_callback(self, callback: NullaryCallbackType) -> bool: + with self._state.condition: + if self._state.callbacks is None: + return False + else: + self._state.callbacks.append(callback) + return True + + def disable_next_message_compression(self) -> None: + with self._state.condition: + self._state.disable_next_compression = True + + def invocation_metadata(self) -> Optional[MetadataType]: + return self._rpc_event.invocation_metadata + + def peer(self) -> str: + return _common.decode(self._rpc_event.call.peer()) + + def peer_identities(self) -> Optional[Sequence[bytes]]: + return cygrpc.peer_identities(self._rpc_event.call) + + def peer_identity_key(self) -> Optional[str]: + id_key = cygrpc.peer_identity_key(self._rpc_event.call) + return id_key if id_key is None else _common.decode(id_key) + + def auth_context(self) -> Mapping[str, Sequence[bytes]]: + auth_context = cygrpc.auth_context(self._rpc_event.call) + auth_context_dict = {} if auth_context is None else auth_context + return { + _common.decode(key): value + for key, value in auth_context_dict.items() + } + + def set_compression(self, compression: grpc.Compression) -> None: + with self._state.condition: + self._state.compression_algorithm = compression + + def send_initial_metadata(self, initial_metadata: MetadataType) -> None: + with self._state.condition: + if self._state.client is _CANCELLED: + _raise_rpc_error(self._state) + else: + if self._state.initial_metadata_allowed: + operation = _get_initial_metadata_operation( + self._state, initial_metadata + ) + self._rpc_event.call.start_server_batch( + (operation,), _send_initial_metadata(self._state) + ) + self._state.initial_metadata_allowed = False + self._state.due.add(_SEND_INITIAL_METADATA_TOKEN) + else: + raise ValueError("Initial metadata no longer allowed!") + + def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None: + with self._state.condition: + self._state.trailing_metadata = trailing_metadata + + def trailing_metadata(self) -> Optional[MetadataType]: + return self._state.trailing_metadata + + def abort(self, code: grpc.StatusCode, details: str) -> None: + # treat OK like other invalid arguments: fail the RPC + if code == grpc.StatusCode.OK: + _LOGGER.error( + "abort() called with StatusCode.OK; returning UNKNOWN" + ) + code = grpc.StatusCode.UNKNOWN + details = "" + with self._state.condition: + self._state.code = code + self._state.details = _common.encode(details) + self._state.aborted = True + raise Exception() + + def abort_with_status(self, status: grpc.Status) -> None: + self._state.trailing_metadata = status.trailing_metadata + self.abort(status.code, status.details) + + def set_code(self, code: grpc.StatusCode) -> None: + with self._state.condition: + self._state.code = code + + def code(self) -> grpc.StatusCode: + return self._state.code + + def set_details(self, details: str) -> None: + with self._state.condition: + self._state.details = _common.encode(details) + + def details(self) -> bytes: + return self._state.details + + def _finalize_state(self) -> None: + pass + + +class _RequestIterator(object): + _state: _RPCState + _call: cygrpc.Call + _request_deserializer: Optional[DeserializingFunction] + + def __init__( + self, + state: _RPCState, + call: cygrpc.Call, + request_deserializer: Optional[DeserializingFunction], + ): + self._state = state + self._call = call + self._request_deserializer = request_deserializer + + def _raise_or_start_receive_message(self) -> None: + if self._state.client is _CANCELLED: + _raise_rpc_error(self._state) + elif not _is_rpc_state_active(self._state): + raise StopIteration() + else: + self._call.start_server_batch( + (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), + _receive_message( + self._state, self._call, self._request_deserializer + ), + ) + self._state.due.add(_RECEIVE_MESSAGE_TOKEN) + + def _look_for_request(self) -> Any: + if self._state.client is _CANCELLED: + _raise_rpc_error(self._state) + elif ( + self._state.request is None + and _RECEIVE_MESSAGE_TOKEN not in self._state.due + ): + raise StopIteration() + else: + request = self._state.request + self._state.request = None + return request + + raise AssertionError() # should never run + + def _next(self) -> Any: + with self._state.condition: + self._raise_or_start_receive_message() + while True: + self._state.condition.wait() + request = self._look_for_request() + if request is not None: + return request + + def __iter__(self) -> _RequestIterator: + return self + + def __next__(self) -> Any: + return self._next() + + def next(self) -> Any: + return self._next() + + +def _unary_request( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + request_deserializer: Optional[DeserializingFunction], +) -> Callable[[], Any]: + def unary_request(): + with state.condition: + if not _is_rpc_state_active(state): + return None + else: + rpc_event.call.start_server_batch( + (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), + _receive_message( + state, rpc_event.call, request_deserializer + ), + ) + state.due.add(_RECEIVE_MESSAGE_TOKEN) + while True: + state.condition.wait() + if state.request is None: + if state.client is _CLOSED: + details = '"{}" requires exactly one request message.'.format( + rpc_event.call_details.method + ) + _abort( + state, + rpc_event.call, + cygrpc.StatusCode.unimplemented, + _common.encode(details), + ) + return None + elif state.client is _CANCELLED: + return None + else: + request = state.request + state.request = None + return request + + return unary_request + + +def _call_behavior( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + behavior: ArityAgnosticMethodHandler, + argument: Any, + request_deserializer: Optional[DeserializingFunction], + send_response_callback: Optional[Callable[[ResponseType], None]] = None, +) -> Tuple[Union[ResponseType, Iterator[ResponseType]], bool]: + from grpc import _create_servicer_context # pytype: disable=pyi-error + + with _create_servicer_context( + rpc_event, state, request_deserializer + ) as context: + try: + response_or_iterator = None + if send_response_callback is not None: + response_or_iterator = behavior( + argument, context, send_response_callback + ) + else: + response_or_iterator = behavior(argument, context) + return response_or_iterator, True + except Exception as exception: # pylint: disable=broad-except + with state.condition: + if state.aborted: + _abort( + state, + rpc_event.call, + cygrpc.StatusCode.unknown, + b"RPC Aborted", + ) + elif exception not in state.rpc_errors: + try: + details = "Exception calling application: {}".format( + exception + ) + except Exception: # pylint: disable=broad-except + details = ( + "Calling application raised unprintable Exception!" + ) + _LOGGER.exception( + traceback.format_exception( + type(exception), + exception, + exception.__traceback__, + ) + ) + traceback.print_exc() + _LOGGER.exception(details) + _abort( + state, + rpc_event.call, + cygrpc.StatusCode.unknown, + _common.encode(details), + ) + return None, False + + +def _take_response_from_response_iterator( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + response_iterator: Iterator[ResponseType], +) -> Tuple[ResponseType, bool]: + try: + return next(response_iterator), True + except StopIteration: + return None, True + except Exception as exception: # pylint: disable=broad-except + with state.condition: + if state.aborted: + _abort( + state, + rpc_event.call, + cygrpc.StatusCode.unknown, + b"RPC Aborted", + ) + elif exception not in state.rpc_errors: + details = "Exception iterating responses: {}".format(exception) + _LOGGER.exception(details) + _abort( + state, + rpc_event.call, + cygrpc.StatusCode.unknown, + _common.encode(details), + ) + return None, False + + +def _serialize_response( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + response: Any, + response_serializer: Optional[SerializingFunction], +) -> Optional[bytes]: + serialized_response = _common.serialize(response, response_serializer) + if serialized_response is None: + with state.condition: + _abort( + state, + rpc_event.call, + cygrpc.StatusCode.internal, + b"Failed to serialize response!", + ) + return None + else: + return serialized_response + + +def _get_send_message_op_flags_from_state( + state: _RPCState, +) -> Union[int, cygrpc.WriteFlag]: + if state.disable_next_compression: + return cygrpc.WriteFlag.no_compress + else: + return _EMPTY_FLAGS + + +def _reset_per_message_state(state: _RPCState) -> None: + with state.condition: + state.disable_next_compression = False + + +def _send_response( + rpc_event: cygrpc.BaseEvent, state: _RPCState, serialized_response: bytes +) -> bool: + with state.condition: + if not _is_rpc_state_active(state): + return False + else: + if state.initial_metadata_allowed: + operations = ( + _get_initial_metadata_operation(state, None), + cygrpc.SendMessageOperation( + serialized_response, + _get_send_message_op_flags_from_state(state), + ), + ) + state.initial_metadata_allowed = False + token = _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN + else: + operations = ( + cygrpc.SendMessageOperation( + serialized_response, + _get_send_message_op_flags_from_state(state), + ), + ) + token = _SEND_MESSAGE_TOKEN + rpc_event.call.start_server_batch( + operations, _send_message(state, token) + ) + state.due.add(token) + _reset_per_message_state(state) + while True: + state.condition.wait() + if token not in state.due: + return _is_rpc_state_active(state) + + +def _status( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + serialized_response: Optional[bytes], +) -> None: + with state.condition: + if state.client is not _CANCELLED: + code = _completion_code(state) + details = _details(state) + operations = [ + cygrpc.SendStatusFromServerOperation( + state.trailing_metadata, code, details, _EMPTY_FLAGS + ), + ] + if state.initial_metadata_allowed: + operations.append(_get_initial_metadata_operation(state, None)) + if serialized_response is not None: + operations.append( + cygrpc.SendMessageOperation( + serialized_response, + _get_send_message_op_flags_from_state(state), + ) + ) + rpc_event.call.start_server_batch( + operations, + _send_status_from_server(state, _SEND_STATUS_FROM_SERVER_TOKEN), + ) + state.statused = True + _reset_per_message_state(state) + state.due.add(_SEND_STATUS_FROM_SERVER_TOKEN) + + +def _unary_response_in_pool( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + behavior: ArityAgnosticMethodHandler, + argument_thunk: Callable[[], Any], + request_deserializer: Optional[SerializingFunction], + response_serializer: Optional[SerializingFunction], +) -> None: + cygrpc.install_context_from_request_call_event(rpc_event) + + try: + argument = argument_thunk() + if argument is not None: + response, proceed = _call_behavior( + rpc_event, state, behavior, argument, request_deserializer + ) + if proceed: + serialized_response = _serialize_response( + rpc_event, state, response, response_serializer + ) + if serialized_response is not None: + _status(rpc_event, state, serialized_response) + except Exception: # pylint: disable=broad-except + traceback.print_exc() + finally: + cygrpc.uninstall_context() + + +def _stream_response_in_pool( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + behavior: ArityAgnosticMethodHandler, + argument_thunk: Callable[[], Any], + request_deserializer: Optional[DeserializingFunction], + response_serializer: Optional[SerializingFunction], +) -> None: + cygrpc.install_context_from_request_call_event(rpc_event) + + def send_response(response: Any) -> None: + if response is None: + _status(rpc_event, state, None) + else: + serialized_response = _serialize_response( + rpc_event, state, response, response_serializer + ) + if serialized_response is not None: + _send_response(rpc_event, state, serialized_response) + + try: + argument = argument_thunk() + if argument is not None: + if ( + hasattr(behavior, "experimental_non_blocking") + and behavior.experimental_non_blocking + ): + _call_behavior( + rpc_event, + state, + behavior, + argument, + request_deserializer, + send_response_callback=send_response, + ) + else: + response_iterator, proceed = _call_behavior( + rpc_event, state, behavior, argument, request_deserializer + ) + if proceed: + _send_message_callback_to_blocking_iterator_adapter( + rpc_event, state, send_response, response_iterator + ) + except Exception: # pylint: disable=broad-except + traceback.print_exc() + finally: + cygrpc.uninstall_context() + + +def _is_rpc_state_active(state: _RPCState) -> bool: + return state.client is not _CANCELLED and not state.statused + + +def _send_message_callback_to_blocking_iterator_adapter( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + send_response_callback: Callable[[ResponseType], None], + response_iterator: Iterator[ResponseType], +) -> None: + while True: + response, proceed = _take_response_from_response_iterator( + rpc_event, state, response_iterator + ) + if proceed: + send_response_callback(response) + if not _is_rpc_state_active(state): + break + else: + break + + +def _select_thread_pool_for_behavior( + behavior: ArityAgnosticMethodHandler, + default_thread_pool: futures.ThreadPoolExecutor, +) -> futures.ThreadPoolExecutor: + if hasattr(behavior, "experimental_thread_pool") and isinstance( + behavior.experimental_thread_pool, futures.ThreadPoolExecutor + ): + return behavior.experimental_thread_pool + else: + return default_thread_pool + + +def _handle_unary_unary( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + method_handler: grpc.RpcMethodHandler, + default_thread_pool: futures.ThreadPoolExecutor, +) -> futures.Future: + unary_request = _unary_request( + rpc_event, state, method_handler.request_deserializer + ) + thread_pool = _select_thread_pool_for_behavior( + method_handler.unary_unary, default_thread_pool + ) + return thread_pool.submit( + state.context.run, + _unary_response_in_pool, + rpc_event, + state, + method_handler.unary_unary, + unary_request, + method_handler.request_deserializer, + method_handler.response_serializer, + ) + + +def _handle_unary_stream( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + method_handler: grpc.RpcMethodHandler, + default_thread_pool: futures.ThreadPoolExecutor, +) -> futures.Future: + unary_request = _unary_request( + rpc_event, state, method_handler.request_deserializer + ) + thread_pool = _select_thread_pool_for_behavior( + method_handler.unary_stream, default_thread_pool + ) + return thread_pool.submit( + state.context.run, + _stream_response_in_pool, + rpc_event, + state, + method_handler.unary_stream, + unary_request, + method_handler.request_deserializer, + method_handler.response_serializer, + ) + + +def _handle_stream_unary( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + method_handler: grpc.RpcMethodHandler, + default_thread_pool: futures.ThreadPoolExecutor, +) -> futures.Future: + request_iterator = _RequestIterator( + state, rpc_event.call, method_handler.request_deserializer + ) + thread_pool = _select_thread_pool_for_behavior( + method_handler.stream_unary, default_thread_pool + ) + return thread_pool.submit( + state.context.run, + _unary_response_in_pool, + rpc_event, + state, + method_handler.stream_unary, + lambda: request_iterator, + method_handler.request_deserializer, + method_handler.response_serializer, + ) + + +def _handle_stream_stream( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + method_handler: grpc.RpcMethodHandler, + default_thread_pool: futures.ThreadPoolExecutor, +) -> futures.Future: + request_iterator = _RequestIterator( + state, rpc_event.call, method_handler.request_deserializer + ) + thread_pool = _select_thread_pool_for_behavior( + method_handler.stream_stream, default_thread_pool + ) + return thread_pool.submit( + state.context.run, + _stream_response_in_pool, + rpc_event, + state, + method_handler.stream_stream, + lambda: request_iterator, + method_handler.request_deserializer, + method_handler.response_serializer, + ) + + +def _find_method_handler( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + method_with_handler: _Method, + interceptor_pipeline: Optional[_interceptor._ServicePipeline], +) -> Optional[grpc.RpcMethodHandler]: + def query_handlers( + handler_call_details: _HandlerCallDetails, + ) -> Optional[grpc.RpcMethodHandler]: + return method_with_handler.handler(handler_call_details) + + method_name = method_with_handler.name() + if not method_name: + method_name = _common.decode(rpc_event.call_details.method) + + handler_call_details = _HandlerCallDetails( + method_name, + rpc_event.invocation_metadata, + ) + + if interceptor_pipeline is not None: + return state.context.run( + interceptor_pipeline.execute, query_handlers, handler_call_details + ) + else: + return state.context.run(query_handlers, handler_call_details) + + +def _reject_rpc( + rpc_event: cygrpc.BaseEvent, + rpc_state: _RPCState, + status: cygrpc.StatusCode, + details: bytes, +): + operations = ( + _get_initial_metadata_operation(rpc_state, None), + cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS), + cygrpc.SendStatusFromServerOperation( + None, status, details, _EMPTY_FLAGS + ), + ) + rpc_event.call.start_server_batch( + operations, + lambda ignored_event: ( + rpc_state, + (), + ), + ) + + +def _handle_with_method_handler( + rpc_event: cygrpc.BaseEvent, + state: _RPCState, + method_handler: grpc.RpcMethodHandler, + thread_pool: futures.ThreadPoolExecutor, +) -> futures.Future: + with state.condition: + rpc_event.call.start_server_batch( + (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),), + _receive_close_on_server(state), + ) + state.due.add(_RECEIVE_CLOSE_ON_SERVER_TOKEN) + if method_handler.request_streaming: + if method_handler.response_streaming: + return _handle_stream_stream( + rpc_event, state, method_handler, thread_pool + ) + else: + return _handle_stream_unary( + rpc_event, state, method_handler, thread_pool + ) + else: + if method_handler.response_streaming: + return _handle_unary_stream( + rpc_event, state, method_handler, thread_pool + ) + else: + return _handle_unary_unary( + rpc_event, state, method_handler, thread_pool + ) + + +def _handle_call( + rpc_event: cygrpc.BaseEvent, + method_with_handler: _Method, + interceptor_pipeline: Optional[_interceptor._ServicePipeline], + thread_pool: futures.ThreadPoolExecutor, + concurrency_exceeded: bool, +) -> Tuple[Optional[_RPCState], Optional[futures.Future]]: + """Handles RPC based on provided handlers. + + When receiving a call event from Core, registered method will have its + name as tag, we pass the tag as registered_method_name to this method, + then we can find the handler in registered_method_handlers based on + the method name. + + For call event with unregistered method, the method name will be included + in rpc_event.call_details.method and we need to query the generics handlers + to find the actual handler. + """ + if not rpc_event.success: + return None, None + if rpc_event.call_details.method or method_with_handler.name(): + rpc_state = _RPCState() + try: + method_handler = _find_method_handler( + rpc_event, + rpc_state, + method_with_handler, + interceptor_pipeline, + ) + except Exception as exception: # pylint: disable=broad-except + details = "Exception servicing handler: {}".format(exception) + _LOGGER.exception(details) + _reject_rpc( + rpc_event, + rpc_state, + cygrpc.StatusCode.unknown, + b"Error in service handler!", + ) + return rpc_state, None + if method_handler is None: + _reject_rpc( + rpc_event, + rpc_state, + cygrpc.StatusCode.unimplemented, + b"Method not found!", + ) + return rpc_state, None + elif concurrency_exceeded: + _reject_rpc( + rpc_event, + rpc_state, + cygrpc.StatusCode.resource_exhausted, + b"Concurrent RPC limit exceeded!", + ) + return rpc_state, None + else: + return ( + rpc_state, + _handle_with_method_handler( + rpc_event, rpc_state, method_handler, thread_pool + ), + ) + else: + return None, None + + +@enum.unique +class _ServerStage(enum.Enum): + STOPPED = "stopped" + STARTED = "started" + GRACE = "grace" + + +class _ServerState(object): + lock: threading.RLock + completion_queue: cygrpc.CompletionQueue + server: cygrpc.Server + generic_handlers: List[grpc.GenericRpcHandler] + registered_method_handlers: Dict[str, grpc.RpcMethodHandler] + interceptor_pipeline: Optional[_interceptor._ServicePipeline] + thread_pool: futures.ThreadPoolExecutor + stage: _ServerStage + termination_event: threading.Event + shutdown_events: List[threading.Event] + maximum_concurrent_rpcs: Optional[int] + active_rpc_count: int + rpc_states: Set[_RPCState] + due: Set[str] + server_deallocated: bool + + # pylint: disable=too-many-arguments + def __init__( + self, + completion_queue: cygrpc.CompletionQueue, + server: cygrpc.Server, + generic_handlers: Sequence[grpc.GenericRpcHandler], + interceptor_pipeline: Optional[_interceptor._ServicePipeline], + thread_pool: futures.ThreadPoolExecutor, + maximum_concurrent_rpcs: Optional[int], + ): + self.lock = threading.RLock() + self.completion_queue = completion_queue + self.server = server + self.generic_handlers = list(generic_handlers) + self.interceptor_pipeline = interceptor_pipeline + self.thread_pool = thread_pool + self.stage = _ServerStage.STOPPED + self.termination_event = threading.Event() + self.shutdown_events = [self.termination_event] + self.maximum_concurrent_rpcs = maximum_concurrent_rpcs + self.active_rpc_count = 0 + self.registered_method_handlers = {} + + # TODO(https://github.com/grpc/grpc/issues/6597): eliminate these fields. + self.rpc_states = set() + self.due = set() + + # A "volatile" flag to interrupt the daemon serving thread + self.server_deallocated = False + + +def _add_generic_handlers( + state: _ServerState, generic_handlers: Iterable[grpc.GenericRpcHandler] +) -> None: + with state.lock: + state.generic_handlers.extend(generic_handlers) + + +def _add_registered_method_handlers( + state: _ServerState, method_handlers: Dict[str, grpc.RpcMethodHandler] +) -> None: + with state.lock: + state.registered_method_handlers.update(method_handlers) + + +def _add_insecure_port(state: _ServerState, address: bytes) -> int: + with state.lock: + return state.server.add_http2_port(address) + + +def _add_secure_port( + state: _ServerState, + address: bytes, + server_credentials: grpc.ServerCredentials, +) -> int: + with state.lock: + return state.server.add_http2_port( + address, server_credentials._credentials + ) + + +def _request_call(state: _ServerState) -> None: + state.server.request_call( + state.completion_queue, state.completion_queue, _REQUEST_CALL_TAG + ) + state.due.add(_REQUEST_CALL_TAG) + + +def _request_registered_call(state: _ServerState, method: str) -> None: + registered_call_tag = method + state.server.request_registered_call( + state.completion_queue, + state.completion_queue, + method, + registered_call_tag, + ) + state.due.add(registered_call_tag) + + +# TODO(https://github.com/grpc/grpc/issues/6597): delete this function. +def _stop_serving(state: _ServerState) -> bool: + if not state.rpc_states and not state.due: + state.server.destroy() + for shutdown_event in state.shutdown_events: + shutdown_event.set() + state.stage = _ServerStage.STOPPED + return True + else: + return False + + +def _on_call_completed(state: _ServerState) -> None: + with state.lock: + state.active_rpc_count -= 1 + + +# pylint: disable=too-many-branches +def _process_event_and_continue( + state: _ServerState, event: cygrpc.BaseEvent +) -> bool: + should_continue = True + if event.tag is _SHUTDOWN_TAG: + with state.lock: + state.due.remove(_SHUTDOWN_TAG) + if _stop_serving(state): + should_continue = False + elif ( + event.tag is _REQUEST_CALL_TAG + or event.tag in state.registered_method_handlers.keys() + ): + registered_method_name = None + if event.tag in state.registered_method_handlers.keys(): + registered_method_name = event.tag + method_with_handler = _RegisteredMethod( + registered_method_name, + state.registered_method_handlers.get( + registered_method_name, None + ), + ) + else: + method_with_handler = _GenericMethod( + state.generic_handlers, + ) + with state.lock: + state.due.remove(event.tag) + concurrency_exceeded = ( + state.maximum_concurrent_rpcs is not None + and state.active_rpc_count >= state.maximum_concurrent_rpcs + ) + rpc_state, rpc_future = _handle_call( + event, + method_with_handler, + state.interceptor_pipeline, + state.thread_pool, + concurrency_exceeded, + ) + if rpc_state is not None: + state.rpc_states.add(rpc_state) + if rpc_future is not None: + state.active_rpc_count += 1 + rpc_future.add_done_callback( + lambda unused_future: _on_call_completed(state) + ) + if state.stage is _ServerStage.STARTED: + if ( + registered_method_name + in state.registered_method_handlers.keys() + ): + _request_registered_call(state, registered_method_name) + else: + _request_call(state) + elif _stop_serving(state): + should_continue = False + else: + rpc_state, callbacks = event.tag(event) + for callback in callbacks: + try: + callback() + except Exception: # pylint: disable=broad-except + _LOGGER.exception("Exception calling callback!") + if rpc_state is not None: + with state.lock: + state.rpc_states.remove(rpc_state) + if _stop_serving(state): + should_continue = False + return should_continue + + +def _serve(state: _ServerState) -> None: + while True: + timeout = time.time() + _DEALLOCATED_SERVER_CHECK_PERIOD_S + event = state.completion_queue.poll(timeout) + if state.server_deallocated: + _begin_shutdown_once(state) + if event.completion_type != cygrpc.CompletionType.queue_timeout: + if not _process_event_and_continue(state, event): + return + # We want to force the deletion of the previous event + # ~before~ we poll again; if the event has a reference + # to a shutdown Call object, this can induce spinlock. + event = None + + +def _begin_shutdown_once(state: _ServerState) -> None: + with state.lock: + if state.stage is _ServerStage.STARTED: + state.server.shutdown(state.completion_queue, _SHUTDOWN_TAG) + state.stage = _ServerStage.GRACE + state.due.add(_SHUTDOWN_TAG) + + +def _stop(state: _ServerState, grace: Optional[float]) -> threading.Event: + with state.lock: + if state.stage is _ServerStage.STOPPED: + shutdown_event = threading.Event() + shutdown_event.set() + return shutdown_event + else: + _begin_shutdown_once(state) + shutdown_event = threading.Event() + state.shutdown_events.append(shutdown_event) + if grace is None: + state.server.cancel_all_calls() + else: + + def cancel_all_calls_after_grace(): + shutdown_event.wait(timeout=grace) + with state.lock: + state.server.cancel_all_calls() + + thread = threading.Thread(target=cancel_all_calls_after_grace) + thread.start() + return shutdown_event + shutdown_event.wait() + return shutdown_event + + +def _start(state: _ServerState) -> None: + with state.lock: + if state.stage is not _ServerStage.STOPPED: + raise ValueError("Cannot start already-started server!") + state.server.start() + state.stage = _ServerStage.STARTED + # Request a call for each registered method so we can handle any of them. + for method in state.registered_method_handlers.keys(): + _request_registered_call(state, method) + # Also request a call for non-registered method. + _request_call(state) + thread = threading.Thread(target=_serve, args=(state,)) + thread.daemon = True + thread.start() + + +def _validate_generic_rpc_handlers( + generic_rpc_handlers: Iterable[grpc.GenericRpcHandler], +) -> None: + for generic_rpc_handler in generic_rpc_handlers: + service_attribute = getattr(generic_rpc_handler, "service", None) + if service_attribute is None: + raise AttributeError( + '"{}" must conform to grpc.GenericRpcHandler type but does ' + 'not have "service" method!'.format(generic_rpc_handler) + ) + + +def _augment_options( + base_options: Sequence[ChannelArgumentType], + compression: Optional[grpc.Compression], + xds: bool, +) -> Sequence[ChannelArgumentType]: + compression_option = _compression.create_channel_option(compression) + maybe_server_call_tracer_factory_option = ( + _observability.create_server_call_tracer_factory_option(xds) + ) + return ( + tuple(base_options) + + compression_option + + maybe_server_call_tracer_factory_option + ) + + +class _Server(grpc.Server): + _state: _ServerState + + # pylint: disable=too-many-arguments + def __init__( + self, + thread_pool: futures.ThreadPoolExecutor, + generic_handlers: Sequence[grpc.GenericRpcHandler], + interceptors: Sequence[grpc.ServerInterceptor], + options: Sequence[ChannelArgumentType], + maximum_concurrent_rpcs: Optional[int], + compression: Optional[grpc.Compression], + xds: bool, + ): + completion_queue = cygrpc.CompletionQueue() + server = cygrpc.Server(_augment_options(options, compression, xds), xds) + server.register_completion_queue(completion_queue) + self._state = _ServerState( + completion_queue, + server, + generic_handlers, + _interceptor.service_pipeline(interceptors), + thread_pool, + maximum_concurrent_rpcs, + ) + self._cy_server = server + + def add_generic_rpc_handlers( + self, generic_rpc_handlers: Iterable[grpc.GenericRpcHandler] + ) -> None: + _validate_generic_rpc_handlers(generic_rpc_handlers) + _add_generic_handlers(self._state, generic_rpc_handlers) + + def add_registered_method_handlers( + self, + service_name: str, + method_handlers: Dict[str, grpc.RpcMethodHandler], + ) -> None: + # Can't register method once server started. + with self._state.lock: + if self._state.stage is _ServerStage.STARTED: + return + + # TODO(xuanwn): We should validate method_handlers first. + method_to_handlers = { + _common.fully_qualified_method(service_name, method): method_handler + for method, method_handler in method_handlers.items() + } + for fully_qualified_method in method_to_handlers.keys(): + self._cy_server.register_method(fully_qualified_method) + _add_registered_method_handlers(self._state, method_to_handlers) + + def add_insecure_port(self, address: str) -> int: + return _common.validate_port_binding_result( + address, _add_insecure_port(self._state, _common.encode(address)) + ) + + def add_secure_port( + self, address: str, server_credentials: grpc.ServerCredentials + ) -> int: + return _common.validate_port_binding_result( + address, + _add_secure_port( + self._state, _common.encode(address), server_credentials + ), + ) + + def start(self) -> None: + _start(self._state) + + def wait_for_termination(self, timeout: Optional[float] = None) -> bool: + # NOTE(https://bugs.python.org/issue35935) + # Remove this workaround once threading.Event.wait() is working with + # CTRL+C across platforms. + return _common.wait( + self._state.termination_event.wait, + self._state.termination_event.is_set, + timeout=timeout, + ) + + def stop(self, grace: Optional[float]) -> threading.Event: + return _stop(self._state, grace) + + def __del__(self): + if hasattr(self, "_state"): + # We can not grab a lock in __del__(), so set a flag to signal the + # serving daemon thread (if it exists) to initiate shutdown. + self._state.server_deallocated = True + + +def create_server( + thread_pool: futures.ThreadPoolExecutor, + generic_rpc_handlers: Sequence[grpc.GenericRpcHandler], + interceptors: Sequence[grpc.ServerInterceptor], + options: Sequence[ChannelArgumentType], + maximum_concurrent_rpcs: Optional[int], + compression: Optional[grpc.Compression], + xds: bool, +) -> _Server: + _validate_generic_rpc_handlers(generic_rpc_handlers) + return _Server( + thread_pool, + generic_rpc_handlers, + interceptors, + options, + maximum_concurrent_rpcs, + compression, + xds, + ) diff --git a/python_embeded/Lib/site-packages/grpc/_simple_stubs.py b/python_embeded/Lib/site-packages/grpc/_simple_stubs.py new file mode 100644 index 0000000000000000000000000000000000000000..f2d288d6e9e9210d0dacf0934c5bc15c114db464 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_simple_stubs.py @@ -0,0 +1,588 @@ +# Copyright 2020 The gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Functions that obviate explicit stubs and explicit channels.""" + +import collections +import datetime +import logging +import os +import threading +from typing import ( + Any, + AnyStr, + Callable, + Dict, + Iterator, + Optional, + Sequence, + Tuple, + TypeVar, + Union, +) + +import grpc +from grpc.experimental import experimental_api + +RequestType = TypeVar("RequestType") +ResponseType = TypeVar("ResponseType") + +OptionsType = Sequence[Tuple[str, str]] +CacheKey = Tuple[ + str, + OptionsType, + Optional[grpc.ChannelCredentials], + Optional[grpc.Compression], +] + +_LOGGER = logging.getLogger(__name__) + +_EVICTION_PERIOD_KEY = "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" +if _EVICTION_PERIOD_KEY in os.environ: + _EVICTION_PERIOD = datetime.timedelta( + seconds=float(os.environ[_EVICTION_PERIOD_KEY]) + ) + _LOGGER.debug( + "Setting managed channel eviction period to %s", _EVICTION_PERIOD + ) +else: + _EVICTION_PERIOD = datetime.timedelta(minutes=10) + +_MAXIMUM_CHANNELS_KEY = "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" +if _MAXIMUM_CHANNELS_KEY in os.environ: + _MAXIMUM_CHANNELS = int(os.environ[_MAXIMUM_CHANNELS_KEY]) + _LOGGER.debug("Setting maximum managed channels to %d", _MAXIMUM_CHANNELS) +else: + _MAXIMUM_CHANNELS = 2**8 + +_DEFAULT_TIMEOUT_KEY = "GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS" +if _DEFAULT_TIMEOUT_KEY in os.environ: + _DEFAULT_TIMEOUT = float(os.environ[_DEFAULT_TIMEOUT_KEY]) + _LOGGER.debug("Setting default timeout seconds to %f", _DEFAULT_TIMEOUT) +else: + _DEFAULT_TIMEOUT = 60.0 + + +def _create_channel( + target: str, + options: Sequence[Tuple[str, str]], + channel_credentials: Optional[grpc.ChannelCredentials], + compression: Optional[grpc.Compression], +) -> grpc.Channel: + _LOGGER.debug( + f"Creating secure channel with credentials '{channel_credentials}', " + + f"options '{options}' and compression '{compression}'" + ) + return grpc.secure_channel( + target, + credentials=channel_credentials, + options=options, + compression=compression, + ) + + +class ChannelCache: + # NOTE(rbellevi): Untyped due to reference cycle. + _singleton = None + _lock: threading.RLock = threading.RLock() + _condition: threading.Condition = threading.Condition(lock=_lock) + _eviction_ready: threading.Event = threading.Event() + + _mapping: Dict[CacheKey, Tuple[grpc.Channel, datetime.datetime]] + _eviction_thread: threading.Thread + + def __init__(self): + self._mapping = collections.OrderedDict() + self._eviction_thread = threading.Thread( + target=ChannelCache._perform_evictions, daemon=True + ) + self._eviction_thread.start() + + @staticmethod + def get(): + with ChannelCache._lock: + if ChannelCache._singleton is None: + ChannelCache._singleton = ChannelCache() + ChannelCache._eviction_ready.wait() + return ChannelCache._singleton + + def _evict_locked(self, key: CacheKey): + channel, _ = self._mapping.pop(key) + _LOGGER.debug( + "Evicting channel %s with configuration %s.", channel, key + ) + channel.close() + del channel + + @staticmethod + def _perform_evictions(): + while True: + with ChannelCache._lock: + ChannelCache._eviction_ready.set() + if not ChannelCache._singleton._mapping: + ChannelCache._condition.wait() + elif len(ChannelCache._singleton._mapping) > _MAXIMUM_CHANNELS: + key = next(iter(ChannelCache._singleton._mapping.keys())) + ChannelCache._singleton._evict_locked(key) + # And immediately reevaluate. + else: + key, (_, eviction_time) = next( + iter(ChannelCache._singleton._mapping.items()) + ) + now = datetime.datetime.now() + if eviction_time <= now: + ChannelCache._singleton._evict_locked(key) + continue + else: + time_to_eviction = (eviction_time - now).total_seconds() + # NOTE: We aim to *eventually* coalesce to a state in + # which no overdue channels are in the cache and the + # length of the cache is longer than _MAXIMUM_CHANNELS. + # We tolerate momentary states in which these two + # criteria are not met. + ChannelCache._condition.wait(timeout=time_to_eviction) + + def get_channel( + self, + target: str, + options: Sequence[Tuple[str, str]], + channel_credentials: Optional[grpc.ChannelCredentials], + insecure: bool, + compression: Optional[grpc.Compression], + method: str, + _registered_method: bool, + ) -> Tuple[grpc.Channel, Optional[int]]: + """Get a channel from cache or creates a new channel. + + This method also takes care of register method for channel, + which means we'll register a new call handle if we're calling a + non-registered method for an existing channel. + + Returns: + A tuple with two items. The first item is the channel, second item is + the call handle if the method is registered, None if it's not registered. + """ + if insecure and channel_credentials: + raise ValueError( + "The insecure option is mutually exclusive with " + + "the channel_credentials option. Please use one " + + "or the other." + ) + if insecure: + channel_credentials = ( + grpc.experimental.insecure_channel_credentials() + ) + elif channel_credentials is None: + _LOGGER.debug("Defaulting to SSL channel credentials.") + channel_credentials = grpc.ssl_channel_credentials() + key = (target, options, channel_credentials, compression) + with self._lock: + channel_data = self._mapping.get(key, None) + call_handle = None + if channel_data is not None: + channel = channel_data[0] + # Register a new call handle if we're calling a registered method for an + # existing channel and this method is not registered. + if _registered_method: + call_handle = channel._get_registered_call_handle(method) + self._mapping.pop(key) + self._mapping[key] = ( + channel, + datetime.datetime.now() + _EVICTION_PERIOD, + ) + return channel, call_handle + else: + channel = _create_channel( + target, options, channel_credentials, compression + ) + if _registered_method: + call_handle = channel._get_registered_call_handle(method) + self._mapping[key] = ( + channel, + datetime.datetime.now() + _EVICTION_PERIOD, + ) + if ( + len(self._mapping) == 1 + or len(self._mapping) >= _MAXIMUM_CHANNELS + ): + self._condition.notify() + return channel, call_handle + + def _test_only_channel_count(self) -> int: + with self._lock: + return len(self._mapping) + + +@experimental_api +# pylint: disable=too-many-locals +def unary_unary( + request: RequestType, + target: str, + method: str, + request_serializer: Optional[Callable[[Any], bytes]] = None, + response_deserializer: Optional[Callable[[bytes], Any]] = None, + options: Sequence[Tuple[AnyStr, AnyStr]] = (), + channel_credentials: Optional[grpc.ChannelCredentials] = None, + insecure: bool = False, + call_credentials: Optional[grpc.CallCredentials] = None, + compression: Optional[grpc.Compression] = None, + wait_for_ready: Optional[bool] = None, + timeout: Optional[float] = _DEFAULT_TIMEOUT, + metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None, + _registered_method: Optional[bool] = False, +) -> ResponseType: + """Invokes a unary-unary RPC without an explicitly specified channel. + + THIS IS AN EXPERIMENTAL API. + + This is backed by a per-process cache of channels. Channels are evicted + from the cache after a fixed period by a background. Channels will also be + evicted if more than a configured maximum accumulate. + + The default eviction period is 10 minutes. One may set the environment + variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this. + + The default maximum number of channels is 256. One may set the + environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure + this. + + Args: + request: An iterator that yields request values for the RPC. + target: The server address. + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the response + message. Response goes undeserialized in case None is passed. + options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core + runtime) to configure the channel. + channel_credentials: A credential applied to the whole channel, e.g. the + return value of grpc.ssl_channel_credentials() or + grpc.insecure_channel_credentials(). + insecure: If True, specifies channel_credentials as + :term:`grpc.insecure_channel_credentials()`. This option is mutually + exclusive with the `channel_credentials` option. + call_credentials: A call credential applied to each call individually, + e.g. the output of grpc.metadata_call_credentials() or + grpc.access_token_call_credentials(). + compression: An optional value indicating the compression method to be + used over the lifetime of the channel, e.g. grpc.Compression.Gzip. + wait_for_ready: An optional flag indicating whether the RPC should fail + immediately if the connection is not ready at the time the RPC is + invoked, or if it should wait until the connection to the server + becomes ready. When using this option, the user will likely also want + to set a timeout. Defaults to True. + timeout: An optional duration of time in seconds to allow for the RPC, + after which an exception will be raised. If timeout is unspecified, + defaults to a timeout controlled by the + GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is + unset, defaults to 60 seconds. Supply a value of None to indicate that + no timeout should be enforced. + metadata: Optional metadata to send to the server. + + Returns: + The response to the RPC. + """ + channel, method_handle = ChannelCache.get().get_channel( + target, + options, + channel_credentials, + insecure, + compression, + method, + _registered_method, + ) + multicallable = channel.unary_unary( + method, request_serializer, response_deserializer, method_handle + ) + wait_for_ready = wait_for_ready if wait_for_ready is not None else True + return multicallable( + request, + metadata=metadata, + wait_for_ready=wait_for_ready, + credentials=call_credentials, + timeout=timeout, + ) + + +@experimental_api +# pylint: disable=too-many-locals +def unary_stream( + request: RequestType, + target: str, + method: str, + request_serializer: Optional[Callable[[Any], bytes]] = None, + response_deserializer: Optional[Callable[[bytes], Any]] = None, + options: Sequence[Tuple[AnyStr, AnyStr]] = (), + channel_credentials: Optional[grpc.ChannelCredentials] = None, + insecure: bool = False, + call_credentials: Optional[grpc.CallCredentials] = None, + compression: Optional[grpc.Compression] = None, + wait_for_ready: Optional[bool] = None, + timeout: Optional[float] = _DEFAULT_TIMEOUT, + metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None, + _registered_method: Optional[bool] = False, +) -> Iterator[ResponseType]: + """Invokes a unary-stream RPC without an explicitly specified channel. + + THIS IS AN EXPERIMENTAL API. + + This is backed by a per-process cache of channels. Channels are evicted + from the cache after a fixed period by a background. Channels will also be + evicted if more than a configured maximum accumulate. + + The default eviction period is 10 minutes. One may set the environment + variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this. + + The default maximum number of channels is 256. One may set the + environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure + this. + + Args: + request: An iterator that yields request values for the RPC. + target: The server address. + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the response + message. Response goes undeserialized in case None is passed. + options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core + runtime) to configure the channel. + channel_credentials: A credential applied to the whole channel, e.g. the + return value of grpc.ssl_channel_credentials(). + insecure: If True, specifies channel_credentials as + :term:`grpc.insecure_channel_credentials()`. This option is mutually + exclusive with the `channel_credentials` option. + call_credentials: A call credential applied to each call individually, + e.g. the output of grpc.metadata_call_credentials() or + grpc.access_token_call_credentials(). + compression: An optional value indicating the compression method to be + used over the lifetime of the channel, e.g. grpc.Compression.Gzip. + wait_for_ready: An optional flag indicating whether the RPC should fail + immediately if the connection is not ready at the time the RPC is + invoked, or if it should wait until the connection to the server + becomes ready. When using this option, the user will likely also want + to set a timeout. Defaults to True. + timeout: An optional duration of time in seconds to allow for the RPC, + after which an exception will be raised. If timeout is unspecified, + defaults to a timeout controlled by the + GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is + unset, defaults to 60 seconds. Supply a value of None to indicate that + no timeout should be enforced. + metadata: Optional metadata to send to the server. + + Returns: + An iterator of responses. + """ + channel, method_handle = ChannelCache.get().get_channel( + target, + options, + channel_credentials, + insecure, + compression, + method, + _registered_method, + ) + multicallable = channel.unary_stream( + method, request_serializer, response_deserializer, method_handle + ) + wait_for_ready = wait_for_ready if wait_for_ready is not None else True + return multicallable( + request, + metadata=metadata, + wait_for_ready=wait_for_ready, + credentials=call_credentials, + timeout=timeout, + ) + + +@experimental_api +# pylint: disable=too-many-locals +def stream_unary( + request_iterator: Iterator[RequestType], + target: str, + method: str, + request_serializer: Optional[Callable[[Any], bytes]] = None, + response_deserializer: Optional[Callable[[bytes], Any]] = None, + options: Sequence[Tuple[AnyStr, AnyStr]] = (), + channel_credentials: Optional[grpc.ChannelCredentials] = None, + insecure: bool = False, + call_credentials: Optional[grpc.CallCredentials] = None, + compression: Optional[grpc.Compression] = None, + wait_for_ready: Optional[bool] = None, + timeout: Optional[float] = _DEFAULT_TIMEOUT, + metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None, + _registered_method: Optional[bool] = False, +) -> ResponseType: + """Invokes a stream-unary RPC without an explicitly specified channel. + + THIS IS AN EXPERIMENTAL API. + + This is backed by a per-process cache of channels. Channels are evicted + from the cache after a fixed period by a background. Channels will also be + evicted if more than a configured maximum accumulate. + + The default eviction period is 10 minutes. One may set the environment + variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this. + + The default maximum number of channels is 256. One may set the + environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure + this. + + Args: + request_iterator: An iterator that yields request values for the RPC. + target: The server address. + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the response + message. Response goes undeserialized in case None is passed. + options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core + runtime) to configure the channel. + channel_credentials: A credential applied to the whole channel, e.g. the + return value of grpc.ssl_channel_credentials(). + call_credentials: A call credential applied to each call individually, + e.g. the output of grpc.metadata_call_credentials() or + grpc.access_token_call_credentials(). + insecure: If True, specifies channel_credentials as + :term:`grpc.insecure_channel_credentials()`. This option is mutually + exclusive with the `channel_credentials` option. + compression: An optional value indicating the compression method to be + used over the lifetime of the channel, e.g. grpc.Compression.Gzip. + wait_for_ready: An optional flag indicating whether the RPC should fail + immediately if the connection is not ready at the time the RPC is + invoked, or if it should wait until the connection to the server + becomes ready. When using this option, the user will likely also want + to set a timeout. Defaults to True. + timeout: An optional duration of time in seconds to allow for the RPC, + after which an exception will be raised. If timeout is unspecified, + defaults to a timeout controlled by the + GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is + unset, defaults to 60 seconds. Supply a value of None to indicate that + no timeout should be enforced. + metadata: Optional metadata to send to the server. + + Returns: + The response to the RPC. + """ + channel, method_handle = ChannelCache.get().get_channel( + target, + options, + channel_credentials, + insecure, + compression, + method, + _registered_method, + ) + multicallable = channel.stream_unary( + method, request_serializer, response_deserializer, method_handle + ) + wait_for_ready = wait_for_ready if wait_for_ready is not None else True + return multicallable( + request_iterator, + metadata=metadata, + wait_for_ready=wait_for_ready, + credentials=call_credentials, + timeout=timeout, + ) + + +@experimental_api +# pylint: disable=too-many-locals +def stream_stream( + request_iterator: Iterator[RequestType], + target: str, + method: str, + request_serializer: Optional[Callable[[Any], bytes]] = None, + response_deserializer: Optional[Callable[[bytes], Any]] = None, + options: Sequence[Tuple[AnyStr, AnyStr]] = (), + channel_credentials: Optional[grpc.ChannelCredentials] = None, + insecure: bool = False, + call_credentials: Optional[grpc.CallCredentials] = None, + compression: Optional[grpc.Compression] = None, + wait_for_ready: Optional[bool] = None, + timeout: Optional[float] = _DEFAULT_TIMEOUT, + metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None, + _registered_method: Optional[bool] = False, +) -> Iterator[ResponseType]: + """Invokes a stream-stream RPC without an explicitly specified channel. + + THIS IS AN EXPERIMENTAL API. + + This is backed by a per-process cache of channels. Channels are evicted + from the cache after a fixed period by a background. Channels will also be + evicted if more than a configured maximum accumulate. + + The default eviction period is 10 minutes. One may set the environment + variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this. + + The default maximum number of channels is 256. One may set the + environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure + this. + + Args: + request_iterator: An iterator that yields request values for the RPC. + target: The server address. + method: The name of the RPC method. + request_serializer: Optional :term:`serializer` for serializing the request + message. Request goes unserialized in case None is passed. + response_deserializer: Optional :term:`deserializer` for deserializing the response + message. Response goes undeserialized in case None is passed. + options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core + runtime) to configure the channel. + channel_credentials: A credential applied to the whole channel, e.g. the + return value of grpc.ssl_channel_credentials(). + call_credentials: A call credential applied to each call individually, + e.g. the output of grpc.metadata_call_credentials() or + grpc.access_token_call_credentials(). + insecure: If True, specifies channel_credentials as + :term:`grpc.insecure_channel_credentials()`. This option is mutually + exclusive with the `channel_credentials` option. + compression: An optional value indicating the compression method to be + used over the lifetime of the channel, e.g. grpc.Compression.Gzip. + wait_for_ready: An optional flag indicating whether the RPC should fail + immediately if the connection is not ready at the time the RPC is + invoked, or if it should wait until the connection to the server + becomes ready. When using this option, the user will likely also want + to set a timeout. Defaults to True. + timeout: An optional duration of time in seconds to allow for the RPC, + after which an exception will be raised. If timeout is unspecified, + defaults to a timeout controlled by the + GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is + unset, defaults to 60 seconds. Supply a value of None to indicate that + no timeout should be enforced. + metadata: Optional metadata to send to the server. + + Returns: + An iterator of responses. + """ + channel, method_handle = ChannelCache.get().get_channel( + target, + options, + channel_credentials, + insecure, + compression, + method, + _registered_method, + ) + multicallable = channel.stream_stream( + method, request_serializer, response_deserializer, method_handle + ) + wait_for_ready = wait_for_ready if wait_for_ready is not None else True + return multicallable( + request_iterator, + metadata=metadata, + wait_for_ready=wait_for_ready, + credentials=call_credentials, + timeout=timeout, + ) diff --git a/python_embeded/Lib/site-packages/grpc/_typing.py b/python_embeded/Lib/site-packages/grpc/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b559b75eb3205443207217810a44967712037b --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_typing.py @@ -0,0 +1,95 @@ +# Copyright 2022 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Common types for gRPC Sync API""" + +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Iterable, + Iterator, + Optional, + Sequence, + Tuple, + TypeVar, + Union, +) + +from grpc._cython import cygrpc + +if TYPE_CHECKING: + from grpc import ServicerContext + from grpc._server import _RPCState + +RequestType = TypeVar("RequestType") +ResponseType = TypeVar("ResponseType") +SerializingFunction = Callable[[Any], bytes] +DeserializingFunction = Callable[[bytes], Any] +MetadataType = Sequence[Tuple[str, Union[str, bytes]]] +ChannelArgumentType = Tuple[str, Any] +DoneCallbackType = Callable[[Any], None] +NullaryCallbackType = Callable[[], None] +RequestIterableType = Iterable[Any] +ResponseIterableType = Iterable[Any] +UserTag = Callable[[cygrpc.BaseEvent], bool] +IntegratedCallFactory = Callable[ + [ + int, + bytes, + None, + Optional[float], + Optional[MetadataType], + Optional[cygrpc.CallCredentials], + Sequence[Sequence[cygrpc.Operation]], + UserTag, + Any, + ], + cygrpc.IntegratedCall, +] +ServerTagCallbackType = Tuple[ + Optional["_RPCState"], Sequence[NullaryCallbackType] +] +ServerCallbackTag = Callable[[cygrpc.BaseEvent], ServerTagCallbackType] +ArityAgnosticMethodHandler = Union[ + Callable[ + [RequestType, "ServicerContext", Callable[[ResponseType], None]], + ResponseType, + ], + Callable[ + [RequestType, "ServicerContext", Callable[[ResponseType], None]], + Iterator[ResponseType], + ], + Callable[ + [ + Iterator[RequestType], + "ServicerContext", + Callable[[ResponseType], None], + ], + ResponseType, + ], + Callable[ + [ + Iterator[RequestType], + "ServicerContext", + Callable[[ResponseType], None], + ], + Iterator[ResponseType], + ], + Callable[[RequestType, "ServicerContext"], ResponseType], + Callable[[RequestType, "ServicerContext"], Iterator[ResponseType]], + Callable[[Iterator[RequestType], "ServicerContext"], ResponseType], + Callable[ + [Iterator[RequestType], "ServicerContext"], Iterator[ResponseType] + ], +] diff --git a/python_embeded/Lib/site-packages/grpc/_utilities.py b/python_embeded/Lib/site-packages/grpc/_utilities.py new file mode 100644 index 0000000000000000000000000000000000000000..0f0ae499d782b0bc4567bc635afd2da03e81780f --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc/_utilities.py @@ -0,0 +1,222 @@ +# Copyright 2015 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Internal utilities for gRPC Python.""" + +import collections +import logging +import threading +import time +from typing import Callable, Dict, Optional, Sequence + +import grpc # pytype: disable=pyi-error +from grpc import _common # pytype: disable=pyi-error +from grpc._typing import DoneCallbackType + +_LOGGER = logging.getLogger(__name__) + +_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE = ( + 'Exception calling connectivity future "done" callback!' +) + + +class RpcMethodHandler( + collections.namedtuple( + "_RpcMethodHandler", + ( + "request_streaming", + "response_streaming", + "request_deserializer", + "response_serializer", + "unary_unary", + "unary_stream", + "stream_unary", + "stream_stream", + ), + ), + grpc.RpcMethodHandler, +): + pass + + +class DictionaryGenericHandler(grpc.ServiceRpcHandler): + _name: str + _method_handlers: Dict[str, grpc.RpcMethodHandler] + + def __init__( + self, service: str, method_handlers: Dict[str, grpc.RpcMethodHandler] + ): + self._name = service + self._method_handlers = { + _common.fully_qualified_method(service, method): method_handler + for method, method_handler in method_handlers.items() + } + + def service_name(self) -> str: + return self._name + + def service( + self, handler_call_details: grpc.HandlerCallDetails + ) -> Optional[grpc.RpcMethodHandler]: + details_method = handler_call_details.method + return self._method_handlers.get( + details_method + ) # pytype: disable=attribute-error + + +class _ChannelReadyFuture(grpc.Future): + _condition: threading.Condition + _channel: grpc.Channel + _matured: bool + _cancelled: bool + _done_callbacks: Sequence[Callable] + + def __init__(self, channel: grpc.Channel): + self._condition = threading.Condition() + self._channel = channel + + self._matured = False + self._cancelled = False + self._done_callbacks = [] + + def _block(self, timeout: Optional[float]) -> None: + until = None if timeout is None else time.time() + timeout + with self._condition: + while True: + if self._cancelled: + raise grpc.FutureCancelledError() + elif self._matured: + return + else: + if until is None: + self._condition.wait() + else: + remaining = until - time.time() + if remaining < 0: + raise grpc.FutureTimeoutError() + else: + self._condition.wait(timeout=remaining) + + def _update(self, connectivity: Optional[grpc.ChannelConnectivity]) -> None: + with self._condition: + if ( + not self._cancelled + and connectivity is grpc.ChannelConnectivity.READY + ): + self._matured = True + self._channel.unsubscribe(self._update) + self._condition.notify_all() + done_callbacks = tuple(self._done_callbacks) + self._done_callbacks = None + else: + return + + for done_callback in done_callbacks: + try: + done_callback(self) + except Exception: # pylint: disable=broad-except + _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE) + + def cancel(self) -> bool: + with self._condition: + if not self._matured: + self._cancelled = True + self._channel.unsubscribe(self._update) + self._condition.notify_all() + done_callbacks = tuple(self._done_callbacks) + self._done_callbacks = None + else: + return False + + for done_callback in done_callbacks: + try: + done_callback(self) + except Exception: # pylint: disable=broad-except + _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE) + + return True + + def cancelled(self) -> bool: + with self._condition: + return self._cancelled + + def running(self) -> bool: + with self._condition: + return not self._cancelled and not self._matured + + def done(self) -> bool: + with self._condition: + return self._cancelled or self._matured + + def result(self, timeout: Optional[float] = None) -> None: + self._block(timeout) + + def exception(self, timeout: Optional[float] = None) -> None: + self._block(timeout) + + def traceback(self, timeout: Optional[float] = None) -> None: + self._block(timeout) + + def add_done_callback(self, fn: DoneCallbackType): + with self._condition: + if not self._cancelled and not self._matured: + self._done_callbacks.append(fn) + return + + fn(self) + + def start(self): + with self._condition: + self._channel.subscribe(self._update, try_to_connect=True) + + def __del__(self): + with self._condition: + if not self._cancelled and not self._matured: + self._channel.unsubscribe(self._update) + + +def channel_ready_future(channel: grpc.Channel) -> _ChannelReadyFuture: + ready_future = _ChannelReadyFuture(channel) + ready_future.start() + return ready_future + + +def first_version_is_lower(version1: str, version2: str) -> bool: + """ + Compares two versions in the format '1.60.1' or '1.60.1.dev0'. + + This method will be used in all stubs generated by grpcio-tools to check whether + the stub version is compatible with the runtime grpcio. + + Args: + version1: The first version string. + version2: The second version string. + + Returns: + True if version1 is lower, False otherwise. + """ + version1_list = version1.split(".") + version2_list = version2.split(".") + + try: + for i in range(3): + if int(version1_list[i]) < int(version2_list[i]): + return True + elif int(version1_list[i]) > int(version2_list[i]): + return False + except ValueError: + # Return false in case we can't convert version to int. + return False + + # The version without dev0 will be considered lower. + return len(version1_list) < len(version2_list) diff --git a/python_embeded/Lib/site-packages/grpc_status/__init__.py b/python_embeded/Lib/site-packages/grpc_status/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38fdfc9c5cf23b71d5b71dc40ee1524b6ac8ecc5 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc_status/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/python_embeded/Lib/site-packages/grpc_status/_async.py b/python_embeded/Lib/site-packages/grpc_status/_async.py new file mode 100644 index 0000000000000000000000000000000000000000..9f58c8a81f3304618fec7defce0def717b2c0f0a --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc_status/_async.py @@ -0,0 +1,58 @@ +# Copyright 2020 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Reference implementation for status mapping in gRPC Python.""" + +from google.rpc import status_pb2 +from grpc.experimental import aio + +from ._common import GRPC_DETAILS_METADATA_KEY +from ._common import code_to_grpc_status_code + + +async def from_call(call: aio.Call): + """Returns a google.rpc.status.Status message from a given grpc.aio.Call. + + This is an EXPERIMENTAL API. + + Args: + call: An grpc.aio.Call instance. + + Returns: + A google.rpc.status.Status message representing the status of the RPC. + """ + code = await call.code() + details = await call.details() + trailing_metadata = await call.trailing_metadata() + if trailing_metadata is None: + return None + for key, value in trailing_metadata: + if key == GRPC_DETAILS_METADATA_KEY: + rich_status = status_pb2.Status.FromString(value) + if code.value[0] != rich_status.code: + raise ValueError( + "Code in Status proto (%s) doesn't match status code (%s)" + % (code_to_grpc_status_code(rich_status.code), code) + ) + if details != rich_status.message: + raise ValueError( + "Message in Status proto (%s) doesn't match status details" + " (%s)" % (rich_status.message, details) + ) + return rich_status + return None + + +__all__ = [ + "from_call", +] diff --git a/python_embeded/Lib/site-packages/grpc_status/_common.py b/python_embeded/Lib/site-packages/grpc_status/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..66677d849d64756ff8b51ab5bf17c158edf42586 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc_status/_common.py @@ -0,0 +1,27 @@ +# Copyright 2020 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Reference implementation for status mapping in gRPC Python.""" + +import grpc + +_CODE_TO_GRPC_CODE_MAPPING = {x.value[0]: x for x in grpc.StatusCode} + +GRPC_DETAILS_METADATA_KEY = "grpc-status-details-bin" + + +def code_to_grpc_status_code(code): + try: + return _CODE_TO_GRPC_CODE_MAPPING[code] + except KeyError: + raise ValueError("Invalid status code %s" % code) diff --git a/python_embeded/Lib/site-packages/grpc_status/rpc_status.py b/python_embeded/Lib/site-packages/grpc_status/rpc_status.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f10a8b18f4156c0b4754e62c67caf3d32fbeda --- /dev/null +++ b/python_embeded/Lib/site-packages/grpc_status/rpc_status.py @@ -0,0 +1,96 @@ +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Reference implementation for status mapping in gRPC Python.""" + +import collections +import sys + +from google.rpc import status_pb2 +import grpc + +from ._common import GRPC_DETAILS_METADATA_KEY +from ._common import code_to_grpc_status_code + + +class _Status( + collections.namedtuple("_Status", ("code", "details", "trailing_metadata")), + grpc.Status, +): + pass + + +def from_call(call): + """Returns a google.rpc.status.Status message corresponding to a given grpc.Call. + + This is an EXPERIMENTAL API. + + Args: + call: A grpc.Call instance. + + Returns: + A google.rpc.status.Status message representing the status of the RPC. + + Raises: + ValueError: If the gRPC call's code or details are inconsistent with the + status code and message inside of the google.rpc.status.Status. + """ + if call.trailing_metadata() is None: + return None + for key, value in call.trailing_metadata(): + if key == GRPC_DETAILS_METADATA_KEY: + rich_status = status_pb2.Status.FromString(value) + if call.code().value[0] != rich_status.code: + raise ValueError( + "Code in Status proto (%s) doesn't match status code (%s)" + % (code_to_grpc_status_code(rich_status.code), call.code()) + ) + if call.details() != rich_status.message: + raise ValueError( + "Message in Status proto (%s) doesn't match status details" + " (%s)" % (rich_status.message, call.details()) + ) + return rich_status + return None + + +def to_status(status): + """Convert a google.rpc.status.Status message to grpc.Status. + + This is an EXPERIMENTAL API. + + Args: + status: a google.rpc.status.Status message representing the non-OK status + to terminate the RPC with and communicate it to the client. + + Returns: + A grpc.Status instance representing the input google.rpc.status.Status message. + """ + return _Status( + code=code_to_grpc_status_code(status.code), + details=status.message, + trailing_metadata=( + (GRPC_DETAILS_METADATA_KEY, status.SerializeToString()), + ), + ) + + +__all__ = [ + "from_call", + "to_status", +] + +if sys.version_info[0] >= 3 and sys.version_info[1] >= 6: + from . import _async as aio # pylint: disable=unused-import + + __all__.append("aio") diff --git a/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/LICENSE b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..442f783d527f531f00439d5b5cba7b68f2b48b2e --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/LICENSE @@ -0,0 +1,610 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +----------------------------------------------------------- + +BSD 3-Clause License + +Copyright 2016, Google Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from this +software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +----------------------------------------------------------- + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/METADATA b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..59cee2560740fa13646fee66aa4449bbc18874cc --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/METADATA @@ -0,0 +1,129 @@ +Metadata-Version: 2.1 +Name: grpcio +Version: 1.73.1 +Summary: HTTP/2-based RPC framework +Home-page: https://grpc.io +Author: The gRPC Authors +Author-email: grpc-io@googlegroups.com +License: Apache License 2.0 +Project-URL: Source Code, https://github.com/grpc/grpc +Project-URL: Bug Tracker, https://github.com/grpc/grpc/issues +Project-URL: Documentation, https://grpc.github.io/grpc/python +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: License :: OSI Approved :: Apache Software License +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: protobuf +Requires-Dist: grpcio-tools >=1.73.1 ; extra == 'protobuf' + +gRPC Python +=========== + +|compat_check_pypi| + +Package for gRPC Python. + +.. |compat_check_pypi| image:: https://python-compatibility-tools.appspot.com/one_badge_image?package=grpcio + :target: https://python-compatibility-tools.appspot.com/one_badge_target?package=grpcio + + +Installation +------------ + +gRPC Python is available for Linux, macOS, and Windows. + +Installing From PyPI +~~~~~~~~~~~~~~~~~~~~ + +If you are installing locally... + +:: + + $ pip install grpcio + +Else system wide (on Ubuntu)... + +:: + + $ sudo pip install grpcio + +If you're on Windows make sure that you installed the :code:`pip.exe` component +when you installed Python (if not go back and install it!) then invoke: + +:: + + $ pip.exe install grpcio + +Windows users may need to invoke :code:`pip.exe` from a command line ran as +administrator. + +n.b. On Windows and on Mac OS X one *must* have a recent release of :code:`pip` +to retrieve the proper wheel from PyPI. Be sure to upgrade to the latest +version! + +Installing From Source +~~~~~~~~~~~~~~~~~~~~~~ + +Building from source requires that you have the Python headers (usually a +package named :code:`python-dev`). + +:: + + $ export REPO_ROOT=grpc # REPO_ROOT can be any directory of your choice + $ git clone -b RELEASE_TAG_HERE https://github.com/grpc/grpc $REPO_ROOT + $ cd $REPO_ROOT + $ git submodule update --init + + # To include systemd socket-activation feature in the build, + # first install the `libsystemd-dev` package, then : + $ export GRPC_PYTHON_BUILD_WITH_SYSTEMD=1 + + # For the next two commands do `sudo pip install` if you get permission-denied errors + $ pip install -r requirements.txt + $ GRPC_PYTHON_BUILD_WITH_CYTHON=1 pip install . + +You cannot currently install Python from source on Windows. Things might work +out for you in MSYS2 (follow the Linux instructions), but it isn't officially +supported at the moment. + +Troubleshooting +~~~~~~~~~~~~~~~ + +Help, I ... + +* **... see the following error on some platforms** + + :: + + /tmp/pip-build-U8pSsr/cython/Cython/Plex/Scanners.c:4:20: fatal error: Python.h: No such file or directory + #include "Python.h" + ^ + compilation terminated. + + You can fix it by installing `python-dev` package. i.e + + :: + + sudo apt-get install python-dev + + +Versioning +~~~~~~~~~~ + +gRPC Python is developed in a monorepo shared with implementations of gRPC in +other programming languages. While the minor versions are released in +lock-step with other languages in the repo (e.g. 1.63.0 is guaranteed to exist +for all languages), patch versions may be specific to only a single +language. For example, if 1.63.1 is a C++-specific patch, 1.63.1 may not be +uploaded to PyPi. As a result, it is __not__ a good assumption that the latest +patch for a given minor version on Github is also the latest patch for that +same minor version on PyPi. + diff --git a/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/RECORD b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e97beffd608f87318a3b52903bde0d4e967bcb54 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/RECORD @@ -0,0 +1,120 @@ +grpc/__init__.py,sha256=Vl7Jh3KVTCHAtN0kSoyHhte6BvMBY4_6E0QQMZEvMBE,84681 +grpc/__pycache__/__init__.cpython-312.pyc,, +grpc/__pycache__/_auth.cpython-312.pyc,, +grpc/__pycache__/_channel.cpython-312.pyc,, +grpc/__pycache__/_common.cpython-312.pyc,, +grpc/__pycache__/_compression.cpython-312.pyc,, +grpc/__pycache__/_grpcio_metadata.cpython-312.pyc,, +grpc/__pycache__/_interceptor.cpython-312.pyc,, +grpc/__pycache__/_observability.cpython-312.pyc,, +grpc/__pycache__/_plugin_wrapping.cpython-312.pyc,, +grpc/__pycache__/_runtime_protos.cpython-312.pyc,, +grpc/__pycache__/_server.cpython-312.pyc,, +grpc/__pycache__/_simple_stubs.cpython-312.pyc,, +grpc/__pycache__/_typing.cpython-312.pyc,, +grpc/__pycache__/_utilities.cpython-312.pyc,, +grpc/_auth.py,sha256=7GGYpUPXKqU7_iF_jniN1fDWch0_1T3x0nkhzRfsf40,2715 +grpc/_channel.py,sha256=Yq8CYcVTlgi3hWonOG3FyDwhP_03HCWjWMLb1wX4oQU,83613 +grpc/_common.py,sha256=L-pYsWV2y6d9EYCM9XnEBJzw1QoSDKfTbONqPiL6Z0g,6967 +grpc/_compression.py,sha256=hrvGhY68cMej3c53nV2CJg_pGg5kZrMWyUQBrJKxLiY,2054 +grpc/_cython/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/_cython/__pycache__/__init__.cpython-312.pyc,, +grpc/_cython/_credentials/roots.pem,sha256=iQrx6SIqWnawwL7sTFcKoy0a1ZIIj89WEN6VR4qN5jg,268777 +grpc/_cython/_cygrpc/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/_cython/_cygrpc/__pycache__/__init__.cpython-312.pyc,, +grpc/_cython/cygrpc.cp312-win_amd64.pyd,sha256=zIZjjSaQvmoquvUGtFAT1N0dCACTX83gIxYGZtZWFRE,9402368 +grpc/_grpcio_metadata.py,sha256=-bVdgY4oe8RKKIYlQos9SDp3n_QXCfyDYzELsc5Uu3Q,26 +grpc/_interceptor.py,sha256=xkXA_oQCZXBTBiIWz-OmX81z7gf4KU1_dqU6wqmzBoY,26675 +grpc/_observability.py,sha256=HAOiiUGfC4JTM2sdjyANTY7mj7kRghx3FEAJM1JPQ3E,10716 +grpc/_plugin_wrapping.py,sha256=sd98vNKf1TqtQWMSDIKcT1z8tX2lwKrfbjkYQ1l4EB0,4518 +grpc/_runtime_protos.py,sha256=mhCStPUyivS2LUvN8hIXO92KaqzcRn4Q6kTeyTesNDo,5970 +grpc/_server.py,sha256=7ZDwXKcOhiQPjtNjr60BPciIGEKW6KRtbIn9wQHaLPI,52413 +grpc/_simple_stubs.py,sha256=3p-NQBfa41JcLydxBFIUfbj28XrlIgV1VVAOdrxT4gE,25198 +grpc/_typing.py,sha256=jsam5hDuif4oZU-3t8wrDnEF2IIh1AQHdkJe4hqVMuk,2853 +grpc/_utilities.py,sha256=n6dxyRWRfDjH8bmgrteEPDNdve_fVVYUZXhMk-8-ZcM,7265 +grpc/aio/__init__.py,sha256=ww6NbDPsc3XAFs8WSYykRYIMemQ8wx4tnoH7UTF6DUg,3255 +grpc/aio/__pycache__/__init__.cpython-312.pyc,, +grpc/aio/__pycache__/_base_call.cpython-312.pyc,, +grpc/aio/__pycache__/_base_channel.cpython-312.pyc,, +grpc/aio/__pycache__/_base_server.cpython-312.pyc,, +grpc/aio/__pycache__/_call.cpython-312.pyc,, +grpc/aio/__pycache__/_channel.cpython-312.pyc,, +grpc/aio/__pycache__/_interceptor.cpython-312.pyc,, +grpc/aio/__pycache__/_metadata.cpython-312.pyc,, +grpc/aio/__pycache__/_server.cpython-312.pyc,, +grpc/aio/__pycache__/_typing.cpython-312.pyc,, +grpc/aio/__pycache__/_utils.cpython-312.pyc,, +grpc/aio/_base_call.py,sha256=2u6QA8f1cEfDOjEPjH3Ermthji9yP6PiEZyMm9JS1Lg,7817 +grpc/aio/_base_channel.py,sha256=Qp_pxAKuiIKyFbTupCqts56p4NOhj0yi9e3vlSaefsQ,14257 +grpc/aio/_base_server.py,sha256=5T_jhzYFmETW9d4mkkKZ5LAcPht5mufvK1jInEiCcpc,12945 +grpc/aio/_call.py,sha256=V136GU08-lXEjU22DfesDxTC-5w7U4Azw93Wa76w0K4,26120 +grpc/aio/_channel.py,sha256=5BAAsEujDAE2c7OhP65_y0G2q397epT1udBINlk1x7M,22726 +grpc/aio/_interceptor.py,sha256=pN3bZ_gP-kMZubIJ0o4gyGS6kCVMgTFw8KYrmOfdxEU,42523 +grpc/aio/_metadata.py,sha256=wvoXY3ky2RI6355iLS452nvQ6xqJry8ZiagUkTsaDws,5146 +grpc/aio/_server.py,sha256=WKTxg5gbjtP7uD5ju1Yc5yWO6R_eA39gfMAL7RviXDE,9170 +grpc/aio/_typing.py,sha256=QgYlt_nen7CnvtDxCcpUw0BVjRDo7roQHkycqzfcz0I,1421 +grpc/aio/_utils.py,sha256=Fw8FpKtucE2a2VRNF3JyAMzh0BtgNQZKpE5jWlHlwQw,843 +grpc/beta/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/beta/__pycache__/__init__.cpython-312.pyc,, +grpc/beta/__pycache__/_client_adaptations.cpython-312.pyc,, +grpc/beta/__pycache__/_metadata.cpython-312.pyc,, +grpc/beta/__pycache__/_server_adaptations.cpython-312.pyc,, +grpc/beta/__pycache__/implementations.cpython-312.pyc,, +grpc/beta/__pycache__/interfaces.cpython-312.pyc,, +grpc/beta/__pycache__/utilities.cpython-312.pyc,, +grpc/beta/_client_adaptations.py,sha256=4C6KYM68G9Dg76SbPNMnGrpcj3I1aLG7nAdvDEuzMl8,28038 +grpc/beta/_metadata.py,sha256=4bRwelrMpqyqZxmTb_lAhGDpICyBVR-qmsvB1Ti8JrA,1694 +grpc/beta/_server_adaptations.py,sha256=T7EHbyI8BCB_eMyGUoBXnIxQcjp_CoV2jHRPZ8P5sUY,15076 +grpc/beta/implementations.py,sha256=fEpftVpElsOzHK3MxVVQqE21CZ5HdBUkSAbjLNvU1Ew,12403 +grpc/beta/interfaces.py,sha256=U5D3tvq7Z_t4fCYJD9RfFqqnpSvS9VmB4cYQTtari-Y,6245 +grpc/beta/utilities.py,sha256=Yt9_vnL1Bx6l5QO4UL3-TMb4AqKzTJNhmDkRawmlXfg,5158 +grpc/experimental/__init__.py,sha256=J_nNA_SE-VfwMXleVA9CVxc2gNXpZPXIQNSflWeQ1S0,4237 +grpc/experimental/__pycache__/__init__.cpython-312.pyc,, +grpc/experimental/__pycache__/gevent.cpython-312.pyc,, +grpc/experimental/__pycache__/session_cache.cpython-312.pyc,, +grpc/experimental/aio/__init__.py,sha256=QoEtaa5C408IeaaSMKvooYNJdWCqyX6X9UYF-maJcIY,676 +grpc/experimental/aio/__pycache__/__init__.cpython-312.pyc,, +grpc/experimental/gevent.py,sha256=ZmFL0iK7irhC9JtTC2JJP23-IRG3_ZCohRQBhhVWuyM,1000 +grpc/experimental/session_cache.py,sha256=OdASXKtZYY8vP1Yo6GeRi4dfEaVuvyiOK5CknnROExE,1578 +grpc/framework/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/framework/__pycache__/__init__.cpython-312.pyc,, +grpc/framework/common/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/framework/common/__pycache__/__init__.cpython-312.pyc,, +grpc/framework/common/__pycache__/cardinality.cpython-312.pyc,, +grpc/framework/common/__pycache__/style.cpython-312.pyc,, +grpc/framework/common/cardinality.py,sha256=lhyS0Chc2kUCH84K069F2PgNLFJHpjfBjSdN79olL8E,1014 +grpc/framework/common/style.py,sha256=eFEX5mA2ynBzHFf8H2eKeAFp2mm-fR343MiGq9Xq_sI,848 +grpc/framework/foundation/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/framework/foundation/__pycache__/__init__.cpython-312.pyc,, +grpc/framework/foundation/__pycache__/abandonment.cpython-312.pyc,, +grpc/framework/foundation/__pycache__/callable_util.cpython-312.pyc,, +grpc/framework/foundation/__pycache__/future.cpython-312.pyc,, +grpc/framework/foundation/__pycache__/logging_pool.cpython-312.pyc,, +grpc/framework/foundation/__pycache__/stream.cpython-312.pyc,, +grpc/framework/foundation/__pycache__/stream_util.cpython-312.pyc,, +grpc/framework/foundation/abandonment.py,sha256=lI3FSuizdQ85z8sxEKluhvYj9I64YeImvqWDuWu6JXs,900 +grpc/framework/foundation/callable_util.py,sha256=QJZNFhQXoJFD6DAeiRe3KGSnJd-br0C7aqgsagAR1HI,3249 +grpc/framework/foundation/future.py,sha256=WGkqWv-4W0ahgE0iRsgsKdIuVNIBny22OrARQb4AMfc,8592 +grpc/framework/foundation/logging_pool.py,sha256=4hGk3EL1_QyDyF4ic4CF5SI2rrTwWe7Pczj-dJEyuYs,2320 +grpc/framework/foundation/stream.py,sha256=l2VMgFK5qhPMBT0yjM75ZppHMIf5Lzz6Iwnp6Wd9wAw,1420 +grpc/framework/foundation/stream_util.py,sha256=xbo7u8uXLBsQ_vf_NKHsls8mFOmmsaLQni51yk_xLpw,4920 +grpc/framework/interfaces/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/framework/interfaces/__pycache__/__init__.cpython-312.pyc,, +grpc/framework/interfaces/base/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/framework/interfaces/base/__pycache__/__init__.cpython-312.pyc,, +grpc/framework/interfaces/base/__pycache__/base.cpython-312.pyc,, +grpc/framework/interfaces/base/__pycache__/utilities.cpython-312.pyc,, +grpc/framework/interfaces/base/base.py,sha256=5Bvs4SPEUAhJUQCvflvP4BqUx-UXs2SGBAXf2hAv9TA,12562 +grpc/framework/interfaces/base/utilities.py,sha256=fN-_DUGGZdbb8HwHmOmWYHcSRHZbWiPy1ScROb9zCzc,2445 +grpc/framework/interfaces/face/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590 +grpc/framework/interfaces/face/__pycache__/__init__.cpython-312.pyc,, +grpc/framework/interfaces/face/__pycache__/face.cpython-312.pyc,, +grpc/framework/interfaces/face/__pycache__/utilities.cpython-312.pyc,, +grpc/framework/interfaces/face/face.py,sha256=Ml3loDRLwrunMkCs_B9iE6uJEbV3QSCciWxLWykGaYo,40784 +grpc/framework/interfaces/face/utilities.py,sha256=i2hcUy2q1bGfZ2YGgz8vR1Hhjxd3VmqWQAN5G6Tel-0,7022 +grpcio-1.73.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +grpcio-1.73.1.dist-info/LICENSE,sha256=r2PsgwP9UTw5BUp_27KVfsqU-p-O8FvhUTnWMS8iJ3s,30297 +grpcio-1.73.1.dist-info/METADATA,sha256=wDHyknhRGA2uZoh5QysSwVIJ6lYSM5S-3O2ao8N6gds,3967 +grpcio-1.73.1.dist-info/RECORD,, +grpcio-1.73.1.dist-info/WHEEL,sha256=fZWyj_84lK0cA-ZNCsdwhbJl0OTrpWkxInEn424qrSs,102 +grpcio-1.73.1.dist-info/top_level.txt,sha256=eEd2Jq_aVQFp38bWW8Pfwjz_5iibqeOFT-2zXlPAq_8,5 diff --git a/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8e45f0d7975b8ae27b0181e5f001004394157773 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/top_level.txt b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b2fe54cba7bccaa783f551549920c8e8927cf1e --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio-1.73.1.dist-info/top_level.txt @@ -0,0 +1 @@ +grpc diff --git a/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e09a3e90900cb576f297c9558916a926312a5df --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/LICENSE @@ -0,0 +1,610 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +----------------------------------------------------------- + +BSD 3-Clause License + +Copyright 2016, Google Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from this +software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +----------------------------------------------------------- + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/METADATA b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..6b79de1af1fb3bd168409bfcdde69a6cf85444cc --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/METADATA @@ -0,0 +1,33 @@ +Metadata-Version: 2.1 +Name: grpcio-status +Version: 1.71.0 +Summary: Status proto mapping for gRPC +Home-page: https://grpc.io +Author: The gRPC Authors +Author-email: grpc-io@googlegroups.com +License: Apache License 2.0 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: License :: OSI Approved :: Apache Software License +Requires-Python: >=3.9 +License-File: LICENSE +Requires-Dist: protobuf <6.0dev,>=5.26.1 +Requires-Dist: grpcio >=1.71.0 +Requires-Dist: googleapis-common-protos >=1.5.5 + +gRPC Python Status Proto +=========================== + +Reference package for GRPC Python status proto mapping. + + +Dependencies +------------ + +Depends on the `grpcio` package, available from PyPI via `pip install grpcio`. diff --git a/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/RECORD b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..79ce86fcfdc6923d823b183965cf5377431552a0 --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/RECORD @@ -0,0 +1,14 @@ +grpc_status/__init__.py,sha256=Y4nCOh9lDjUtOPLoO7VWHkB-96lRNUo0k6Cs7H_DTK0,580 +grpc_status/__pycache__/__init__.cpython-312.pyc,, +grpc_status/__pycache__/_async.cpython-312.pyc,, +grpc_status/__pycache__/_common.cpython-312.pyc,, +grpc_status/__pycache__/rpc_status.cpython-312.pyc,, +grpc_status/_async.py,sha256=VVYnftzgq0h5JWiPlanlcXFI1sJRysfkgKNmbsbSsOc,2004 +grpc_status/_common.py,sha256=fntl-3SZf7M0JhjjicHObNAjcKv4qS8QjSJZqs8kGNY,959 +grpc_status/rpc_status.py,sha256=N0iuEZitOl4lMRnRVrOfSahPyp9O-viFq8YsCSuQt10,2992 +grpcio_status-1.71.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +grpcio_status-1.71.0.dist-info/LICENSE,sha256=WQGY4_MF8sNH_eZNY3xlSSu-9VTbbINk4UnNN143l-4,29687 +grpcio_status-1.71.0.dist-info/METADATA,sha256=E2aXKESSjBMervJmfwqm6xVn2TBllkjRH3zbHHN6K0g,1064 +grpcio_status-1.71.0.dist-info/RECORD,, +grpcio_status-1.71.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92 +grpcio_status-1.71.0.dist-info/top_level.txt,sha256=yQk7zXr3YXmKtg7OddIv6jlXTTFFMTnDpXSla2xtV58,12 diff --git a/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..bab98d675883cc7567a79df485cd7b4f015e376f --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..46d4e4663da5ef853e572aef2fce4cf6aff999dc --- /dev/null +++ b/python_embeded/Lib/site-packages/grpcio_status-1.71.0.dist-info/top_level.txt @@ -0,0 +1 @@ +grpc_status diff --git a/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/METADATA b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8a2f639061cc4a203f7109d8335d28076442c61d --- /dev/null +++ b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/METADATA @@ -0,0 +1,202 @@ +Metadata-Version: 2.4 +Name: h11 +Version: 0.16.0 +Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1 +Home-page: https://github.com/python-hyper/h11 +Author: Nathaniel J. Smith +Author-email: njs@pobox.com +License: MIT +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: System :: Networking +Requires-Python: >=3.8 +License-File: LICENSE.txt +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-python +Dynamic: summary + +h11 +=== + +.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master + :target: https://travis-ci.org/python-hyper/h11 + :alt: Automated test status + +.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg + :target: https://codecov.io/gh/python-hyper/h11 + :alt: Test coverage + +.. image:: https://readthedocs.org/projects/h11/badge/?version=latest + :target: http://h11.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +This is a little HTTP/1.1 library written from scratch in Python, +heavily inspired by `hyper-h2 `_. + +It's a "bring-your-own-I/O" library; h11 contains no IO code +whatsoever. This means you can hook h11 up to your favorite network +API, and that could be anything you want: synchronous, threaded, +asynchronous, or your own implementation of `RFC 6214 +`_ -- h11 won't judge you. +(Compare this to the current state of the art, where every time a `new +network API `_ comes along then someone +gets to start over reimplementing the entire HTTP protocol from +scratch.) Cory Benfield made an `excellent blog post describing the +benefits of this approach +`_, or if you like video +then here's his `PyCon 2016 talk on the same theme +`_. + +This also means that h11 is not immediately useful out of the box: +it's a toolkit for building programs that speak HTTP, not something +that could directly replace ``requests`` or ``twisted.web`` or +whatever. But h11 makes it much easier to implement something like +``requests`` or ``twisted.web``. + +At a high level, working with h11 goes like this: + +1) First, create an ``h11.Connection`` object to track the state of a + single HTTP/1.1 connection. + +2) When you read data off the network, pass it to + ``conn.receive_data(...)``; you'll get back a list of objects + representing high-level HTTP "events". + +3) When you want to send a high-level HTTP event, create the + corresponding "event" object and pass it to ``conn.send(...)``; + this will give you back some bytes that you can then push out + through the network. + +For example, a client might instantiate and then send a +``h11.Request`` object, then zero or more ``h11.Data`` objects for the +request body (e.g., if this is a POST), and then a +``h11.EndOfMessage`` to indicate the end of the message. Then the +server would then send back a ``h11.Response``, some ``h11.Data``, and +its own ``h11.EndOfMessage``. If either side violates the protocol, +you'll get a ``h11.ProtocolError`` exception. + +h11 is suitable for implementing both servers and clients, and has a +pleasantly symmetric API: the events you send as a client are exactly +the ones that you receive as a server and vice-versa. + +`Here's an example of a tiny HTTP client +`_ + +It also has `a fine manual `_. + +FAQ +--- + +*Whyyyyy?* + +I wanted to play with HTTP in `Curio +`__ and `Trio +`__, which at the time didn't have any +HTTP libraries. So I thought, no big deal, Python has, like, a dozen +different implementations of HTTP, surely I can find one that's +reusable. I didn't find one, but I did find Cory's call-to-arms +blog-post. So I figured, well, fine, if I have to implement HTTP from +scratch, at least I can make sure no-one *else* has to ever again. + +*Should I use it?* + +Maybe. You should be aware that it's a very young project. But, it's +feature complete and has an exhaustive test-suite and complete docs, +so the next step is for people to try using it and see how it goes +:-). If you do then please let us know -- if nothing else we'll want +to talk to you before making any incompatible changes! + +*What are the features/limitations?* + +Roughly speaking, it's trying to be a robust, complete, and non-hacky +implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230: +HTTP/1.1 Message Syntax and Routing +`_. That is, it mostly focuses on +implementing HTTP at the level of taking bytes on and off the wire, +and the headers related to that, and tries to be anal about spec +conformance. It doesn't know about higher-level concerns like URL +routing, conditional GETs, cross-origin cookie policies, or content +negotiation. But it does know how to take care of framing, +cross-version differences in keep-alive handling, and the "obsolete +line folding" rule, so you can focus your energies on the hard / +interesting parts for your application, and it tries to support the +full specification in the sense that any useful HTTP/1.1 conformant +application should be able to use h11. + +It's pure Python, and has no dependencies outside of the standard +library. + +It has a test suite with 100.0% coverage for both statements and +branches. + +Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3. +The last Python 2-compatible version was h11 0.11.x. +(Originally it had a Cython wrapper for `http-parser +`_ and a beautiful nested state +machine implemented with ``yield from`` to postprocess the output. But +I had to take these out -- the new *parser* needs fewer lines-of-code +than the old *parser wrapper*, is written in pure Python, uses no +exotic language syntax, and has more features. It's sad, really; that +old state machine was really slick. I just need a few sentences here +to mourn that.) + +I don't know how fast it is. I haven't benchmarked or profiled it yet, +so it's probably got a few pointless hot spots, and I've been trying +to err on the side of simplicity and robustness instead of +micro-optimization. But at the architectural level I tried hard to +avoid fundamentally bad decisions, e.g., I believe that all the +parsing algorithms remain linear-time even in the face of pathological +input like slowloris, and there are no byte-by-byte loops. (I also +believe that it maintains bounded memory usage in the face of +arbitrary/pathological input.) + +The whole library is ~800 lines-of-code. You can read and understand +the whole thing in less than an hour. Most of the energy invested in +this so far has been spent on trying to keep things simple by +minimizing special-cases and ad hoc state manipulation; even though it +is now quite small and simple, I'm still annoyed that I haven't +figured out how to make it even smaller and simpler. (Unfortunately, +HTTP does not lend itself to simplicity.) + +The API is ~feature complete and I don't expect the general outlines +to change much, but you can't judge an API's ergonomics until you +actually document and use it, so I'd expect some changes in the +details. + +*How do I try it?* + +.. code-block:: sh + + $ pip install h11 + $ git clone git@github.com:python-hyper/h11 + $ cd h11/examples + $ python basic-client.py + +and go from there. + +*License?* + +MIT + +*Code of conduct?* + +Contributors are requested to follow our `code of conduct +`_ in +all project spaces. diff --git a/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/RECORD b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a8f8e63f529ce81b7d7c970ea791147d9a732175 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/RECORD @@ -0,0 +1,29 @@ +h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348 +h11-0.16.0.dist-info/RECORD,, +h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91 +h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124 +h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4 +h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507 +h11/__pycache__/__init__.cpython-312.pyc,, +h11/__pycache__/_abnf.cpython-312.pyc,, +h11/__pycache__/_connection.cpython-312.pyc,, +h11/__pycache__/_events.cpython-312.pyc,, +h11/__pycache__/_headers.cpython-312.pyc,, +h11/__pycache__/_readers.cpython-312.pyc,, +h11/__pycache__/_receivebuffer.cpython-312.pyc,, +h11/__pycache__/_state.cpython-312.pyc,, +h11/__pycache__/_util.cpython-312.pyc,, +h11/__pycache__/_version.cpython-312.pyc,, +h11/__pycache__/_writers.cpython-312.pyc,, +h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815 +h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863 +h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792 +h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412 +h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590 +h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252 +h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231 +h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888 +h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686 +h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081 +h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 diff --git a/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1eb3c49d99559863120cfb8433fc8738fba43ba9 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0d24def711344ec6f4da2108f7d5c9261eb35f8b --- /dev/null +++ b/python_embeded/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt @@ -0,0 +1 @@ +h11 diff --git a/python_embeded/Lib/site-packages/h11/__init__.py b/python_embeded/Lib/site-packages/h11/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..989e92c3458681a6f0be72ae4105ea742750d328 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/__init__.py @@ -0,0 +1,62 @@ +# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230), +# containing no networking code at all, loosely modelled on hyper-h2's generic +# implementation of HTTP/2 (and in particular the h2.connection.H2Connection +# class). There's still a bunch of subtle details you need to get right if you +# want to make this actually useful, because it doesn't implement all the +# semantics to check that what you're asking to write to the wire is sensible, +# but at least it gets you out of dealing with the wire itself. + +from h11._connection import Connection, NEED_DATA, PAUSED +from h11._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from h11._state import ( + CLIENT, + CLOSED, + DONE, + ERROR, + IDLE, + MIGHT_SWITCH_PROTOCOL, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, + SWITCHED_PROTOCOL, +) +from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolError +from h11._version import __version__ + +PRODUCT_ID = "python-h11/" + __version__ + + +__all__ = ( + "Connection", + "NEED_DATA", + "PAUSED", + "ConnectionClosed", + "Data", + "EndOfMessage", + "Event", + "InformationalResponse", + "Request", + "Response", + "CLIENT", + "CLOSED", + "DONE", + "ERROR", + "IDLE", + "MUST_CLOSE", + "SEND_BODY", + "SEND_RESPONSE", + "SERVER", + "SWITCHED_PROTOCOL", + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", +) diff --git a/python_embeded/Lib/site-packages/h11/_abnf.py b/python_embeded/Lib/site-packages/h11/_abnf.py new file mode 100644 index 0000000000000000000000000000000000000000..933587fba22290d7eb7df4c88e12f1e61702b8ce --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_abnf.py @@ -0,0 +1,132 @@ +# We use native strings for all the re patterns, to take advantage of string +# formatting, and then convert to bytestrings when compiling the final re +# objects. + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace +# OWS = *( SP / HTAB ) +# ; optional whitespace +OWS = r"[ \t]*" + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators +# token = 1*tchar +# +# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" +# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" +# / DIGIT / ALPHA +# ; any VCHAR, except delimiters +token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+" + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields +# field-name = token +field_name = token + +# The standard says: +# +# field-value = *( field-content / obs-fold ) +# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] +# field-vchar = VCHAR / obs-text +# obs-fold = CRLF 1*( SP / HTAB ) +# ; obsolete line folding +# ; see Section 3.2.4 +# +# https://tools.ietf.org/html/rfc5234#appendix-B.1 +# +# VCHAR = %x21-7E +# ; visible (printing) characters +# +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string +# obs-text = %x80-FF +# +# However, the standard definition of field-content is WRONG! It disallows +# fields containing a single visible character surrounded by whitespace, +# e.g. "foo a bar". +# +# See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 +# +# So our definition of field_content attempts to fix it up... +# +# Also, we allow lots of control characters, because apparently people assume +# that they're legal in practice (e.g., google analytics makes cookies with +# \x01 in them!): +# https://github.com/python-hyper/h11/issues/57 +# We still don't allow NUL or whitespace, because those are often treated as +# meta-characters and letting them through can lead to nasty issues like SSRF. +vchar = r"[\x21-\x7e]" +vchar_or_obs_text = r"[^\x00\s]" +field_vchar = vchar_or_obs_text +field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals()) + +# We handle obs-fold at a different level, and our fixed-up field_content +# already grows to swallow the whole value, so ? instead of * +field_value = r"({field_content})?".format(**globals()) + +# header-field = field-name ":" OWS field-value OWS +header_field = ( + r"(?P{field_name})" + r":" + r"{OWS}" + r"(?P{field_value})" + r"{OWS}".format(**globals()) +) + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line +# +# request-line = method SP request-target SP HTTP-version CRLF +# method = token +# HTTP-version = HTTP-name "/" DIGIT "." DIGIT +# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive +# +# request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full +# URL, host+port (for connect), or even "*", but in any case we are guaranteed +# that it contists of the visible printing characters. +method = token +request_target = r"{vchar}+".format(**globals()) +http_version = r"HTTP/(?P[0-9]\.[0-9])" +request_line = ( + r"(?P{method})" + r" " + r"(?P{request_target})" + r" " + r"{http_version}".format(**globals()) +) + +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line +# +# status-line = HTTP-version SP status-code SP reason-phrase CRLF +# status-code = 3DIGIT +# reason-phrase = *( HTAB / SP / VCHAR / obs-text ) +status_code = r"[0-9]{3}" +reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals()) +status_line = ( + r"{http_version}" + r" " + r"(?P{status_code})" + # However, there are apparently a few too many servers out there that just + # leave out the reason phrase: + # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036 + # https://github.com/seanmonstar/httparse/issues/29 + # so make it optional. ?: is a non-capturing group. + r"(?: (?P{reason_phrase}))?".format(**globals()) +) + +HEXDIG = r"[0-9A-Fa-f]" +# Actually +# +# chunk-size = 1*HEXDIG +# +# but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20 +chunk_size = r"({HEXDIG}){{1,20}}".format(**globals()) +# Actually +# +# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) +# +# but we aren't parsing the things so we don't really care. +chunk_ext = r";.*" +chunk_header = ( + r"(?P{chunk_size})" + r"(?P{chunk_ext})?" + r"{OWS}\r\n".format( + **globals() + ) # Even though the specification does not allow for extra whitespaces, + # we are lenient with trailing whitespaces because some servers on the wild use it. +) diff --git a/python_embeded/Lib/site-packages/h11/_connection.py b/python_embeded/Lib/site-packages/h11/_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..e37d82a82a882c072cb938a90eb4486b51cdad99 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_connection.py @@ -0,0 +1,659 @@ +# This contains the main Connection class. Everything in h11 revolves around +# this. +from typing import ( + Any, + Callable, + cast, + Dict, + List, + Optional, + overload, + Tuple, + Type, + Union, +) + +from ._events import ( + ConnectionClosed, + Data, + EndOfMessage, + Event, + InformationalResponse, + Request, + Response, +) +from ._headers import get_comma_header, has_expect_100_continue, set_comma_header +from ._readers import READERS, ReadersType +from ._receivebuffer import ReceiveBuffer +from ._state import ( + _SWITCH_CONNECT, + _SWITCH_UPGRADE, + CLIENT, + ConnectionState, + DONE, + ERROR, + MIGHT_SWITCH_PROTOCOL, + SEND_BODY, + SERVER, + SWITCHED_PROTOCOL, +) +from ._util import ( # Import the internal things we need + LocalProtocolError, + RemoteProtocolError, + Sentinel, +) +from ._writers import WRITERS, WritersType + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = ["Connection", "NEED_DATA", "PAUSED"] + + +class NEED_DATA(Sentinel, metaclass=Sentinel): + pass + + +class PAUSED(Sentinel, metaclass=Sentinel): + pass + + +# If we ever have this much buffered without it making a complete parseable +# event, we error out. The only time we really buffer is when reading the +# request/response line + headers together, so this is effectively the limit on +# the size of that. +# +# Some precedents for defaults: +# - node.js: 80 * 1024 +# - tomcat: 8 * 1024 +# - IIS: 16 * 1024 +# - Apache: <8 KiB per line> +DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024 + + +# RFC 7230's rules for connection lifecycles: +# - If either side says they want to close the connection, then the connection +# must close. +# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close +# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive +# (and even this is a mess -- e.g. if you're implementing a proxy then +# sending Connection: keep-alive is forbidden). +# +# We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So +# our rule is: +# - If someone says Connection: close, we will close +# - If someone uses HTTP/1.0, we will close. +def _keep_alive(event: Union[Request, Response]) -> bool: + connection = get_comma_header(event.headers, b"connection") + if b"close" in connection: + return False + if getattr(event, "http_version", b"1.1") < b"1.1": + return False + return True + + +def _body_framing( + request_method: bytes, event: Union[Request, Response] +) -> Tuple[str, Union[Tuple[()], Tuple[int]]]: + # Called when we enter SEND_BODY to figure out framing information for + # this body. + # + # These are the only two events that can trigger a SEND_BODY state: + assert type(event) in (Request, Response) + # Returns one of: + # + # ("content-length", count) + # ("chunked", ()) + # ("http/1.0", ()) + # + # which are (lookup key, *args) for constructing body reader/writer + # objects. + # + # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3 + # + # Step 1: some responses always have an empty body, regardless of what the + # headers say. + if type(event) is Response: + if ( + event.status_code in (204, 304) + or request_method == b"HEAD" + or (request_method == b"CONNECT" and 200 <= event.status_code < 300) + ): + return ("content-length", (0,)) + # Section 3.3.3 also lists another case -- responses with status_code + # < 200. For us these are InformationalResponses, not Responses, so + # they can't get into this function in the first place. + assert event.status_code >= 200 + + # Step 2: check for Transfer-Encoding (T-E beats C-L): + transfer_encodings = get_comma_header(event.headers, b"transfer-encoding") + if transfer_encodings: + assert transfer_encodings == [b"chunked"] + return ("chunked", ()) + + # Step 3: check for Content-Length + content_lengths = get_comma_header(event.headers, b"content-length") + if content_lengths: + return ("content-length", (int(content_lengths[0]),)) + + # Step 4: no applicable headers; fallback/default depends on type + if type(event) is Request: + return ("content-length", (0,)) + else: + return ("http/1.0", ()) + + +################################################################ +# +# The main Connection class +# +################################################################ + + +class Connection: + """An object encapsulating the state of an HTTP connection. + + Args: + our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If + you're implementing a server, pass :data:`h11.SERVER`. + + max_incomplete_event_size (int): + The maximum number of bytes we're willing to buffer of an + incomplete event. In practice this mostly sets a limit on the + maximum size of the request/response line + headers. If this is + exceeded, then :meth:`next_event` will raise + :exc:`RemoteProtocolError`. + + """ + + def __init__( + self, + our_role: Type[Sentinel], + max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, + ) -> None: + self._max_incomplete_event_size = max_incomplete_event_size + # State and role tracking + if our_role not in (CLIENT, SERVER): + raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}") + self.our_role = our_role + self.their_role: Type[Sentinel] + if our_role is CLIENT: + self.their_role = SERVER + else: + self.their_role = CLIENT + self._cstate = ConnectionState() + + # Callables for converting data->events or vice-versa given the + # current state + self._writer = self._get_io_object(self.our_role, None, WRITERS) + self._reader = self._get_io_object(self.their_role, None, READERS) + + # Holds any unprocessed received data + self._receive_buffer = ReceiveBuffer() + # If this is true, then it indicates that the incoming connection was + # closed *after* the end of whatever's in self._receive_buffer: + self._receive_buffer_closed = False + + # Extra bits of state that don't fit into the state machine. + # + # These two are only used to interpret framing headers for figuring + # out how to read/write response bodies. their_http_version is also + # made available as a convenient public API. + self.their_http_version: Optional[bytes] = None + self._request_method: Optional[bytes] = None + # This is pure flow-control and doesn't at all affect the set of legal + # transitions, so no need to bother ConnectionState with it: + self.client_is_waiting_for_100_continue = False + + @property + def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]: + """A dictionary like:: + + {CLIENT: , SERVER: } + + See :ref:`state-machine` for details. + + """ + return dict(self._cstate.states) + + @property + def our_state(self) -> Type[Sentinel]: + """The current state of whichever role we are playing. See + :ref:`state-machine` for details. + """ + return self._cstate.states[self.our_role] + + @property + def their_state(self) -> Type[Sentinel]: + """The current state of whichever role we are NOT playing. See + :ref:`state-machine` for details. + """ + return self._cstate.states[self.their_role] + + @property + def they_are_waiting_for_100_continue(self) -> bool: + return self.their_role is CLIENT and self.client_is_waiting_for_100_continue + + def start_next_cycle(self) -> None: + """Attempt to reset our connection state for a new request/response + cycle. + + If both client and server are in :data:`DONE` state, then resets them + both to :data:`IDLE` state in preparation for a new request/response + cycle on this same connection. Otherwise, raises a + :exc:`LocalProtocolError`. + + See :ref:`keepalive-and-pipelining`. + + """ + old_states = dict(self._cstate.states) + self._cstate.start_next_cycle() + self._request_method = None + # self.their_http_version gets left alone, since it presumably lasts + # beyond a single request/response cycle + assert not self.client_is_waiting_for_100_continue + self._respond_to_state_changes(old_states) + + def _process_error(self, role: Type[Sentinel]) -> None: + old_states = dict(self._cstate.states) + self._cstate.process_error(role) + self._respond_to_state_changes(old_states) + + def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]: + if type(event) is InformationalResponse and event.status_code == 101: + return _SWITCH_UPGRADE + if type(event) is Response: + if ( + _SWITCH_CONNECT in self._cstate.pending_switch_proposals + and 200 <= event.status_code < 300 + ): + return _SWITCH_CONNECT + return None + + # All events go through here + def _process_event(self, role: Type[Sentinel], event: Event) -> None: + # First, pass the event through the state machine to make sure it + # succeeds. + old_states = dict(self._cstate.states) + if role is CLIENT and type(event) is Request: + if event.method == b"CONNECT": + self._cstate.process_client_switch_proposal(_SWITCH_CONNECT) + if get_comma_header(event.headers, b"upgrade"): + self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE) + server_switch_event = None + if role is SERVER: + server_switch_event = self._server_switch_event(event) + self._cstate.process_event(role, type(event), server_switch_event) + + # Then perform the updates triggered by it. + + if type(event) is Request: + self._request_method = event.method + + if role is self.their_role and type(event) in ( + Request, + Response, + InformationalResponse, + ): + event = cast(Union[Request, Response, InformationalResponse], event) + self.their_http_version = event.http_version + + # Keep alive handling + # + # RFC 7230 doesn't really say what one should do if Connection: close + # shows up on a 1xx InformationalResponse. I think the idea is that + # this is not supposed to happen. In any case, if it does happen, we + # ignore it. + if type(event) in (Request, Response) and not _keep_alive( + cast(Union[Request, Response], event) + ): + self._cstate.process_keep_alive_disabled() + + # 100-continue + if type(event) is Request and has_expect_100_continue(event): + self.client_is_waiting_for_100_continue = True + if type(event) in (InformationalResponse, Response): + self.client_is_waiting_for_100_continue = False + if role is CLIENT and type(event) in (Data, EndOfMessage): + self.client_is_waiting_for_100_continue = False + + self._respond_to_state_changes(old_states, event) + + def _get_io_object( + self, + role: Type[Sentinel], + event: Optional[Event], + io_dict: Union[ReadersType, WritersType], + ) -> Optional[Callable[..., Any]]: + # event may be None; it's only used when entering SEND_BODY + state = self._cstate.states[role] + if state is SEND_BODY: + # Special case: the io_dict has a dict of reader/writer factories + # that depend on the request/response framing. + framing_type, args = _body_framing( + cast(bytes, self._request_method), cast(Union[Request, Response], event) + ) + return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index] + else: + # General case: the io_dict just has the appropriate reader/writer + # for this state + return io_dict.get((role, state)) # type: ignore[return-value] + + # This must be called after any action that might have caused + # self._cstate.states to change. + def _respond_to_state_changes( + self, + old_states: Dict[Type[Sentinel], Type[Sentinel]], + event: Optional[Event] = None, + ) -> None: + # Update reader/writer + if self.our_state != old_states[self.our_role]: + self._writer = self._get_io_object(self.our_role, event, WRITERS) + if self.their_state != old_states[self.their_role]: + self._reader = self._get_io_object(self.their_role, event, READERS) + + @property + def trailing_data(self) -> Tuple[bytes, bool]: + """Data that has been received, but not yet processed, represented as + a tuple with two elements, where the first is a byte-string containing + the unprocessed data itself, and the second is a bool that is True if + the receive connection was closed. + + See :ref:`switching-protocols` for discussion of why you'd want this. + """ + return (bytes(self._receive_buffer), self._receive_buffer_closed) + + def receive_data(self, data: bytes) -> None: + """Add data to our internal receive buffer. + + This does not actually do any processing on the data, just stores + it. To trigger processing, you have to call :meth:`next_event`. + + Args: + data (:term:`bytes-like object`): + The new data that was just received. + + Special case: If *data* is an empty byte-string like ``b""``, + then this indicates that the remote side has closed the + connection (end of file). Normally this is convenient, because + standard Python APIs like :meth:`file.read` or + :meth:`socket.recv` use ``b""`` to indicate end-of-file, while + other failures to read are indicated using other mechanisms + like raising :exc:`TimeoutError`. When using such an API you + can just blindly pass through whatever you get from ``read`` + to :meth:`receive_data`, and everything will work. + + But, if you have an API where reading an empty string is a + valid non-EOF condition, then you need to be aware of this and + make sure to check for such strings and avoid passing them to + :meth:`receive_data`. + + Returns: + Nothing, but after calling this you should call :meth:`next_event` + to parse the newly received data. + + Raises: + RuntimeError: + Raised if you pass an empty *data*, indicating EOF, and then + pass a non-empty *data*, indicating more data that somehow + arrived after the EOF. + + (Calling ``receive_data(b"")`` multiple times is fine, + and equivalent to calling it once.) + + """ + if data: + if self._receive_buffer_closed: + raise RuntimeError("received close, then received more data?") + self._receive_buffer += data + else: + self._receive_buffer_closed = True + + def _extract_next_receive_event( + self, + ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + state = self.their_state + # We don't pause immediately when they enter DONE, because even in + # DONE state we can still process a ConnectionClosed() event. But + # if we have data in our buffer, then we definitely aren't getting + # a ConnectionClosed() immediately and we need to pause. + if state is DONE and self._receive_buffer: + return PAUSED + if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: + return PAUSED + assert self._reader is not None + event = self._reader(self._receive_buffer) + if event is None: + if not self._receive_buffer and self._receive_buffer_closed: + # In some unusual cases (basically just HTTP/1.0 bodies), EOF + # triggers an actual protocol event; in that case, we want to + # return that event, and then the state will change and we'll + # get called again to generate the actual ConnectionClosed(). + if hasattr(self._reader, "read_eof"): + event = self._reader.read_eof() + else: + event = ConnectionClosed() + if event is None: + event = NEED_DATA + return event # type: ignore[no-any-return] + + def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: + """Parse the next event out of our receive buffer, update our internal + state, and return it. + + This is a mutating operation -- think of it like calling :func:`next` + on an iterator. + + Returns: + : One of three things: + + 1) An event object -- see :ref:`events`. + + 2) The special constant :data:`NEED_DATA`, which indicates that + you need to read more data from your socket and pass it to + :meth:`receive_data` before this method will be able to return + any more events. + + 3) The special constant :data:`PAUSED`, which indicates that we + are not in a state where we can process incoming data (usually + because the peer has finished their part of the current + request/response cycle, and you have not yet called + :meth:`start_next_cycle`). See :ref:`flow-control` for details. + + Raises: + RemoteProtocolError: + The peer has misbehaved. You should close the connection + (possibly after sending some kind of 4xx response). + + Once this method returns :class:`ConnectionClosed` once, then all + subsequent calls will also return :class:`ConnectionClosed`. + + If this method raises any exception besides :exc:`RemoteProtocolError` + then that's a bug -- if it happens please file a bug report! + + If this method raises any exception then it also sets + :attr:`Connection.their_state` to :data:`ERROR` -- see + :ref:`error-handling` for discussion. + + """ + + if self.their_state is ERROR: + raise RemoteProtocolError("Can't receive data when peer state is ERROR") + try: + event = self._extract_next_receive_event() + if event not in [NEED_DATA, PAUSED]: + self._process_event(self.their_role, cast(Event, event)) + if event is NEED_DATA: + if len(self._receive_buffer) > self._max_incomplete_event_size: + # 431 is "Request header fields too large" which is pretty + # much the only situation where we can get here + raise RemoteProtocolError( + "Receive buffer too long", error_status_hint=431 + ) + if self._receive_buffer_closed: + # We're still trying to complete some event, but that's + # never going to happen because no more data is coming + raise RemoteProtocolError("peer unexpectedly closed connection") + return event + except BaseException as exc: + self._process_error(self.their_role) + if isinstance(exc, LocalProtocolError): + exc._reraise_as_remote_protocol_error() + else: + raise + + @overload + def send(self, event: ConnectionClosed) -> None: + ... + + @overload + def send( + self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage] + ) -> bytes: + ... + + @overload + def send(self, event: Event) -> Optional[bytes]: + ... + + def send(self, event: Event) -> Optional[bytes]: + """Convert a high-level event into bytes that can be sent to the peer, + while updating our internal state machine. + + Args: + event: The :ref:`event ` to send. + + Returns: + If ``type(event) is ConnectionClosed``, then returns + ``None``. Otherwise, returns a :term:`bytes-like object`. + + Raises: + LocalProtocolError: + Sending this event at this time would violate our + understanding of the HTTP/1.1 protocol. + + If this method raises any exception then it also sets + :attr:`Connection.our_state` to :data:`ERROR` -- see + :ref:`error-handling` for discussion. + + """ + data_list = self.send_with_data_passthrough(event) + if data_list is None: + return None + else: + return b"".join(data_list) + + def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: + """Identical to :meth:`send`, except that in situations where + :meth:`send` returns a single :term:`bytes-like object`, this instead + returns a list of them -- and when sending a :class:`Data` event, this + list is guaranteed to contain the exact object you passed in as + :attr:`Data.data`. See :ref:`sendfile` for discussion. + + """ + if self.our_state is ERROR: + raise LocalProtocolError("Can't send data when our state is ERROR") + try: + if type(event) is Response: + event = self._clean_up_response_headers_for_sending(event) + # We want to call _process_event before calling the writer, + # because if someone tries to do something invalid then this will + # give a sensible error message, while our writers all just assume + # they will only receive valid events. But, _process_event might + # change self._writer. So we have to do a little dance: + writer = self._writer + self._process_event(self.our_role, event) + if type(event) is ConnectionClosed: + return None + else: + # In any situation where writer is None, process_event should + # have raised ProtocolError + assert writer is not None + data_list: List[bytes] = [] + writer(event, data_list.append) + return data_list + except: + self._process_error(self.our_role) + raise + + def send_failed(self) -> None: + """Notify the state machine that we failed to send the data it gave + us. + + This causes :attr:`Connection.our_state` to immediately become + :data:`ERROR` -- see :ref:`error-handling` for discussion. + + """ + self._process_error(self.our_role) + + # When sending a Response, we take responsibility for a few things: + # + # - Sometimes you MUST set Connection: close. We take care of those + # times. (You can also set it yourself if you want, and if you do then + # we'll respect that and close the connection at the right time. But you + # don't have to worry about that unless you want to.) + # + # - The user has to set Content-Length if they want it. Otherwise, for + # responses that have bodies (e.g. not HEAD), then we will automatically + # select the right mechanism for streaming a body of unknown length, + # which depends on depending on the peer's HTTP version. + # + # This function's *only* responsibility is making sure headers are set up + # right -- everything downstream just looks at the headers. There are no + # side channels. + def _clean_up_response_headers_for_sending(self, response: Response) -> Response: + assert type(response) is Response + + headers = response.headers + need_close = False + + # HEAD requests need some special handling: they always act like they + # have Content-Length: 0, and that's how _body_framing treats + # them. But their headers are supposed to match what we would send if + # the request was a GET. (Technically there is one deviation allowed: + # we're allowed to leave out the framing headers -- see + # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as + # easy to get them right.) + method_for_choosing_headers = cast(bytes, self._request_method) + if method_for_choosing_headers == b"HEAD": + method_for_choosing_headers = b"GET" + framing_type, _ = _body_framing(method_for_choosing_headers, response) + if framing_type in ("chunked", "http/1.0"): + # This response has a body of unknown length. + # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked + # If our peer is HTTP/1.0, we use no framing headers, and close the + # connection afterwards. + # + # Make sure to clear Content-Length (in principle user could have + # set both and then we ignored Content-Length b/c + # Transfer-Encoding overwrote it -- this would be naughty of them, + # but the HTTP spec says that if our peer does this then we have + # to fix it instead of erroring out, so we'll accord the user the + # same respect). + headers = set_comma_header(headers, b"content-length", []) + if self.their_http_version is None or self.their_http_version < b"1.1": + # Either we never got a valid request and are sending back an + # error (their_http_version is None), so we assume the worst; + # or else we did get a valid HTTP/1.0 request, so we know that + # they don't understand chunked encoding. + headers = set_comma_header(headers, b"transfer-encoding", []) + # This is actually redundant ATM, since currently we + # unconditionally disable keep-alive when talking to HTTP/1.0 + # peers. But let's be defensive just in case we add + # Connection: keep-alive support later: + if self._request_method != b"HEAD": + need_close = True + else: + headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"]) + + if not self._cstate.keep_alive or need_close: + # Make sure Connection: close is set + connection = set(get_comma_header(headers, b"connection")) + connection.discard(b"keep-alive") + connection.add(b"close") + headers = set_comma_header(headers, b"connection", sorted(connection)) + + return Response( + headers=headers, + status_code=response.status_code, + http_version=response.http_version, + reason=response.reason, + ) diff --git a/python_embeded/Lib/site-packages/h11/_events.py b/python_embeded/Lib/site-packages/h11/_events.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1c3adbde2c4e7710482a18e3471f91f1da610e --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_events.py @@ -0,0 +1,369 @@ +# High level events that make up HTTP/1.1 conversations. Loosely inspired by +# the corresponding events in hyper-h2: +# +# http://python-hyper.org/h2/en/stable/api.html#events +# +# Don't subclass these. Stuff will break. + +import re +from abc import ABC +from dataclasses import dataclass +from typing import List, Tuple, Union + +from ._abnf import method, request_target +from ._headers import Headers, normalize_and_validate +from ._util import bytesify, LocalProtocolError, validate + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = [ + "Event", + "Request", + "InformationalResponse", + "Response", + "Data", + "EndOfMessage", + "ConnectionClosed", +] + +method_re = re.compile(method.encode("ascii")) +request_target_re = re.compile(request_target.encode("ascii")) + + +class Event(ABC): + """ + Base class for h11 events. + """ + + __slots__ = () + + +@dataclass(init=False, frozen=True) +class Request(Event): + """The beginning of an HTTP request. + + Fields: + + .. attribute:: method + + An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte + string. :term:`Bytes-like objects ` and native + strings containing only ascii characters will be automatically + converted to byte strings. + + .. attribute:: target + + The target of an HTTP request, e.g. ``b"/index.html"``, or one of the + more exotic formats described in `RFC 7320, section 5.3 + `_. Always a byte + string. :term:`Bytes-like objects ` and native + strings containing only ascii characters will be automatically + converted to byte strings. + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + """ + + __slots__ = ("method", "headers", "target", "http_version") + + method: bytes + headers: Headers + target: bytes + http_version: bytes + + def __init__( + self, + *, + method: Union[bytes, str], + headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], + target: Union[bytes, str], + http_version: Union[bytes, str] = b"1.1", + _parsed: bool = False, + ) -> None: + super().__init__() + if isinstance(headers, Headers): + object.__setattr__(self, "headers", headers) + else: + object.__setattr__( + self, "headers", normalize_and_validate(headers, _parsed=_parsed) + ) + if not _parsed: + object.__setattr__(self, "method", bytesify(method)) + object.__setattr__(self, "target", bytesify(target)) + object.__setattr__(self, "http_version", bytesify(http_version)) + else: + object.__setattr__(self, "method", method) + object.__setattr__(self, "target", target) + object.__setattr__(self, "http_version", http_version) + + # "A server MUST respond with a 400 (Bad Request) status code to any + # HTTP/1.1 request message that lacks a Host header field and to any + # request message that contains more than one Host header field or a + # Host header field with an invalid field-value." + # -- https://tools.ietf.org/html/rfc7230#section-5.4 + host_count = 0 + for name, value in self.headers: + if name == b"host": + host_count += 1 + if self.http_version == b"1.1" and host_count == 0: + raise LocalProtocolError("Missing mandatory Host: header") + if host_count > 1: + raise LocalProtocolError("Found multiple Host: headers") + + validate(method_re, self.method, "Illegal method characters") + validate(request_target_re, self.target, "Illegal target characters") + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class _ResponseBase(Event): + __slots__ = ("headers", "http_version", "reason", "status_code") + + headers: Headers + http_version: bytes + reason: bytes + status_code: int + + def __init__( + self, + *, + headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], + status_code: int, + http_version: Union[bytes, str] = b"1.1", + reason: Union[bytes, str] = b"", + _parsed: bool = False, + ) -> None: + super().__init__() + if isinstance(headers, Headers): + object.__setattr__(self, "headers", headers) + else: + object.__setattr__( + self, "headers", normalize_and_validate(headers, _parsed=_parsed) + ) + if not _parsed: + object.__setattr__(self, "reason", bytesify(reason)) + object.__setattr__(self, "http_version", bytesify(http_version)) + if not isinstance(status_code, int): + raise LocalProtocolError("status code must be integer") + # Because IntEnum objects are instances of int, but aren't + # duck-compatible (sigh), see gh-72. + object.__setattr__(self, "status_code", int(status_code)) + else: + object.__setattr__(self, "reason", reason) + object.__setattr__(self, "http_version", http_version) + object.__setattr__(self, "status_code", status_code) + + self.__post_init__() + + def __post_init__(self) -> None: + pass + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class InformationalResponse(_ResponseBase): + """An HTTP informational response. + + Fields: + + .. attribute:: status_code + + The status code of this response, as an integer. For an + :class:`InformationalResponse`, this is always in the range [100, + 200). + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for + details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + .. attribute:: reason + + The reason phrase of this response, as a byte string. For example: + ``b"OK"``, or ``b"Not Found"``. + + """ + + def __post_init__(self) -> None: + if not (100 <= self.status_code < 200): + raise LocalProtocolError( + "InformationalResponse status_code should be in range " + "[100, 200), not {}".format(self.status_code) + ) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class Response(_ResponseBase): + """The beginning of an HTTP response. + + Fields: + + .. attribute:: status_code + + The status code of this response, as an integer. For an + :class:`Response`, this is always in the range [200, + 1000). + + .. attribute:: headers + + Request headers, represented as a list of (name, value) pairs. See + :ref:`the header normalization rules ` for details. + + .. attribute:: http_version + + The HTTP protocol version, represented as a byte string like + ``b"1.1"``. See :ref:`the HTTP version normalization rules + ` for details. + + .. attribute:: reason + + The reason phrase of this response, as a byte string. For example: + ``b"OK"``, or ``b"Not Found"``. + + """ + + def __post_init__(self) -> None: + if not (200 <= self.status_code < 1000): + raise LocalProtocolError( + "Response status_code should be in range [200, 1000), not {}".format( + self.status_code + ) + ) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(init=False, frozen=True) +class Data(Event): + """Part of an HTTP message body. + + Fields: + + .. attribute:: data + + A :term:`bytes-like object` containing part of a message body. Or, if + using the ``combine=False`` argument to :meth:`Connection.send`, then + any object that your socket writing code knows what to do with, and for + which calling :func:`len` returns the number of bytes that will be + written -- see :ref:`sendfile` for details. + + .. attribute:: chunk_start + + A marker that indicates whether this data object is from the start of a + chunked transfer encoding chunk. This field is ignored when when a Data + event is provided to :meth:`Connection.send`: it is only valid on + events emitted from :meth:`Connection.next_event`. You probably + shouldn't use this attribute at all; see + :ref:`chunk-delimiters-are-bad` for details. + + .. attribute:: chunk_end + + A marker that indicates whether this data object is the last for a + given chunked transfer encoding chunk. This field is ignored when when + a Data event is provided to :meth:`Connection.send`: it is only valid + on events emitted from :meth:`Connection.next_event`. You probably + shouldn't use this attribute at all; see + :ref:`chunk-delimiters-are-bad` for details. + + """ + + __slots__ = ("data", "chunk_start", "chunk_end") + + data: bytes + chunk_start: bool + chunk_end: bool + + def __init__( + self, data: bytes, chunk_start: bool = False, chunk_end: bool = False + ) -> None: + object.__setattr__(self, "data", data) + object.__setattr__(self, "chunk_start", chunk_start) + object.__setattr__(self, "chunk_end", chunk_end) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that +# are forbidden to be sent in a trailer, since processing them as if they were +# present in the header section might bypass external security filters." +# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part +# Unfortunately, the list of forbidden fields is long and vague :-/ +@dataclass(init=False, frozen=True) +class EndOfMessage(Event): + """The end of an HTTP message. + + Fields: + + .. attribute:: headers + + Default value: ``[]`` + + Any trailing headers attached to this message, represented as a list of + (name, value) pairs. See :ref:`the header normalization rules + ` for details. + + Must be empty unless ``Transfer-Encoding: chunked`` is in use. + + """ + + __slots__ = ("headers",) + + headers: Headers + + def __init__( + self, + *, + headers: Union[ + Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None + ] = None, + _parsed: bool = False, + ) -> None: + super().__init__() + if headers is None: + headers = Headers([]) + elif not isinstance(headers, Headers): + headers = normalize_and_validate(headers, _parsed=_parsed) + + object.__setattr__(self, "headers", headers) + + # This is an unhashable type. + __hash__ = None # type: ignore + + +@dataclass(frozen=True) +class ConnectionClosed(Event): + """This event indicates that the sender has closed their outgoing + connection. + + Note that this does not necessarily mean that they can't *receive* further + data, because TCP connections are composed to two one-way channels which + can be closed independently. See :ref:`closing` for details. + + No fields. + """ + + pass diff --git a/python_embeded/Lib/site-packages/h11/_headers.py b/python_embeded/Lib/site-packages/h11/_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..31da3e2b23b55a624b36f105e62a6902e63286aa --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_headers.py @@ -0,0 +1,282 @@ +import re +from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union + +from ._abnf import field_name, field_value +from ._util import bytesify, LocalProtocolError, validate + +if TYPE_CHECKING: + from ._events import Request + +try: + from typing import Literal +except ImportError: + from typing_extensions import Literal # type: ignore + +CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1 + + +# Facts +# ----- +# +# Headers are: +# keys: case-insensitive ascii +# values: mixture of ascii and raw bytes +# +# "Historically, HTTP has allowed field content with text in the ISO-8859-1 +# charset [ISO-8859-1], supporting other charsets only through use of +# [RFC2047] encoding. In practice, most HTTP header field values use only a +# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD +# limit their field values to US-ASCII octets. A recipient SHOULD treat other +# octets in field content (obs-text) as opaque data." +# And it deprecates all non-ascii values +# +# Leading/trailing whitespace in header names is forbidden +# +# Values get leading/trailing whitespace stripped +# +# Content-Disposition actually needs to contain unicode semantically; to +# accomplish this it has a terrifically weird way of encoding the filename +# itself as ascii (and even this still has lots of cross-browser +# incompatibilities) +# +# Order is important: +# "a proxy MUST NOT change the order of these field values when forwarding a +# message" +# (and there are several headers where the order indicates a preference) +# +# Multiple occurences of the same header: +# "A sender MUST NOT generate multiple header fields with the same field name +# in a message unless either the entire field value for that header field is +# defined as a comma-separated list [or the header is Set-Cookie which gets a +# special exception]" - RFC 7230. (cookies are in RFC 6265) +# +# So every header aside from Set-Cookie can be merged by b", ".join if it +# occurs repeatedly. But, of course, they can't necessarily be split by +# .split(b","), because quoting. +# +# Given all this mess (case insensitive, duplicates allowed, order is +# important, ...), there doesn't appear to be any standard way to handle +# headers in Python -- they're almost like dicts, but... actually just +# aren't. For now we punt and just use a super simple representation: headers +# are a list of pairs +# +# [(name1, value1), (name2, value2), ...] +# +# where all entries are bytestrings, names are lowercase and have no +# leading/trailing whitespace, and values are bytestrings with no +# leading/trailing whitespace. Searching and updating are done via naive O(n) +# methods. +# +# Maybe a dict-of-lists would be better? + +_content_length_re = re.compile(rb"[0-9]+") +_field_name_re = re.compile(field_name.encode("ascii")) +_field_value_re = re.compile(field_value.encode("ascii")) + + +class Headers(Sequence[Tuple[bytes, bytes]]): + """ + A list-like interface that allows iterating over headers as byte-pairs + of (lowercased-name, value). + + Internally we actually store the representation as three-tuples, + including both the raw original casing, in order to preserve casing + over-the-wire, and the lowercased name, for case-insensitive comparisions. + + r = Request( + method="GET", + target="/", + headers=[("Host", "example.org"), ("Connection", "keep-alive")], + http_version="1.1", + ) + assert r.headers == [ + (b"host", b"example.org"), + (b"connection", b"keep-alive") + ] + assert r.headers.raw_items() == [ + (b"Host", b"example.org"), + (b"Connection", b"keep-alive") + ] + """ + + __slots__ = "_full_items" + + def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: + self._full_items = full_items + + def __bool__(self) -> bool: + return bool(self._full_items) + + def __eq__(self, other: object) -> bool: + return list(self) == list(other) # type: ignore + + def __len__(self) -> int: + return len(self._full_items) + + def __repr__(self) -> str: + return "" % repr(list(self)) + + def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override] + _, name, value = self._full_items[idx] + return (name, value) + + def raw_items(self) -> List[Tuple[bytes, bytes]]: + return [(raw_name, value) for raw_name, _, value in self._full_items] + + +HeaderTypes = Union[ + List[Tuple[bytes, bytes]], + List[Tuple[bytes, str]], + List[Tuple[str, bytes]], + List[Tuple[str, str]], +] + + +@overload +def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: + ... + + +@overload +def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: + ... + + +@overload +def normalize_and_validate( + headers: Union[Headers, HeaderTypes], _parsed: bool = False +) -> Headers: + ... + + +def normalize_and_validate( + headers: Union[Headers, HeaderTypes], _parsed: bool = False +) -> Headers: + new_headers = [] + seen_content_length = None + saw_transfer_encoding = False + for name, value in headers: + # For headers coming out of the parser, we can safely skip some steps, + # because it always returns bytes and has already run these regexes + # over the data: + if not _parsed: + name = bytesify(name) + value = bytesify(value) + validate(_field_name_re, name, "Illegal header name {!r}", name) + validate(_field_value_re, value, "Illegal header value {!r}", value) + assert isinstance(name, bytes) + assert isinstance(value, bytes) + + raw_name = name + name = name.lower() + if name == b"content-length": + lengths = {length.strip() for length in value.split(b",")} + if len(lengths) != 1: + raise LocalProtocolError("conflicting Content-Length headers") + value = lengths.pop() + validate(_content_length_re, value, "bad Content-Length") + if len(value) > CONTENT_LENGTH_MAX_DIGITS: + raise LocalProtocolError("bad Content-Length") + if seen_content_length is None: + seen_content_length = value + new_headers.append((raw_name, name, value)) + elif seen_content_length != value: + raise LocalProtocolError("conflicting Content-Length headers") + elif name == b"transfer-encoding": + # "A server that receives a request message with a transfer coding + # it does not understand SHOULD respond with 501 (Not + # Implemented)." + # https://tools.ietf.org/html/rfc7230#section-3.3.1 + if saw_transfer_encoding: + raise LocalProtocolError( + "multiple Transfer-Encoding headers", error_status_hint=501 + ) + # "All transfer-coding names are case-insensitive" + # -- https://tools.ietf.org/html/rfc7230#section-4 + value = value.lower() + if value != b"chunked": + raise LocalProtocolError( + "Only Transfer-Encoding: chunked is supported", + error_status_hint=501, + ) + saw_transfer_encoding = True + new_headers.append((raw_name, name, value)) + else: + new_headers.append((raw_name, name, value)) + return Headers(new_headers) + + +def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: + # Should only be used for headers whose value is a list of + # comma-separated, case-insensitive values. + # + # The header name `name` is expected to be lower-case bytes. + # + # Connection: meets these criteria (including cast insensitivity). + # + # Content-Length: technically is just a single value (1*DIGIT), but the + # standard makes reference to implementations that do multiple values, and + # using this doesn't hurt. Ditto, case insensitivity doesn't things either + # way. + # + # Transfer-Encoding: is more complex (allows for quoted strings), so + # splitting on , is actually wrong. For example, this is legal: + # + # Transfer-Encoding: foo; options="1,2", chunked + # + # and should be parsed as + # + # foo; options="1,2" + # chunked + # + # but this naive function will parse it as + # + # foo; options="1 + # 2" + # chunked + # + # However, this is okay because the only thing we are going to do with + # any Transfer-Encoding is reject ones that aren't just "chunked", so + # both of these will be treated the same anyway. + # + # Expect: the only legal value is the literal string + # "100-continue". Splitting on commas is harmless. Case insensitive. + # + out: List[bytes] = [] + for _, found_name, found_raw_value in headers._full_items: + if found_name == name: + found_raw_value = found_raw_value.lower() + for found_split_value in found_raw_value.split(b","): + found_split_value = found_split_value.strip() + if found_split_value: + out.append(found_split_value) + return out + + +def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers: + # The header name `name` is expected to be lower-case bytes. + # + # Note that when we store the header we use title casing for the header + # names, in order to match the conventional HTTP header style. + # + # Simply calling `.title()` is a blunt approach, but it's correct + # here given the cases where we're using `set_comma_header`... + # + # Connection, Content-Length, Transfer-Encoding. + new_headers: List[Tuple[bytes, bytes]] = [] + for found_raw_name, found_name, found_raw_value in headers._full_items: + if found_name != name: + new_headers.append((found_raw_name, found_raw_value)) + for new_value in new_values: + new_headers.append((name.title(), new_value)) + return normalize_and_validate(new_headers) + + +def has_expect_100_continue(request: "Request") -> bool: + # https://tools.ietf.org/html/rfc7231#section-5.1.1 + # "A server that receives a 100-continue expectation in an HTTP/1.0 request + # MUST ignore that expectation." + if request.http_version < b"1.1": + return False + expect = get_comma_header(request.headers, b"expect") + return b"100-continue" in expect diff --git a/python_embeded/Lib/site-packages/h11/_readers.py b/python_embeded/Lib/site-packages/h11/_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..576804cc282032526e0a932c9853d586a094bad0 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_readers.py @@ -0,0 +1,250 @@ +# Code to read HTTP data +# +# Strategy: each reader is a callable which takes a ReceiveBuffer object, and +# either: +# 1) consumes some of it and returns an Event +# 2) raises a LocalProtocolError (for consistency -- e.g. we call validate() +# and it might raise a LocalProtocolError, so simpler just to always use +# this) +# 3) returns None, meaning "I need more data" +# +# If they have a .read_eof attribute, then this will be called if an EOF is +# received -- but this is optional. Either way, the actual ConnectionClosed +# event will be generated afterwards. +# +# READERS is a dict describing how to pick a reader. It maps states to either: +# - a reader +# - or, for body readers, a dict of per-framing reader factories + +import re +from typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union + +from ._abnf import chunk_header, header_field, request_line, status_line +from ._events import Data, EndOfMessage, InformationalResponse, Request, Response +from ._receivebuffer import ReceiveBuffer +from ._state import ( + CLIENT, + CLOSED, + DONE, + IDLE, + MUST_CLOSE, + SEND_BODY, + SEND_RESPONSE, + SERVER, +) +from ._util import LocalProtocolError, RemoteProtocolError, Sentinel, validate + +__all__ = ["READERS"] + +header_field_re = re.compile(header_field.encode("ascii")) +obs_fold_re = re.compile(rb"[ \t]+") + + +def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]: + it = iter(lines) + last: Optional[bytes] = None + for line in it: + match = obs_fold_re.match(line) + if match: + if last is None: + raise LocalProtocolError("continuation line at start of headers") + if not isinstance(last, bytearray): + # Cast to a mutable type, avoiding copy on append to ensure O(n) time + last = bytearray(last) + last += b" " + last += line[match.end() :] + else: + if last is not None: + yield last + last = line + if last is not None: + yield last + + +def _decode_header_lines( + lines: Iterable[bytes], +) -> Iterable[Tuple[bytes, bytes]]: + for line in _obsolete_line_fold(lines): + matches = validate(header_field_re, line, "illegal header line: {!r}", line) + yield (matches["field_name"], matches["field_value"]) + + +request_line_re = re.compile(request_line.encode("ascii")) + + +def maybe_read_from_IDLE_client(buf: ReceiveBuffer) -> Optional[Request]: + lines = buf.maybe_extract_lines() + if lines is None: + if buf.is_next_line_obviously_invalid_request_line(): + raise LocalProtocolError("illegal request line") + return None + if not lines: + raise LocalProtocolError("no request line received") + matches = validate( + request_line_re, lines[0], "illegal request line: {!r}", lines[0] + ) + return Request( + headers=list(_decode_header_lines(lines[1:])), _parsed=True, **matches + ) + + +status_line_re = re.compile(status_line.encode("ascii")) + + +def maybe_read_from_SEND_RESPONSE_server( + buf: ReceiveBuffer, +) -> Union[InformationalResponse, Response, None]: + lines = buf.maybe_extract_lines() + if lines is None: + if buf.is_next_line_obviously_invalid_request_line(): + raise LocalProtocolError("illegal request line") + return None + if not lines: + raise LocalProtocolError("no response line received") + matches = validate(status_line_re, lines[0], "illegal status line: {!r}", lines[0]) + http_version = ( + b"1.1" if matches["http_version"] is None else matches["http_version"] + ) + reason = b"" if matches["reason"] is None else matches["reason"] + status_code = int(matches["status_code"]) + class_: Union[Type[InformationalResponse], Type[Response]] = ( + InformationalResponse if status_code < 200 else Response + ) + return class_( + headers=list(_decode_header_lines(lines[1:])), + _parsed=True, + status_code=status_code, + reason=reason, + http_version=http_version, + ) + + +class ContentLengthReader: + def __init__(self, length: int) -> None: + self._length = length + self._remaining = length + + def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: + if self._remaining == 0: + return EndOfMessage() + data = buf.maybe_extract_at_most(self._remaining) + if data is None: + return None + self._remaining -= len(data) + return Data(data=data) + + def read_eof(self) -> NoReturn: + raise RemoteProtocolError( + "peer closed connection without sending complete message body " + "(received {} bytes, expected {})".format( + self._length - self._remaining, self._length + ) + ) + + +chunk_header_re = re.compile(chunk_header.encode("ascii")) + + +class ChunkedReader: + def __init__(self) -> None: + self._bytes_in_chunk = 0 + # After reading a chunk, we have to throw away the trailing \r\n. + # This tracks the bytes that we need to match and throw away. + self._bytes_to_discard = b"" + self._reading_trailer = False + + def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]: + if self._reading_trailer: + lines = buf.maybe_extract_lines() + if lines is None: + return None + return EndOfMessage(headers=list(_decode_header_lines(lines))) + if self._bytes_to_discard: + data = buf.maybe_extract_at_most(len(self._bytes_to_discard)) + if data is None: + return None + if data != self._bytes_to_discard[: len(data)]: + raise LocalProtocolError( + f"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})" + ) + self._bytes_to_discard = self._bytes_to_discard[len(data) :] + if self._bytes_to_discard: + return None + # else, fall through and read some more + assert self._bytes_to_discard == b"" + if self._bytes_in_chunk == 0: + # We need to refill our chunk count + chunk_header = buf.maybe_extract_next_line() + if chunk_header is None: + return None + matches = validate( + chunk_header_re, + chunk_header, + "illegal chunk header: {!r}", + chunk_header, + ) + # XX FIXME: we discard chunk extensions. Does anyone care? + self._bytes_in_chunk = int(matches["chunk_size"], base=16) + if self._bytes_in_chunk == 0: + self._reading_trailer = True + return self(buf) + chunk_start = True + else: + chunk_start = False + assert self._bytes_in_chunk > 0 + data = buf.maybe_extract_at_most(self._bytes_in_chunk) + if data is None: + return None + self._bytes_in_chunk -= len(data) + if self._bytes_in_chunk == 0: + self._bytes_to_discard = b"\r\n" + chunk_end = True + else: + chunk_end = False + return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end) + + def read_eof(self) -> NoReturn: + raise RemoteProtocolError( + "peer closed connection without sending complete message body " + "(incomplete chunked read)" + ) + + +class Http10Reader: + def __call__(self, buf: ReceiveBuffer) -> Optional[Data]: + data = buf.maybe_extract_at_most(999999999) + if data is None: + return None + return Data(data=data) + + def read_eof(self) -> EndOfMessage: + return EndOfMessage() + + +def expect_nothing(buf: ReceiveBuffer) -> None: + if buf: + raise LocalProtocolError("Got data when expecting EOF") + return None + + +ReadersType = Dict[ + Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]], + Union[Callable[..., Any], Dict[str, Callable[..., Any]]], +] + +READERS: ReadersType = { + (CLIENT, IDLE): maybe_read_from_IDLE_client, + (SERVER, IDLE): maybe_read_from_SEND_RESPONSE_server, + (SERVER, SEND_RESPONSE): maybe_read_from_SEND_RESPONSE_server, + (CLIENT, DONE): expect_nothing, + (CLIENT, MUST_CLOSE): expect_nothing, + (CLIENT, CLOSED): expect_nothing, + (SERVER, DONE): expect_nothing, + (SERVER, MUST_CLOSE): expect_nothing, + (SERVER, CLOSED): expect_nothing, + SEND_BODY: { + "chunked": ChunkedReader, + "content-length": ContentLengthReader, + "http/1.0": Http10Reader, + }, +} diff --git a/python_embeded/Lib/site-packages/h11/_receivebuffer.py b/python_embeded/Lib/site-packages/h11/_receivebuffer.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c4e08a56f5081e87103f38b4add6ce1b730204 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_receivebuffer.py @@ -0,0 +1,153 @@ +import re +import sys +from typing import List, Optional, Union + +__all__ = ["ReceiveBuffer"] + + +# Operations we want to support: +# - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable), +# or wait until there is one +# - read at-most-N bytes +# Goals: +# - on average, do this fast +# - worst case, do this in O(n) where n is the number of bytes processed +# Plan: +# - store bytearray, offset, how far we've searched for a separator token +# - use the how-far-we've-searched data to avoid rescanning +# - while doing a stream of uninterrupted processing, advance offset instead +# of constantly copying +# WARNING: +# - I haven't benchmarked or profiled any of this yet. +# +# Note that starting in Python 3.4, deleting the initial n bytes from a +# bytearray is amortized O(n), thanks to some excellent work by Antoine +# Martin: +# +# https://bugs.python.org/issue19087 +# +# This means that if we only supported 3.4+, we could get rid of the code here +# involving self._start and self.compress, because it's doing exactly the same +# thing that bytearray now does internally. +# +# BUT unfortunately, we still support 2.7, and reading short segments out of a +# long buffer MUST be O(bytes read) to avoid DoS issues, so we can't actually +# delete this code. Yet: +# +# https://pythonclock.org/ +# +# (Two things to double-check first though: make sure PyPy also has the +# optimization, and benchmark to make sure it's a win, since we do have a +# slightly clever thing where we delay calling compress() until we've +# processed a whole event, which could in theory be slightly more efficient +# than the internal bytearray support.) +blank_line_regex = re.compile(b"\n\r?\n", re.MULTILINE) + + +class ReceiveBuffer: + def __init__(self) -> None: + self._data = bytearray() + self._next_line_search = 0 + self._multiple_lines_search = 0 + + def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer": + self._data += byteslike + return self + + def __bool__(self) -> bool: + return bool(len(self)) + + def __len__(self) -> int: + return len(self._data) + + # for @property unprocessed_data + def __bytes__(self) -> bytes: + return bytes(self._data) + + def _extract(self, count: int) -> bytearray: + # extracting an initial slice of the data buffer and return it + out = self._data[:count] + del self._data[:count] + + self._next_line_search = 0 + self._multiple_lines_search = 0 + + return out + + def maybe_extract_at_most(self, count: int) -> Optional[bytearray]: + """ + Extract a fixed number of bytes from the buffer. + """ + out = self._data[:count] + if not out: + return None + + return self._extract(count) + + def maybe_extract_next_line(self) -> Optional[bytearray]: + """ + Extract the first line, if it is completed in the buffer. + """ + # Only search in buffer space that we've not already looked at. + search_start_index = max(0, self._next_line_search - 1) + partial_idx = self._data.find(b"\r\n", search_start_index) + + if partial_idx == -1: + self._next_line_search = len(self._data) + return None + + # + 2 is to compensate len(b"\r\n") + idx = partial_idx + 2 + + return self._extract(idx) + + def maybe_extract_lines(self) -> Optional[List[bytearray]]: + """ + Extract everything up to the first blank line, and return a list of lines. + """ + # Handle the case where we have an immediate empty line. + if self._data[:1] == b"\n": + self._extract(1) + return [] + + if self._data[:2] == b"\r\n": + self._extract(2) + return [] + + # Only search in buffer space that we've not already looked at. + match = blank_line_regex.search(self._data, self._multiple_lines_search) + if match is None: + self._multiple_lines_search = max(0, len(self._data) - 2) + return None + + # Truncate the buffer and return it. + idx = match.span(0)[-1] + out = self._extract(idx) + lines = out.split(b"\n") + + for line in lines: + if line.endswith(b"\r"): + del line[-1] + + assert lines[-2] == lines[-1] == b"" + + del lines[-2:] + + return lines + + # In theory we should wait until `\r\n` before starting to validate + # incoming data. However it's interesting to detect (very) invalid data + # early given they might not even contain `\r\n` at all (hence only + # timeout will get rid of them). + # This is not a 100% effective detection but more of a cheap sanity check + # allowing for early abort in some useful cases. + # This is especially interesting when peer is messing up with HTTPS and + # sent us a TLS stream where we were expecting plain HTTP given all + # versions of TLS so far start handshake with a 0x16 message type code. + def is_next_line_obviously_invalid_request_line(self) -> bool: + try: + # HTTP header line must not contain non-printable characters + # and should not start with a space + return self._data[0] < 0x21 + except IndexError: + return False diff --git a/python_embeded/Lib/site-packages/h11/_state.py b/python_embeded/Lib/site-packages/h11/_state.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34 --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_state.py @@ -0,0 +1,365 @@ +################################################################ +# The core state machine +################################################################ +# +# Rule 1: everything that affects the state machine and state transitions must +# live here in this file. As much as possible goes into the table-based +# representation, but for the bits that don't quite fit, the actual code and +# state must nonetheless live here. +# +# Rule 2: this file does not know about what role we're playing; it only knows +# about HTTP request/response cycles in the abstract. This ensures that we +# don't cheat and apply different rules to local and remote parties. +# +# +# Theory of operation +# =================== +# +# Possibly the simplest way to think about this is that we actually have 5 +# different state machines here. Yes, 5. These are: +# +# 1) The client state, with its complicated automaton (see the docs) +# 2) The server state, with its complicated automaton (see the docs) +# 3) The keep-alive state, with possible states {True, False} +# 4) The SWITCH_CONNECT state, with possible states {False, True} +# 5) The SWITCH_UPGRADE state, with possible states {False, True} +# +# For (3)-(5), the first state listed is the initial state. +# +# (1)-(3) are stored explicitly in member variables. The last +# two are stored implicitly in the pending_switch_proposals set as: +# (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals) +# (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals) +# +# And each of these machines has two different kinds of transitions: +# +# a) Event-triggered +# b) State-triggered +# +# Event triggered is the obvious thing that you'd think it is: some event +# happens, and if it's the right event at the right time then a transition +# happens. But there are somewhat complicated rules for which machines can +# "see" which events. (As a rule of thumb, if a machine "sees" an event, this +# means two things: the event can affect the machine, and if the machine is +# not in a state where it expects that event then it's an error.) These rules +# are: +# +# 1) The client machine sees all h11.events objects emitted by the client. +# +# 2) The server machine sees all h11.events objects emitted by the server. +# +# It also sees the client's Request event. +# +# And sometimes, server events are annotated with a _SWITCH_* event. For +# example, we can have a (Response, _SWITCH_CONNECT) event, which is +# different from a regular Response event. +# +# 3) The keep-alive machine sees the process_keep_alive_disabled() event +# (which is derived from Request/Response events), and this event +# transitions it from True -> False, or from False -> False. There's no way +# to transition back. +# +# 4&5) The _SWITCH_* machines transition from False->True when we get a +# Request that proposes the relevant type of switch (via +# process_client_switch_proposals), and they go from True->False when we +# get a Response that has no _SWITCH_* annotation. +# +# So that's event-triggered transitions. +# +# State-triggered transitions are less standard. What they do here is couple +# the machines together. The way this works is, when certain *joint* +# configurations of states are achieved, then we automatically transition to a +# new *joint* state. So, for example, if we're ever in a joint state with +# +# client: DONE +# keep-alive: False +# +# then the client state immediately transitions to: +# +# client: MUST_CLOSE +# +# This is fundamentally different from an event-based transition, because it +# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state +# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive +# transitioned True -> False. Either way, once this precondition is satisfied, +# this transition is immediately triggered. +# +# What if two conflicting state-based transitions get enabled at the same +# time? In practice there's only one case where this arises (client DONE -> +# MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by +# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition. +# +# Implementation +# -------------- +# +# The event-triggered transitions for the server and client machines are all +# stored explicitly in a table. Ditto for the state-triggered transitions that +# involve just the server and client state. +# +# The transitions for the other machines, and the state-triggered transitions +# that involve the other machines, are written out as explicit Python code. +# +# It'd be nice if there were some cleaner way to do all this. This isn't +# *too* terrible, but I feel like it could probably be better. +# +# WARNING +# ------- +# +# The script that generates the state machine diagrams for the docs knows how +# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS +# tables. But it can't automatically read the transitions that are written +# directly in Python code. So if you touch those, you need to also update the +# script to keep it in sync! +from typing import cast, Dict, Optional, Set, Tuple, Type, Union + +from ._events import * +from ._util import LocalProtocolError, Sentinel + +# Everything in __all__ gets re-exported as part of the h11 public API. +__all__ = [ + "CLIENT", + "SERVER", + "IDLE", + "SEND_RESPONSE", + "SEND_BODY", + "DONE", + "MUST_CLOSE", + "CLOSED", + "MIGHT_SWITCH_PROTOCOL", + "SWITCHED_PROTOCOL", + "ERROR", +] + + +class CLIENT(Sentinel, metaclass=Sentinel): + pass + + +class SERVER(Sentinel, metaclass=Sentinel): + pass + + +# States +class IDLE(Sentinel, metaclass=Sentinel): + pass + + +class SEND_RESPONSE(Sentinel, metaclass=Sentinel): + pass + + +class SEND_BODY(Sentinel, metaclass=Sentinel): + pass + + +class DONE(Sentinel, metaclass=Sentinel): + pass + + +class MUST_CLOSE(Sentinel, metaclass=Sentinel): + pass + + +class CLOSED(Sentinel, metaclass=Sentinel): + pass + + +class ERROR(Sentinel, metaclass=Sentinel): + pass + + +# Switch types +class MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel): + pass + + +class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel): + pass + + +class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel): + pass + + +class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel): + pass + + +EventTransitionType = Dict[ + Type[Sentinel], + Dict[ + Type[Sentinel], + Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]], + ], +] + +EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = { + CLIENT: { + IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED}, + SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, + DONE: {ConnectionClosed: CLOSED}, + MUST_CLOSE: {ConnectionClosed: CLOSED}, + CLOSED: {ConnectionClosed: CLOSED}, + MIGHT_SWITCH_PROTOCOL: {}, + SWITCHED_PROTOCOL: {}, + ERROR: {}, + }, + SERVER: { + IDLE: { + ConnectionClosed: CLOSED, + Response: SEND_BODY, + # Special case: server sees client Request events, in this form + (Request, CLIENT): SEND_RESPONSE, + }, + SEND_RESPONSE: { + InformationalResponse: SEND_RESPONSE, + Response: SEND_BODY, + (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL, + (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL, + }, + SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE}, + DONE: {ConnectionClosed: CLOSED}, + MUST_CLOSE: {ConnectionClosed: CLOSED}, + CLOSED: {ConnectionClosed: CLOSED}, + SWITCHED_PROTOCOL: {}, + ERROR: {}, + }, +} + +StateTransitionType = Dict[ + Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]] +] + +# NB: there are also some special-case state-triggered transitions hard-coded +# into _fire_state_triggered_transitions below. +STATE_TRIGGERED_TRANSITIONS: StateTransitionType = { + # (Client state, Server state) -> new states + # Protocol negotiation + (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL}, + # Socket shutdown + (CLOSED, DONE): {SERVER: MUST_CLOSE}, + (CLOSED, IDLE): {SERVER: MUST_CLOSE}, + (ERROR, DONE): {SERVER: MUST_CLOSE}, + (DONE, CLOSED): {CLIENT: MUST_CLOSE}, + (IDLE, CLOSED): {CLIENT: MUST_CLOSE}, + (DONE, ERROR): {CLIENT: MUST_CLOSE}, +} + + +class ConnectionState: + def __init__(self) -> None: + # Extra bits of state that don't quite fit into the state model. + + # If this is False then it enables the automatic DONE -> MUST_CLOSE + # transition. Don't set this directly; call .keep_alive_disabled() + self.keep_alive = True + + # This is a subset of {UPGRADE, CONNECT}, containing the proposals + # made by the client for switching protocols. + self.pending_switch_proposals: Set[Type[Sentinel]] = set() + + self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE} + + def process_error(self, role: Type[Sentinel]) -> None: + self.states[role] = ERROR + self._fire_state_triggered_transitions() + + def process_keep_alive_disabled(self) -> None: + self.keep_alive = False + self._fire_state_triggered_transitions() + + def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None: + self.pending_switch_proposals.add(switch_event) + self._fire_state_triggered_transitions() + + def process_event( + self, + role: Type[Sentinel], + event_type: Type[Event], + server_switch_event: Optional[Type[Sentinel]] = None, + ) -> None: + _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type + if server_switch_event is not None: + assert role is SERVER + if server_switch_event not in self.pending_switch_proposals: + raise LocalProtocolError( + "Received server _SWITCH_UPGRADE event without a pending proposal" + ) + _event_type = (event_type, server_switch_event) + if server_switch_event is None and _event_type is Response: + self.pending_switch_proposals = set() + self._fire_event_triggered_transitions(role, _event_type) + # Special case: the server state does get to see Request + # events. + if _event_type is Request: + assert role is CLIENT + self._fire_event_triggered_transitions(SERVER, (Request, CLIENT)) + self._fire_state_triggered_transitions() + + def _fire_event_triggered_transitions( + self, + role: Type[Sentinel], + event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], + ) -> None: + state = self.states[role] + try: + new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type] + except KeyError: + event_type = cast(Type[Event], event_type) + raise LocalProtocolError( + "can't handle event type {} when role={} and state={}".format( + event_type.__name__, role, self.states[role] + ) + ) from None + self.states[role] = new_state + + def _fire_state_triggered_transitions(self) -> None: + # We apply these rules repeatedly until converging on a fixed point + while True: + start_states = dict(self.states) + + # It could happen that both these special-case transitions are + # enabled at the same time: + # + # DONE -> MIGHT_SWITCH_PROTOCOL + # DONE -> MUST_CLOSE + # + # For example, this will always be true of a HTTP/1.0 client + # requesting CONNECT. If this happens, the protocol switch takes + # priority. From there the client will either go to + # SWITCHED_PROTOCOL, in which case it's none of our business when + # they close the connection, or else the server will deny the + # request, in which case the client will go back to DONE and then + # from there to MUST_CLOSE. + if self.pending_switch_proposals: + if self.states[CLIENT] is DONE: + self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL + + if not self.pending_switch_proposals: + if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL: + self.states[CLIENT] = DONE + + if not self.keep_alive: + for role in (CLIENT, SERVER): + if self.states[role] is DONE: + self.states[role] = MUST_CLOSE + + # Tabular state-triggered transitions + joint_state = (self.states[CLIENT], self.states[SERVER]) + changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {}) + self.states.update(changes) + + if self.states == start_states: + # Fixed point reached + return + + def start_next_cycle(self) -> None: + if self.states != {CLIENT: DONE, SERVER: DONE}: + raise LocalProtocolError( + f"not in a reusable state. self.states={self.states}" + ) + # Can't reach DONE/DONE with any of these active, but still, let's be + # sure. + assert self.keep_alive + assert not self.pending_switch_proposals + self.states = {CLIENT: IDLE, SERVER: IDLE} diff --git a/python_embeded/Lib/site-packages/h11/_util.py b/python_embeded/Lib/site-packages/h11/_util.py new file mode 100644 index 0000000000000000000000000000000000000000..6718445290770e028ea2f1f662026c9a0b0991db --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_util.py @@ -0,0 +1,135 @@ +from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union + +__all__ = [ + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", + "validate", + "bytesify", +] + + +class ProtocolError(Exception): + """Exception indicating a violation of the HTTP/1.1 protocol. + + This as an abstract base class, with two concrete base classes: + :exc:`LocalProtocolError`, which indicates that you tried to do something + that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which + indicates that the remote peer tried to do something that HTTP/1.1 says is + illegal. See :ref:`error-handling` for details. + + In addition to the normal :exc:`Exception` features, it has one attribute: + + .. attribute:: error_status_hint + + This gives a suggestion as to what status code a server might use if + this error occurred as part of a request. + + For a :exc:`RemoteProtocolError`, this is useful as a suggestion for + how you might want to respond to a misbehaving peer, if you're + implementing a server. + + For a :exc:`LocalProtocolError`, this can be taken as a suggestion for + how your peer might have responded to *you* if h11 had allowed you to + continue. + + The default is 400 Bad Request, a generic catch-all for protocol + violations. + + """ + + def __init__(self, msg: str, error_status_hint: int = 400) -> None: + if type(self) is ProtocolError: + raise TypeError("tried to directly instantiate ProtocolError") + Exception.__init__(self, msg) + self.error_status_hint = error_status_hint + + +# Strategy: there are a number of public APIs where a LocalProtocolError can +# be raised (send(), all the different event constructors, ...), and only one +# public API where RemoteProtocolError can be raised +# (receive_data()). Therefore we always raise LocalProtocolError internally, +# and then receive_data will translate this into a RemoteProtocolError. +# +# Internally: +# LocalProtocolError is the generic "ProtocolError". +# Externally: +# LocalProtocolError is for local errors and RemoteProtocolError is for +# remote errors. +class LocalProtocolError(ProtocolError): + def _reraise_as_remote_protocol_error(self) -> NoReturn: + # After catching a LocalProtocolError, use this method to re-raise it + # as a RemoteProtocolError. This method must be called from inside an + # except: block. + # + # An easy way to get an equivalent RemoteProtocolError is just to + # modify 'self' in place. + self.__class__ = RemoteProtocolError # type: ignore + # But the re-raising is somewhat non-trivial -- you might think that + # now that we've modified the in-flight exception object, that just + # doing 'raise' to re-raise it would be enough. But it turns out that + # this doesn't work, because Python tracks the exception type + # (exc_info[0]) separately from the exception object (exc_info[1]), + # and we only modified the latter. So we really do need to re-raise + # the new type explicitly. + # On py3, the traceback is part of the exception object, so our + # in-place modification preserved it and we can just re-raise: + raise self + + +class RemoteProtocolError(ProtocolError): + pass + + +def validate( + regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any +) -> Dict[str, bytes]: + match = regex.fullmatch(data) + if not match: + if format_args: + msg = msg.format(*format_args) + raise LocalProtocolError(msg) + return match.groupdict() + + +# Sentinel values +# +# - Inherit identity-based comparison and hashing from object +# - Have a nice repr +# - Have a *bonus property*: type(sentinel) is sentinel +# +# The bonus property is useful if you want to take the return value from +# next_event() and do some sort of dispatch based on type(event). + +_T_Sentinel = TypeVar("_T_Sentinel", bound="Sentinel") + + +class Sentinel(type): + def __new__( + cls: Type[_T_Sentinel], + name: str, + bases: Tuple[type, ...], + namespace: Dict[str, Any], + **kwds: Any + ) -> _T_Sentinel: + assert bases == (Sentinel,) + v = super().__new__(cls, name, bases, namespace, **kwds) + v.__class__ = v # type: ignore + return v + + def __repr__(self) -> str: + return self.__name__ + + +# Used for methods, request targets, HTTP versions, header names, and header +# values. Accepts ascii-strings, or bytes/bytearray/memoryview/..., and always +# returns bytes. +def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes: + # Fast-path: + if type(s) is bytes: + return s + if isinstance(s, str): + s = s.encode("ascii") + if isinstance(s, int): + raise TypeError("expected bytes-like object, not int") + return bytes(s) diff --git a/python_embeded/Lib/site-packages/h11/_version.py b/python_embeded/Lib/site-packages/h11/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..76e7327b8617c9d12236f511414d5eb58e98a44b --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_version.py @@ -0,0 +1,16 @@ +# This file must be kept very simple, because it is consumed from several +# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc. + +# We use a simple scheme: +# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev +# where the +dev versions are never released into the wild, they're just what +# we stick into the VCS in between releases. +# +# This is compatible with PEP 440: +# http://legacy.python.org/dev/peps/pep-0440/ +# via the use of the "local suffix" "+dev", which is disallowed on index +# servers and causes 1.0.0+dev to sort after plain 1.0.0, which is what we +# want. (Contrast with the special suffix 1.0.0.dev, which sorts *before* +# 1.0.0.) + +__version__ = "0.16.0" diff --git a/python_embeded/Lib/site-packages/h11/_writers.py b/python_embeded/Lib/site-packages/h11/_writers.py new file mode 100644 index 0000000000000000000000000000000000000000..939cdb912a9debaea07fbf3a9ac04549c44d077c --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/_writers.py @@ -0,0 +1,145 @@ +# Code to read HTTP data +# +# Strategy: each writer takes an event + a write-some-bytes function, which is +# calls. +# +# WRITERS is a dict describing how to pick a reader. It maps states to either: +# - a writer +# - or, for body writers, a dict of framin-dependent writer factories + +from typing import Any, Callable, Dict, List, Tuple, Type, Union + +from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Response +from ._headers import Headers +from ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVER +from ._util import LocalProtocolError, Sentinel + +__all__ = ["WRITERS"] + +Writer = Callable[[bytes], Any] + + +def write_headers(headers: Headers, write: Writer) -> None: + # "Since the Host field-value is critical information for handling a + # request, a user agent SHOULD generate Host as the first header field + # following the request-line." - RFC 7230 + raw_items = headers._full_items + for raw_name, name, value in raw_items: + if name == b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + for raw_name, name, value in raw_items: + if name != b"host": + write(b"%s: %s\r\n" % (raw_name, value)) + write(b"\r\n") + + +def write_request(request: Request, write: Writer) -> None: + if request.http_version != b"1.1": + raise LocalProtocolError("I only send HTTP/1.1") + write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target)) + write_headers(request.headers, write) + + +# Shared between InformationalResponse and Response +def write_any_response( + response: Union[InformationalResponse, Response], write: Writer +) -> None: + if response.http_version != b"1.1": + raise LocalProtocolError("I only send HTTP/1.1") + status_bytes = str(response.status_code).encode("ascii") + # We don't bother sending ascii status messages like "OK"; they're + # optional and ignored by the protocol. (But the space after the numeric + # status code is mandatory.) + # + # XX FIXME: could at least make an effort to pull out the status message + # from stdlib's http.HTTPStatus table. Or maybe just steal their enums + # (either by import or copy/paste). We already accept them as status codes + # since they're of type IntEnum < int. + write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason)) + write_headers(response.headers, write) + + +class BodyWriter: + def __call__(self, event: Event, write: Writer) -> None: + if type(event) is Data: + self.send_data(event.data, write) + elif type(event) is EndOfMessage: + self.send_eom(event.headers, write) + else: # pragma: no cover + assert False + + def send_data(self, data: bytes, write: Writer) -> None: + pass + + def send_eom(self, headers: Headers, write: Writer) -> None: + pass + + +# +# These are all careful not to do anything to 'data' except call len(data) and +# write(data). This allows us to transparently pass-through funny objects, +# like placeholder objects referring to files on disk that will be sent via +# sendfile(2). +# +class ContentLengthWriter(BodyWriter): + def __init__(self, length: int) -> None: + self._length = length + + def send_data(self, data: bytes, write: Writer) -> None: + self._length -= len(data) + if self._length < 0: + raise LocalProtocolError("Too much data for declared Content-Length") + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: + if self._length != 0: + raise LocalProtocolError("Too little data for declared Content-Length") + if headers: + raise LocalProtocolError("Content-Length and trailers don't mix") + + +class ChunkedWriter(BodyWriter): + def send_data(self, data: bytes, write: Writer) -> None: + # if we encoded 0-length data in the naive way, it would look like an + # end-of-message. + if not data: + return + write(b"%x\r\n" % len(data)) + write(data) + write(b"\r\n") + + def send_eom(self, headers: Headers, write: Writer) -> None: + write(b"0\r\n") + write_headers(headers, write) + + +class Http10Writer(BodyWriter): + def send_data(self, data: bytes, write: Writer) -> None: + write(data) + + def send_eom(self, headers: Headers, write: Writer) -> None: + if headers: + raise LocalProtocolError("can't send trailers to HTTP/1.0 client") + # no need to close the socket ourselves, that will be taken care of by + # Connection: close machinery + + +WritersType = Dict[ + Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]], + Union[ + Dict[str, Type[BodyWriter]], + Callable[[Union[InformationalResponse, Response], Writer], None], + Callable[[Request, Writer], None], + ], +] + +WRITERS: WritersType = { + (CLIENT, IDLE): write_request, + (SERVER, IDLE): write_any_response, + (SERVER, SEND_RESPONSE): write_any_response, + SEND_BODY: { + "chunked": ChunkedWriter, + "content-length": ContentLengthWriter, + "http/1.0": Http10Writer, + }, +} diff --git a/python_embeded/Lib/site-packages/h11/py.typed b/python_embeded/Lib/site-packages/h11/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..f5642f79f21d872f010979dcf6f0c4a415acc19d --- /dev/null +++ b/python_embeded/Lib/site-packages/h11/py.typed @@ -0,0 +1 @@ +Marker diff --git a/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8056834e6714b089ef49847820064a1ae4b041fd --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA @@ -0,0 +1,625 @@ +Metadata-Version: 2.4 +Name: httpcore +Version: 1.0.9 +Summary: A minimal low-level HTTP client. +Project-URL: Documentation, https://www.encode.io/httpcore +Project-URL: Homepage, https://www.encode.io/httpcore/ +Project-URL: Source, https://github.com/encode/httpcore +Author-email: Tom Christie +License-Expression: BSD-3-Clause +License-File: LICENSE.md +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: certifi +Requires-Dist: h11>=0.16 +Provides-Extra: asyncio +Requires-Dist: anyio<5.0,>=4.0; extra == 'asyncio' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: trio +Requires-Dist: trio<1.0,>=0.22.0; extra == 'trio' +Description-Content-Type: text/markdown + +# HTTP Core + +[![Test Suite](https://github.com/encode/httpcore/workflows/Test%20Suite/badge.svg)](https://github.com/encode/httpcore/actions) +[![Package version](https://badge.fury.io/py/httpcore.svg)](https://pypi.org/project/httpcore/) + +> *Do one thing, and do it well.* + +The HTTP Core package provides a minimal low-level HTTP client, which does +one thing only. Sending HTTP requests. + +It does not provide any high level model abstractions over the API, +does not handle redirects, multipart uploads, building authentication headers, +transparent HTTP caching, URL parsing, session cookie handling, +content or charset decoding, handling JSON, environment based configuration +defaults, or any of that Jazz. + +Some things HTTP Core does do: + +* Sending HTTP requests. +* Thread-safe / task-safe connection pooling. +* HTTP(S) proxy & SOCKS proxy support. +* Supports HTTP/1.1 and HTTP/2. +* Provides both sync and async interfaces. +* Async backend support for `asyncio` and `trio`. + +## Requirements + +Python 3.8+ + +## Installation + +For HTTP/1.1 only support, install with: + +```shell +$ pip install httpcore +``` + +There are also a number of optional extras available... + +```shell +$ pip install httpcore['asyncio,trio,http2,socks'] +``` + +## Sending requests + +Send an HTTP request: + +```python +import httpcore + +response = httpcore.request("GET", "https://www.example.com/") + +print(response) +# +print(response.status) +# 200 +print(response.headers) +# [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...] +print(response.content) +# b'\n\n\nExample Domain\n\n\n ...' +``` + +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. + +```python +import httpcore + +http = httpcore.ConnectionPool() +response = http.request("GET", "https://www.example.com/") +``` + +Once you're ready to get going, [head over to the documentation](https://www.encode.io/httpcore/). + +## Motivation + +You *probably* don't want to be using HTTP Core directly. It might make sense if +you're writing something like a proxy service in Python, and you just want +something at the lowest possible level, but more typically you'll want to use +a higher level client library, such as `httpx`. + +The motivation for `httpcore` is: + +* To provide a reusable low-level client library, that other packages can then build on top of. +* To provide a *really clear interface split* between the networking code and client logic, + so that each is easier to understand and reason about in isolation. + +## Dependencies + +The `httpcore` package has the following dependencies... + +* `h11` +* `certifi` + +And the following optional extras... + +* `anyio` - Required by `pip install httpcore['asyncio']`. +* `trio` - Required by `pip install httpcore['trio']`. +* `h2` - Required by `pip install httpcore['http2']`. +* `socksio` - Required by `pip install httpcore['socks']`. + +## Versioning + +We use [SEMVER for our versioning policy](https://semver.org/). + +For changes between package versions please see our [project changelog](CHANGELOG.md). + +We recommend pinning your requirements either the most current major version, or a more specific version range: + +```python +pip install 'httpcore==1.*' +``` +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## Version 1.0.9 (April 24th, 2025) + +- Resolve https://github.com/advisories/GHSA-vqfr-h8mv-ghfj with h11 dependency update. (#1008) + +## Version 1.0.8 (April 11th, 2025) + +- Fix `AttributeError` when importing on Python 3.14. (#1005) + +## Version 1.0.7 (November 15th, 2024) + +- Support `proxy=…` configuration on `ConnectionPool()`. (#974) + +## Version 1.0.6 (October 1st, 2024) + +- Relax `trio` dependency pinning. (#956) +- Handle `trio` raising `NotImplementedError` on unsupported platforms. (#955) +- Handle mapping `ssl.SSLError` to `httpcore.ConnectError`. (#918) + +## 1.0.5 (March 27th, 2024) + +- Handle `EndOfStream` exception for anyio backend. (#899) +- Allow trio `0.25.*` series in package dependancies. (#903) + +## 1.0.4 (February 21st, 2024) + +- Add `target` request extension. (#888) +- Fix support for connection `Upgrade` and `CONNECT` when some data in the stream has been read. (#882) + +## 1.0.3 (February 13th, 2024) + +- Fix support for async cancellations. (#880) +- Fix trace extension when used with socks proxy. (#849) +- Fix SSL context for connections using the "wss" scheme (#869) + +## 1.0.2 (November 10th, 2023) + +- Fix `float("inf")` timeouts in `Event.wait` function. (#846) + +## 1.0.1 (November 3rd, 2023) + +- Fix pool timeout to account for the total time spent retrying. (#823) +- Raise a neater RuntimeError when the correct async deps are not installed. (#826) +- Add support for synchronous TLS-in-TLS streams. (#840) + +## 1.0.0 (October 6th, 2023) + +From version 1.0 our async support is now optional, as the package has minimal dependencies by default. + +For async support use either `pip install 'httpcore[asyncio]'` or `pip install 'httpcore[trio]'`. + +The project versioning policy is now explicitly governed by SEMVER. See https://semver.org/. + +- Async support becomes fully optional. (#809) +- Add support for Python 3.12. (#807) + +## 0.18.0 (September 8th, 2023) + +- Add support for HTTPS proxies. (#745, #786) +- Drop Python 3.7 support. (#727) +- Handle `sni_hostname` extension with SOCKS proxy. (#774) +- Handle HTTP/1.1 half-closed connections gracefully. (#641) +- Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#762) + +## 0.17.3 (July 5th, 2023) + +- Support async cancellations, ensuring that the connection pool is left in a clean state when cancellations occur. (#726) +- 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) +- Graceful handling of HTTP/2 GoAway frames, with requests being transparently retried on a new connection. (#730) +- 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) +- Drop Python 3.7 support. (#727) + +## 0.17.2 (May 23th, 2023) + +- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668) +- Improve logging with per-module logger names. (#690) +- Add `sni_hostname` request extension. (#696) +- Resolve race condition during import of `anyio` package. (#692) +- Enable TCP_NODELAY for all synchronous sockets. (#651) + +## 0.17.1 (May 17th, 2023) + +- If 'retries' is set, then allow retries if an SSL handshake error occurs. (#669) +- Improve correctness of tracebacks on network exceptions, by raising properly chained exceptions. (#678) +- Prevent connection-hanging behaviour when HTTP/2 connections are closed by a server-sent 'GoAway' frame. (#679) +- Fix edge-case exception when removing requests from the connection pool. (#680) +- Fix pool timeout edge-case. (#688) + +## 0.17.0 (March 16th, 2023) + +- Add DEBUG level logging. (#648) +- Respect HTTP/2 max concurrent streams when settings updates are sent by server. (#652) +- Increase the allowable HTTP header size to 100kB. (#647) +- Add `retries` option to SOCKS proxy classes. (#643) + +## 0.16.3 (December 20th, 2022) + +- Allow `ws` and `wss` schemes. Allows us to properly support websocket upgrade connections. (#625) +- Forwarding HTTP proxies use a connection-per-remote-host. Required by some proxy implementations. (#637) +- Don't raise `RuntimeError` when closing a connection pool with active connections. Removes some error cases when cancellations are used. (#631) +- Lazy import `anyio`, so that it's no longer a hard dependancy, and isn't imported if unused. (#639) + +## 0.16.2 (November 25th, 2022) + +- Revert 'Fix async cancellation behaviour', which introduced race conditions. (#627) +- Raise `RuntimeError` if attempting to us UNIX domain sockets on Windows. (#619) + +## 0.16.1 (November 17th, 2022) + +- Fix HTTP/1.1 interim informational responses, such as "100 Continue". (#605) + +## 0.16.0 (October 11th, 2022) + +- Support HTTP/1.1 informational responses. (#581) +- Fix async cancellation behaviour. (#580) +- Support `h11` 0.14. (#579) + +## 0.15.0 (May 17th, 2022) + +- Drop Python 3.6 support (#535) +- Ensure HTTP proxy CONNECT requests include `timeout` configuration. (#506) +- Switch to explicit `typing.Optional` for type hints. (#513) +- For `trio` map OSError exceptions to `ConnectError`. (#543) + +## 0.14.7 (February 4th, 2022) + +- Requests which raise a PoolTimeout need to be removed from the pool queue. (#502) +- Fix AttributeError that happened when Socks5Connection were terminated. (#501) + +## 0.14.6 (February 1st, 2022) + +- Fix SOCKS support for `http://` URLs. (#492) +- Resolve race condition around exceptions during streaming a response. (#491) + +## 0.14.5 (January 18th, 2022) + +- SOCKS proxy support. (#478) +- Add proxy_auth argument to HTTPProxy. (#481) +- Improve error message on 'RemoteProtocolError' exception when server disconnects without sending a response. (#479) + +## 0.14.4 (January 5th, 2022) + +- Support HTTP/2 on HTTPS tunnelling proxies. (#468) +- Fix proxy headers missing on HTTP forwarding. (#456) +- Only instantiate SSL context if required. (#457) +- More robust HTTP/2 handling. (#253, #439, #440, #441) + +## 0.14.3 (November 17th, 2021) + +- Fix race condition when removing closed connections from the pool. (#437) + +## 0.14.2 (November 16th, 2021) + +- Failed connections no longer remain in the pool. (Pull #433) + +## 0.14.1 (November 12th, 2021) + +- `max_connections` becomes optional. (Pull #429) +- `certifi` is now included in the install dependancies. (Pull #428) +- `h2` is now strictly optional. (Pull #428) + +## 0.14.0 (November 11th, 2021) + +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. + +Some of the lower-level API design also makes the components more easily testable in isolation, and the package now has 100% test coverage. + +See [discussion #419](https://github.com/encode/httpcore/discussions/419) for a little more background. + +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... + +* Log the point at which the connection is established, and the IP/port on which it is made. +* 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.) +* Log SSL version info / certificate info. + +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. + +## 0.13.7 (September 13th, 2021) + +- Fix broken error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #403) + +## 0.13.6 (June 15th, 2021) + +### Fixed + +- Close sockets when read or write timeouts occur. (Pull #365) + +## 0.13.5 (June 14th, 2021) + +### Fixed + +- Resolved niggles with AnyIO EOF behaviours. (Pull #358, #362) + +## 0.13.4 (June 9th, 2021) + +### Added + +- Improved error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #354) + +### Fixed + +- 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). + +## 0.13.3 (May 6th, 2021) + +### Added + +- Support HTTP/2 prior knowledge, using `httpcore.SyncConnectionPool(http1=False)`. (Pull #333) + +### Fixed + +- Handle cases where environment does not provide `select.poll` support. (Pull #331) + +## 0.13.2 (April 29th, 2021) + +### Added + +- Improve error message for specific case of `RemoteProtocolError` where server disconnects without sending a response. (Pull #313) + +## 0.13.1 (April 28th, 2021) + +### Fixed + +- More resiliant testing for closed connections. (Pull #311) +- Don't raise exceptions on ungraceful connection closes. (Pull #310) + +## 0.13.0 (April 21st, 2021) + +The 0.13 release updates the core API in order to match the HTTPX Transport API, +introduced in HTTPX 0.18 onwards. + +An example of making requests with the new interface is: + +```python +with httpcore.SyncConnectionPool() as http: + status_code, headers, stream, extensions = http.handle_request( + method=b'GET', + url=(b'https', b'example.org', 443, b'/'), + headers=[(b'host', b'example.org'), (b'user-agent', b'httpcore')] + stream=httpcore.ByteStream(b''), + extensions={} + ) + body = stream.read() + print(status_code, body) +``` + +### Changed + +- The `.request()` method is now `handle_request()`. (Pull #296) +- The `.arequest()` method is now `.handle_async_request()`. (Pull #296) +- The `headers` argument is no longer optional. (Pull #296) +- The `stream` argument is no longer optional. (Pull #296) +- The `ext` argument is now named `extensions`, and is no longer optional. (Pull #296) +- The `"reason"` extension keyword is now named `"reason_phrase"`. (Pull #296) +- The `"reason_phrase"` and `"http_version"` extensions now use byte strings for their values. (Pull #296) +- The `httpcore.PlainByteStream()` class becomes `httpcore.ByteStream()`. (Pull #296) + +### Added + +- Streams now support a `.read()` interface. (Pull #296) + +### Fixed + +- Task cancellation no longer leaks connections from the connection pool. (Pull #305) + +## 0.12.3 (December 7th, 2020) + +### Fixed + +- Abort SSL connections on close rather than waiting for remote EOF when using `asyncio`. (Pull #167) +- Fix exception raised in case of connect timeouts when using the `anyio` backend. (Pull #236) +- Fix `Host` header precedence for `:authority` in HTTP/2. (Pull #241, #243) +- Handle extra edge case when detecting for socket readability when using `asyncio`. (Pull #242, #244) +- Fix `asyncio` SSL warning when using proxy tunneling. (Pull #249) + +## 0.12.2 (November 20th, 2020) + +### Fixed + +- Properly wrap connect errors on the asyncio backend. (Pull #235) +- Fix `ImportError` occurring on Python 3.9 when using the HTTP/1.1 sync client in a multithreaded context. (Pull #237) + +## 0.12.1 (November 7th, 2020) + +### Added + +- Add connect retries. (Pull #221) + +### Fixed + +- Tweak detection of dropped connections, resolving an issue with open files limits on Linux. (Pull #185) +- Avoid leaking connections when establishing an HTTP tunnel to a proxy has failed. (Pull #223) +- Properly wrap OS errors when using `trio`. (Pull #225) + +## 0.12.0 (October 6th, 2020) + +### Changed + +- HTTP header casing is now preserved, rather than always sent in lowercase. (#216 and python-hyper/h11#104) + +### Added + +- Add Python 3.9 to officially supported versions. + +### Fixed + +- Gracefully handle a stdlib asyncio bug when a connection is closed while it is in a paused-for-reading state. (#201) + +## 0.11.1 (September 28nd, 2020) + +### Fixed + +- Add await to async semaphore release() coroutine (#197) +- Drop incorrect curio classifier (#192) + +## 0.11.0 (September 22nd, 2020) + +The Transport API with 0.11.0 has a couple of significant changes. + +Firstly we've moved changed the request interface in order to allow extensions, which will later enable us to support features +such as trailing headers, HTTP/2 server push, and CONNECT/Upgrade connections. + +The interface changes from: + +```python +def request(method, url, headers, stream, timeout): + return (http_version, status_code, reason, headers, stream) +``` + +To instead including an optional dictionary of extensions on the request and response: + +```python +def request(method, url, headers, stream, ext): + return (status_code, headers, stream, ext) +``` + +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. + +In particular: + +* Trailing headers support. +* HTTP/2 Server Push +* sendfile. +* Exposing raw connection on CONNECT, Upgrade, HTTP/2 bi-di streaming. +* Exposing debug information out of the API, including template name, template context. + +Currently extensions are limited to: + +* request: `timeout` - Optional. Timeout dictionary. +* response: `http_version` - Optional. Include the HTTP version used on the response. +* response: `reason` - Optional. Include the reason phrase used on the response. Only valid with HTTP/1.*. + +See https://github.com/encode/httpx/issues/1274#issuecomment-694884553 for the history behind this. + +Secondly, the async version of `request` is now namespaced as `arequest`. + +This allows concrete transports to support both sync and async implementations on the same class. + +### Added + +- Add curio support. (Pull #168) +- Add anyio support, with `backend="anyio"`. (Pull #169) + +### Changed + +- Update the Transport API to use 'ext' for optional extensions. (Pull #190) +- Update the Transport API to use `.request` and `.arequest` so implementations can support both sync and async. (Pull #189) + +## 0.10.2 (August 20th, 2020) + +### Added + +- Added Unix Domain Socket support. (Pull #139) + +### Fixed + +- Always include the port on proxy CONNECT requests. (Pull #154) +- Fix `max_keepalive_connections` configuration. (Pull #153) +- Fixes behaviour in HTTP/1.1 where server disconnects can be used to signal the end of the response body. (Pull #164) + +## 0.10.1 (August 7th, 2020) + +- Include `max_keepalive_connections` on `AsyncHTTPProxy`/`SyncHTTPProxy` classes. + +## 0.10.0 (August 7th, 2020) + +The most notable change in the 0.10.0 release is that HTTP/2 support is now fully optional. + +Use either `pip install httpcore` for HTTP/1.1 support only, or `pip install httpcore[http2]` for HTTP/1.1 and HTTP/2 support. + +### Added + +- HTTP/2 support becomes optional. (Pull #121, #130) +- Add `local_address=...` support. (Pull #100, #134) +- Add `PlainByteStream`, `IteratorByteStream`, `AsyncIteratorByteStream`. The `AsyncByteSteam` and `SyncByteStream` classes are now pure interface classes. (#133) +- Add `LocalProtocolError`, `RemoteProtocolError` exceptions. (Pull #129) +- Add `UnsupportedProtocol` exception. (Pull #128) +- Add `.get_connection_info()` method. (Pull #102, #137) +- Add better TRACE logs. (Pull #101) + +### Changed + +- `max_keepalive` is deprecated in favour of `max_keepalive_connections`. (Pull #140) + +### Fixed + +- Improve handling of server disconnects. (Pull #112) + +## 0.9.1 (May 27th, 2020) + +### Fixed + +- Proper host resolution for sync case, including IPv6 support. (Pull #97) +- Close outstanding connections when connection pool is closed. (Pull #98) + +## 0.9.0 (May 21th, 2020) + +### Changed + +- URL port becomes an `Optional[int]` instead of `int`. (Pull #92) + +### Fixed + +- Honor HTTP/2 max concurrent streams settings. (Pull #89, #90) +- Remove incorrect debug log. (Pull #83) + +## 0.8.4 (May 11th, 2020) + +### Added + +- Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables +and TRACE level logging. (Pull #79) + +### Fixed + +- Reuse of connections on HTTP/2 in close concurrency situations. (Pull #81) + +## 0.8.3 (May 6rd, 2020) + +### Fixed + +- Include `Host` and `Accept` headers on proxy "CONNECT" requests. +- De-duplicate any headers also contained in proxy_headers. +- HTTP/2 flag not being passed down to proxy connections. + +## 0.8.2 (May 3rd, 2020) + +### Fixed + +- Fix connections using proxy forwarding requests not being added to the +connection pool properly. (Pull #70) + +## 0.8.1 (April 30th, 2020) + +### Changed + +- Allow inherintance of both `httpcore.AsyncByteStream`, `httpcore.SyncByteStream` without type conflicts. + +## 0.8.0 (April 30th, 2020) + +### Fixed + +- Fixed tunnel proxy support. + +### Added + +- New `TimeoutException` base class. + +## 0.7.0 (March 5th, 2020) + +- First integration with HTTPX. diff --git a/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..44d4769e791312e8572bc5c24ed2efdc86819835 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD @@ -0,0 +1,68 @@ +httpcore-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpcore-1.0.9.dist-info/METADATA,sha256=_i1P2mGZEol4d54M8n88BFxTGGP83Zh-rMdPOhjUHCE,21529 +httpcore-1.0.9.dist-info/RECORD,, +httpcore-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +httpcore-1.0.9.dist-info/licenses/LICENSE.md,sha256=_ctZFUx0y6uhahEkL3dAvqnyPW_rVUeRfYxflKgDkqU,1518 +httpcore/__init__.py,sha256=9kT_kqChCCJUTHww24ZmR_ezcdbpRYWksD-gYNzkZP8,3445 +httpcore/__pycache__/__init__.cpython-312.pyc,, +httpcore/__pycache__/_api.cpython-312.pyc,, +httpcore/__pycache__/_exceptions.cpython-312.pyc,, +httpcore/__pycache__/_models.cpython-312.pyc,, +httpcore/__pycache__/_ssl.cpython-312.pyc,, +httpcore/__pycache__/_synchronization.cpython-312.pyc,, +httpcore/__pycache__/_trace.cpython-312.pyc,, +httpcore/__pycache__/_utils.cpython-312.pyc,, +httpcore/_api.py,sha256=unZmeDschBWCGCPCwkS3Wot9euK6bg_kKxLtGTxw214,3146 +httpcore/_async/__init__.py,sha256=EWdl2v4thnAHzJpqjU4h2a8DUiGAvNiWrkii9pfhTf0,1221 +httpcore/_async/__pycache__/__init__.cpython-312.pyc,, +httpcore/_async/__pycache__/connection.cpython-312.pyc,, +httpcore/_async/__pycache__/connection_pool.cpython-312.pyc,, +httpcore/_async/__pycache__/http11.cpython-312.pyc,, +httpcore/_async/__pycache__/http2.cpython-312.pyc,, +httpcore/_async/__pycache__/http_proxy.cpython-312.pyc,, +httpcore/_async/__pycache__/interfaces.cpython-312.pyc,, +httpcore/_async/__pycache__/socks_proxy.cpython-312.pyc,, +httpcore/_async/connection.py,sha256=6OcPXqMEfc0BU38_-iHUNDd1vKSTc2UVT09XqNb_BOk,8449 +httpcore/_async/connection_pool.py,sha256=DOIQ2s2ZCf9qfwxhzMprTPLqCL8OxGXiKF6qRHxvVyY,17307 +httpcore/_async/http11.py,sha256=-qM9bV7PjSQF5vxs37-eUXOIFwbIjPcZbNliuX9TtBw,13880 +httpcore/_async/http2.py,sha256=azX1fcmtXaIwjputFlZ4vd92J8xwjGOa9ax9QIv4394,23936 +httpcore/_async/http_proxy.py,sha256=2zVkrlv-Ds-rWGaqaXlrhEJiAQFPo23BT3Gq_sWoBXU,14701 +httpcore/_async/interfaces.py,sha256=jTiaWL83pgpGC9ziv90ZfwaKNMmHwmOalzaKiuTxATo,4455 +httpcore/_async/socks_proxy.py,sha256=lLKgLlggPfhFlqi0ODeBkOWvt9CghBBUyqsnsU1tx6Q,13841 +httpcore/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +httpcore/_backends/__pycache__/__init__.cpython-312.pyc,, +httpcore/_backends/__pycache__/anyio.cpython-312.pyc,, +httpcore/_backends/__pycache__/auto.cpython-312.pyc,, +httpcore/_backends/__pycache__/base.cpython-312.pyc,, +httpcore/_backends/__pycache__/mock.cpython-312.pyc,, +httpcore/_backends/__pycache__/sync.cpython-312.pyc,, +httpcore/_backends/__pycache__/trio.cpython-312.pyc,, +httpcore/_backends/anyio.py,sha256=x8PgEhXRC8bVqsdzk_YJx8Y6d9Tub06CuUSwnbmtqoY,5252 +httpcore/_backends/auto.py,sha256=zO136PKZmsaTDK-HRk84eA-MUg8_2wJf4NvmK432Aio,1662 +httpcore/_backends/base.py,sha256=aShgRdZnMmRhFWHetjumlM73f8Kz1YOAyCUP_4kHslA,3042 +httpcore/_backends/mock.py,sha256=er9T436uSe7NLrfiLa4x6Nuqg5ivQ693CxWYCWsgbH4,4077 +httpcore/_backends/sync.py,sha256=bhE4d9iK9Umxdsdsgm2EfKnXaBms2WggGYU-7jmUujU,7977 +httpcore/_backends/trio.py,sha256=LHu4_Mr5MswQmmT3yE4oLgf9b_JJfeVS4BjDxeJc7Ro,5996 +httpcore/_exceptions.py,sha256=looCKga3_YVYu3s-d3L9RMPRJyhsY7fiuuGxvkOD0c0,1184 +httpcore/_models.py,sha256=IO2CcXcdpovRcLTdGFGB6RyBZdEm2h_TOmoCc4rEKho,17623 +httpcore/_ssl.py,sha256=srqmSNU4iOUvWF-SrJvb8G_YEbHFELOXQOwdDIBTS9c,187 +httpcore/_sync/__init__.py,sha256=JBDIgXt5la1LCJ1sLQeKhjKFpLnpNr8Svs6z2ni3fgg,1141 +httpcore/_sync/__pycache__/__init__.cpython-312.pyc,, +httpcore/_sync/__pycache__/connection.cpython-312.pyc,, +httpcore/_sync/__pycache__/connection_pool.cpython-312.pyc,, +httpcore/_sync/__pycache__/http11.cpython-312.pyc,, +httpcore/_sync/__pycache__/http2.cpython-312.pyc,, +httpcore/_sync/__pycache__/http_proxy.cpython-312.pyc,, +httpcore/_sync/__pycache__/interfaces.cpython-312.pyc,, +httpcore/_sync/__pycache__/socks_proxy.cpython-312.pyc,, +httpcore/_sync/connection.py,sha256=9exGOb3PB-Mp2T1-sckSeL2t-tJ_9-NXomV8ihmWCgU,8238 +httpcore/_sync/connection_pool.py,sha256=a-T8LTsUxc7r0Ww1atfHSDoWPjQ0fA8Ul7S3-F0Mj70,16955 +httpcore/_sync/http11.py,sha256=IFobD1Md5JFlJGKWnh1_Q3epikUryI8qo09v8MiJIEA,13476 +httpcore/_sync/http2.py,sha256=AxU4yhcq68Bn5vqdJYtiXKYUj7nvhYbxz3v4rT4xnvA,23400 +httpcore/_sync/http_proxy.py,sha256=_al_6crKuEZu2wyvu493RZImJdBJnj5oGKNjLOJL2Zo,14463 +httpcore/_sync/interfaces.py,sha256=snXON42vUDHO5JBJvo8D4VWk2Wat44z2OXXHDrjbl94,4344 +httpcore/_sync/socks_proxy.py,sha256=zegZW9Snqj2_992DFJa8_CppOVBkVL4AgwduRkStakQ,13614 +httpcore/_synchronization.py,sha256=zSi13mAColBnknjZBknUC6hKNDQT4C6ijnezZ-r0T2s,9434 +httpcore/_trace.py,sha256=ck6ZoIzYTkdNAIfq5MGeKqBXDtqjOX-qfYwmZFbrGco,3952 +httpcore/_utils.py,sha256=_RLgXYOAYC350ikALV59GZ68IJrdocRZxPs9PjmzdFY,1537 +httpcore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/python_embeded/Lib/site-packages/httpcore/__init__.py b/python_embeded/Lib/site-packages/httpcore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a92dc4a440bdf6f259ec1083c89c817eb7b631b --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/__init__.py @@ -0,0 +1,141 @@ +from ._api import request, stream +from ._async import ( + AsyncConnectionInterface, + AsyncConnectionPool, + AsyncHTTP2Connection, + AsyncHTTP11Connection, + AsyncHTTPConnection, + AsyncHTTPProxy, + AsyncSOCKSProxy, +) +from ._backends.base import ( + SOCKET_OPTION, + AsyncNetworkBackend, + AsyncNetworkStream, + NetworkBackend, + NetworkStream, +) +from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStream +from ._backends.sync import SyncBackend +from ._exceptions import ( + ConnectError, + ConnectionNotAvailable, + ConnectTimeout, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + TimeoutException, + UnsupportedProtocol, + WriteError, + WriteTimeout, +) +from ._models import URL, Origin, Proxy, Request, Response +from ._ssl import default_ssl_context +from ._sync import ( + ConnectionInterface, + ConnectionPool, + HTTP2Connection, + HTTP11Connection, + HTTPConnection, + HTTPProxy, + SOCKSProxy, +) + +# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed. +try: + from ._backends.anyio import AnyIOBackend +except ImportError: # pragma: nocover + + class AnyIOBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = ( + "Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed." + ) + raise RuntimeError(msg) + + +# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed. +try: + from ._backends.trio import TrioBackend +except ImportError: # pragma: nocover + + class TrioBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed." + raise RuntimeError(msg) + + +__all__ = [ + # top-level requests + "request", + "stream", + # models + "Origin", + "URL", + "Request", + "Response", + "Proxy", + # async + "AsyncHTTPConnection", + "AsyncConnectionPool", + "AsyncHTTPProxy", + "AsyncHTTP11Connection", + "AsyncHTTP2Connection", + "AsyncConnectionInterface", + "AsyncSOCKSProxy", + # sync + "HTTPConnection", + "ConnectionPool", + "HTTPProxy", + "HTTP11Connection", + "HTTP2Connection", + "ConnectionInterface", + "SOCKSProxy", + # network backends, implementations + "SyncBackend", + "AnyIOBackend", + "TrioBackend", + # network backends, mock implementations + "AsyncMockBackend", + "AsyncMockStream", + "MockBackend", + "MockStream", + # network backends, interface + "AsyncNetworkStream", + "AsyncNetworkBackend", + "NetworkStream", + "NetworkBackend", + # util + "default_ssl_context", + "SOCKET_OPTION", + # exceptions + "ConnectionNotAvailable", + "ProxyError", + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", + "UnsupportedProtocol", + "TimeoutException", + "PoolTimeout", + "ConnectTimeout", + "ReadTimeout", + "WriteTimeout", + "NetworkError", + "ConnectError", + "ReadError", + "WriteError", +] + +__version__ = "1.0.9" + + +__locals = locals() +for __name in __all__: + # Exclude SOCKET_OPTION, it causes AttributeError on Python 3.14 + if not __name.startswith(("__", "SOCKET_OPTION")): + setattr(__locals[__name], "__module__", "httpcore") # noqa diff --git a/python_embeded/Lib/site-packages/httpcore/_api.py b/python_embeded/Lib/site-packages/httpcore/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..38b961d10de88bebc98c758d0d1f14af1e7c0370 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/_api.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import contextlib +import typing + +from ._models import URL, Extensions, HeaderTypes, Response +from ._sync.connection_pool import ConnectionPool + + +def request( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> Response: + """ + Sends an HTTP request, returning the response. + + ``` + response = httpcore.request("GET", "https://www.example.com/") + ``` + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + return pool.request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + + +@contextlib.contextmanager +def stream( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> typing.Iterator[Response]: + """ + Sends an HTTP request, returning the response within a content manager. + + ``` + with httpcore.stream("GET", "https://www.example.com/") as response: + ... + ``` + + When using the `stream()` function, the body of the response will not be + automatically read. If you want to access the response body you should + either use `content = response.read()`, or `for chunk in response.iter_content()`. + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + with pool.stream( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) as response: + yield response diff --git a/python_embeded/Lib/site-packages/httpcore/_exceptions.py b/python_embeded/Lib/site-packages/httpcore/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..bc28d44f55bdc4b872951a74780469a3999d9ab4 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/_exceptions.py @@ -0,0 +1,81 @@ +import contextlib +import typing + +ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]] + + +@contextlib.contextmanager +def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]: + try: + yield + except Exception as exc: # noqa: PIE786 + for from_exc, to_exc in map.items(): + if isinstance(exc, from_exc): + raise to_exc(exc) from exc + raise # pragma: nocover + + +class ConnectionNotAvailable(Exception): + pass + + +class ProxyError(Exception): + pass + + +class UnsupportedProtocol(Exception): + pass + + +class ProtocolError(Exception): + pass + + +class RemoteProtocolError(ProtocolError): + pass + + +class LocalProtocolError(ProtocolError): + pass + + +# Timeout errors + + +class TimeoutException(Exception): + pass + + +class PoolTimeout(TimeoutException): + pass + + +class ConnectTimeout(TimeoutException): + pass + + +class ReadTimeout(TimeoutException): + pass + + +class WriteTimeout(TimeoutException): + pass + + +# Network errors + + +class NetworkError(Exception): + pass + + +class ConnectError(NetworkError): + pass + + +class ReadError(NetworkError): + pass + + +class WriteError(NetworkError): + pass diff --git a/python_embeded/Lib/site-packages/httpcore/_models.py b/python_embeded/Lib/site-packages/httpcore/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8a65f13347d6621289a166d08123cbc8e1ad0157 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/_models.py @@ -0,0 +1,516 @@ +from __future__ import annotations + +import base64 +import ssl +import typing +import urllib.parse + +# Functions for typechecking... + + +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] +HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None] + +Extensions = typing.MutableMapping[str, typing.Any] + + +def enforce_bytes(value: bytes | str, *, name: str) -> bytes: + """ + Any arguments that are ultimately represented as bytes can be specified + either as bytes or as strings. + + However we enforce that any string arguments must only contain characters in + the plain ASCII range. chr(0)...chr(127). If you need to use characters + outside that range then be precise, and use a byte-wise argument. + """ + if isinstance(value, str): + try: + return value.encode("ascii") + except UnicodeEncodeError: + raise TypeError(f"{name} strings may not include unicode characters.") + elif isinstance(value, bytes): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be bytes or str, but got {seen_type}.") + + +def enforce_url(value: URL | bytes | str, *, name: str) -> URL: + """ + Type check for URL parameters. + """ + if isinstance(value, (bytes, str)): + return URL(value) + elif isinstance(value, URL): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be a URL, bytes, or str, but got {seen_type}.") + + +def enforce_headers( + value: HeadersAsMapping | HeadersAsSequence | None = None, *, name: str +) -> list[tuple[bytes, bytes]]: + """ + Convienence function that ensure all items in request or response headers + are either bytes or strings in the plain ASCII range. + """ + if value is None: + return [] + elif isinstance(value, typing.Mapping): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value.items() + ] + elif isinstance(value, typing.Sequence): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value + ] + + seen_type = type(value).__name__ + raise TypeError( + f"{name} must be a mapping or sequence of two-tuples, but got {seen_type}." + ) + + +def enforce_stream( + value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None, + *, + name: str, +) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]: + if value is None: + return ByteStream(b"") + elif isinstance(value, bytes): + return ByteStream(value) + return value + + +# * https://tools.ietf.org/html/rfc3986#section-3.2.3 +# * https://url.spec.whatwg.org/#url-miscellaneous +# * https://url.spec.whatwg.org/#scheme-state +DEFAULT_PORTS = { + b"ftp": 21, + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, +} + + +def include_request_headers( + headers: list[tuple[bytes, bytes]], + *, + url: "URL", + content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes], +) -> list[tuple[bytes, bytes]]: + headers_set = set(k.lower() for k, v in headers) + + if b"host" not in headers_set: + default_port = DEFAULT_PORTS.get(url.scheme) + if url.port is None or url.port == default_port: + header_value = url.host + else: + header_value = b"%b:%d" % (url.host, url.port) + headers = [(b"Host", header_value)] + headers + + if ( + content is not None + and b"content-length" not in headers_set + and b"transfer-encoding" not in headers_set + ): + if isinstance(content, bytes): + content_length = str(len(content)).encode("ascii") + headers += [(b"Content-Length", content_length)] + else: + headers += [(b"Transfer-Encoding", b"chunked")] # pragma: nocover + + return headers + + +# Interfaces for byte streams... + + +class ByteStream: + """ + A container for non-streaming content, and that supports both sync and async + stream iteration. + """ + + def __init__(self, content: bytes) -> None: + self._content = content + + def __iter__(self) -> typing.Iterator[bytes]: + yield self._content + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{len(self._content)} bytes]>" + + +class Origin: + def __init__(self, scheme: bytes, host: bytes, port: int) -> None: + self.scheme = scheme + self.host = host + self.port = port + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, Origin) + and self.scheme == other.scheme + and self.host == other.host + and self.port == other.port + ) + + def __str__(self) -> str: + scheme = self.scheme.decode("ascii") + host = self.host.decode("ascii") + port = str(self.port) + return f"{scheme}://{host}:{port}" + + +class URL: + """ + Represents the URL against which an HTTP request may be made. + + The URL may either be specified as a plain string, for convienence: + + ```python + url = httpcore.URL("https://www.example.com/") + ``` + + Or be constructed with explicitily pre-parsed components: + + ```python + url = httpcore.URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/') + ``` + + Using this second more explicit style allows integrations that are using + `httpcore` to pass through URLs that have already been parsed in order to use + libraries such as `rfc-3986` rather than relying on the stdlib. It also ensures + that URL parsing is treated identically at both the networking level and at any + higher layers of abstraction. + + The four components are important here, as they allow the URL to be precisely + specified in a pre-parsed format. They also allow certain types of request to + be created that could not otherwise be expressed. + + For example, an HTTP request to `http://www.example.com/` forwarded via a proxy + at `http://localhost:8080`... + + ```python + # Constructs an HTTP request with a complete URL as the target: + # GET https://www.example.com/ HTTP/1.1 + url = httpcore.URL( + scheme=b'http', + host=b'localhost', + port=8080, + target=b'https://www.example.com/' + ) + request = httpcore.Request( + method="GET", + url=url + ) + ``` + + Another example is constructing an `OPTIONS *` request... + + ```python + # Constructs an 'OPTIONS *' HTTP request: + # OPTIONS * HTTP/1.1 + url = httpcore.URL(scheme=b'https', host=b'www.example.com', target=b'*') + request = httpcore.Request(method="OPTIONS", url=url) + ``` + + This kind of request is not possible to formulate with a URL string, + because the `/` delimiter is always used to demark the target from the + host/port portion of the URL. + + For convenience, string-like arguments may be specified either as strings or + as bytes. However, once a request is being issue over-the-wire, the URL + components are always ultimately required to be a bytewise representation. + + In order to avoid any ambiguity over character encodings, when strings are used + as arguments, they must be strictly limited to the ASCII range `chr(0)`-`chr(127)`. + If you require a bytewise representation that is outside this range you must + handle the character encoding directly, and pass a bytes instance. + """ + + def __init__( + self, + url: bytes | str = "", + *, + scheme: bytes | str = b"", + host: bytes | str = b"", + port: int | None = None, + target: bytes | str = b"", + ) -> None: + """ + Parameters: + url: The complete URL as a string or bytes. + scheme: The URL scheme as a string or bytes. + Typically either `"http"` or `"https"`. + host: The URL host as a string or bytes. Such as `"www.example.com"`. + port: The port to connect to. Either an integer or `None`. + target: The target of the HTTP request. Such as `"/items?search=red"`. + """ + if url: + parsed = urllib.parse.urlparse(enforce_bytes(url, name="url")) + self.scheme = parsed.scheme + self.host = parsed.hostname or b"" + self.port = parsed.port + self.target = (parsed.path or b"/") + ( + b"?" + parsed.query if parsed.query else b"" + ) + else: + self.scheme = enforce_bytes(scheme, name="scheme") + self.host = enforce_bytes(host, name="host") + self.port = port + self.target = enforce_bytes(target, name="target") + + @property + def origin(self) -> Origin: + default_port = { + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, + b"socks5": 1080, + b"socks5h": 1080, + }[self.scheme] + return Origin( + scheme=self.scheme, host=self.host, port=self.port or default_port + ) + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, URL) + and other.scheme == self.scheme + and other.host == self.host + and other.port == self.port + and other.target == self.target + ) + + def __bytes__(self) -> bytes: + if self.port is None: + return b"%b://%b%b" % (self.scheme, self.host, self.target) + return b"%b://%b:%d%b" % (self.scheme, self.host, self.port, self.target) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(scheme={self.scheme!r}, " + f"host={self.host!r}, port={self.port!r}, target={self.target!r})" + ) + + +class Request: + """ + An HTTP request. + """ + + def __init__( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + method: The HTTP request method, either as a string or bytes. + For example: `GET`. + url: The request URL, either as a `URL` instance, or as a string or bytes. + For example: `"https://www.example.com".` + headers: The HTTP request headers. + content: The content of the request body. + extensions: A dictionary of optional extra information included on + the request. Possible keys include `"timeout"`, and `"trace"`. + """ + self.method: bytes = enforce_bytes(method, name="method") + self.url: URL = enforce_url(url, name="url") + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + if "target" in self.extensions: + self.url = URL( + scheme=self.url.scheme, + host=self.url.host, + port=self.url.port, + target=self.extensions["target"], + ) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.method!r}]>" + + +class Response: + """ + An HTTP response. + """ + + def __init__( + self, + status: int, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + status: The HTTP status code of the response. For example `200`. + headers: The HTTP response headers. + content: The content of the response body. + extensions: A dictionary of optional extra information included on + the responseself.Possible keys include `"http_version"`, + `"reason_phrase"`, and `"network_stream"`. + """ + self.status: int = status + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + self._stream_consumed = False + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + if isinstance(self.stream, typing.Iterable): + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'response.read()' first." + ) + else: + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'await response.aread()' first." + ) + return self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.status}]>" + + # Sync interface... + + def read(self) -> bytes: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an asynchronous response using 'response.read()'. " + "You should use 'await response.aread()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part for part in self.iter_stream()]) + return self._content + + def iter_stream(self) -> typing.Iterator[bytes]: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an asynchronous response using 'for ... in " + "response.iter_stream()'. " + "You should use 'async for ... in response.aiter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'for ... in response.iter_stream()' more than once." + ) + self._stream_consumed = True + for chunk in self.stream: + yield chunk + + def close(self) -> None: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to close an asynchronous response using 'response.close()'. " + "You should use 'await response.aclose()' instead." + ) + if hasattr(self.stream, "close"): + self.stream.close() + + # Async interface... + + async def aread(self) -> bytes: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an synchronous response using " + "'await response.aread()'. " + "You should use 'response.read()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_stream()]) + return self._content + + async def aiter_stream(self) -> typing.AsyncIterator[bytes]: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an synchronous response using 'async for ... in " + "response.aiter_stream()'. " + "You should use 'for ... in response.iter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'async for ... in response.aiter_stream()' " + "more than once." + ) + self._stream_consumed = True + async for chunk in self.stream: + yield chunk + + async def aclose(self) -> None: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to close a synchronous response using " + "'await response.aclose()'. " + "You should use 'response.close()' instead." + ) + if hasattr(self.stream, "aclose"): + await self.stream.aclose() + + +class Proxy: + def __init__( + self, + url: URL | bytes | str, + auth: tuple[bytes | str, bytes | str] | None = None, + headers: HeadersAsMapping | HeadersAsSequence | None = None, + ssl_context: ssl.SSLContext | None = None, + ): + self.url = enforce_url(url, name="url") + self.headers = enforce_headers(headers, name="headers") + self.ssl_context = ssl_context + + if auth is not None: + username = enforce_bytes(auth[0], name="auth") + password = enforce_bytes(auth[1], name="auth") + userpass = username + b":" + password + authorization = b"Basic " + base64.b64encode(userpass) + self.auth: tuple[bytes, bytes] | None = (username, password) + self.headers = [(b"Proxy-Authorization", authorization)] + self.headers + else: + self.auth = None diff --git a/python_embeded/Lib/site-packages/httpcore/_ssl.py b/python_embeded/Lib/site-packages/httpcore/_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..c99c5a67945b8a3a3544d481e979c791ab45fe23 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/_ssl.py @@ -0,0 +1,9 @@ +import ssl + +import certifi + + +def default_ssl_context() -> ssl.SSLContext: + context = ssl.create_default_context() + context.load_verify_locations(certifi.where()) + return context diff --git a/python_embeded/Lib/site-packages/httpcore/_synchronization.py b/python_embeded/Lib/site-packages/httpcore/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecc9e9c363e2f16c4f934cf41cf871826d6a495 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/_synchronization.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +import threading +import types + +from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions + +# Our async synchronization primatives use either 'anyio' or 'trio' depending +# on if they're running under asyncio or trio. + +try: + import trio +except (ImportError, NotImplementedError): # pragma: nocover + trio = None # type: ignore + +try: + import anyio +except ImportError: # pragma: nocover + anyio = None # type: ignore + + +def current_async_library() -> str: + # Determine if we're running under trio or asyncio. + # See https://sniffio.readthedocs.io/en/latest/ + try: + import sniffio + except ImportError: # pragma: nocover + environment = "asyncio" + else: + environment = sniffio.current_async_library() + + if environment not in ("asyncio", "trio"): # pragma: nocover + raise RuntimeError("Running under an unsupported async environment.") + + if environment == "asyncio" and anyio is None: # pragma: nocover + raise RuntimeError( + "Running with asyncio requires installation of 'httpcore[asyncio]'." + ) + + if environment == "trio" and trio is None: # pragma: nocover + raise RuntimeError( + "Running with trio requires installation of 'httpcore[trio]'." + ) + + return environment + + +class AsyncLock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_lock = trio.Lock() + elif self._backend == "asyncio": + self._anyio_lock = anyio.Lock() + + async def __aenter__(self) -> AsyncLock: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_lock.acquire() + elif self._backend == "asyncio": + await self._anyio_lock.acquire() + + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_lock.release() + elif self._backend == "asyncio": + self._anyio_lock.release() + + +class AsyncThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __enter__(self) -> AsyncThreadLock: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass + + +class AsyncEvent: + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_event = trio.Event() + elif self._backend == "asyncio": + self._anyio_event = anyio.Event() + + def set(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + self._trio_event.set() + elif self._backend == "asyncio": + self._anyio_event.set() + + async def wait(self, timeout: float | None = None) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} + timeout_or_inf = float("inf") if timeout is None else timeout + with map_exceptions(trio_exc_map): + with trio.fail_after(timeout_or_inf): + await self._trio_event.wait() + elif self._backend == "asyncio": + anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} + with map_exceptions(anyio_exc_map): + with anyio.fail_after(timeout): + await self._anyio_event.wait() + + +class AsyncSemaphore: + def __init__(self, bound: int) -> None: + self._bound = bound + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a semaphore with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_semaphore = trio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + elif self._backend == "asyncio": + self._anyio_semaphore = anyio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + + async def acquire(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_semaphore.acquire() + elif self._backend == "asyncio": + await self._anyio_semaphore.acquire() + + async def release(self) -> None: + if self._backend == "trio": + self._trio_semaphore.release() + elif self._backend == "asyncio": + self._anyio_semaphore.release() + + +class AsyncShieldCancellation: + # For certain portions of our codebase where we're dealing with + # closing connections during exception handling we want to shield + # the operation from being cancelled. + # + # with AsyncShieldCancellation(): + # ... # clean-up operations, shielded from cancellation. + + def __init__(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a shielded scope with the correct implementation. + """ + self._backend = current_async_library() + + if self._backend == "trio": + self._trio_shield = trio.CancelScope(shield=True) + elif self._backend == "asyncio": + self._anyio_shield = anyio.CancelScope(shield=True) + + def __enter__(self) -> AsyncShieldCancellation: + if self._backend == "trio": + self._trio_shield.__enter__() + elif self._backend == "asyncio": + self._anyio_shield.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_shield.__exit__(exc_type, exc_value, traceback) + elif self._backend == "asyncio": + self._anyio_shield.__exit__(exc_type, exc_value, traceback) + + +# Our thread-based synchronization primitives... + + +class Lock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> Lock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class ThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> ThreadLock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class Event: + def __init__(self) -> None: + self._event = threading.Event() + + def set(self) -> None: + self._event.set() + + def wait(self, timeout: float | None = None) -> None: + if timeout == float("inf"): # pragma: no cover + timeout = None + if not self._event.wait(timeout=timeout): + raise PoolTimeout() # pragma: nocover + + +class Semaphore: + def __init__(self, bound: int) -> None: + self._semaphore = threading.Semaphore(value=bound) + + def acquire(self) -> None: + self._semaphore.acquire() + + def release(self) -> None: + self._semaphore.release() + + +class ShieldCancellation: + # Thread-synchronous codebases don't support cancellation semantics. + # We have this class because we need to mirror the async and sync + # cases within our package, but it's just a no-op. + def __enter__(self) -> ShieldCancellation: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass diff --git a/python_embeded/Lib/site-packages/httpcore/_trace.py b/python_embeded/Lib/site-packages/httpcore/_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1cd7c47829ce17dbcf651ab56b4ffdce04a485 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/_trace.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import inspect +import logging +import types +import typing + +from ._models import Request + + +class Trace: + def __init__( + self, + name: str, + logger: logging.Logger, + request: Request | None = None, + kwargs: dict[str, typing.Any] | None = None, + ) -> None: + self.name = name + self.logger = logger + self.trace_extension = ( + None if request is None else request.extensions.get("trace") + ) + self.debug = self.logger.isEnabledFor(logging.DEBUG) + self.kwargs = kwargs or {} + self.return_value: typing.Any = None + self.should_trace = self.debug or self.trace_extension is not None + self.prefix = self.logger.name.split(".")[-1] + + def trace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + ret = self.trace_extension(prefix_and_name, info) + if inspect.iscoroutine(ret): # pragma: no cover + raise TypeError( + "If you are using a synchronous interface, " + "the callback of the `trace` extension should " + "be a normal function instead of an asynchronous function." + ) + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + def __enter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + self.trace(f"{self.name}.started", info) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + self.trace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + self.trace(f"{self.name}.failed", info) + + async def atrace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + coro = self.trace_extension(prefix_and_name, info) + if not inspect.iscoroutine(coro): # pragma: no cover + raise TypeError( + "If you're using an asynchronous interface, " + "the callback of the `trace` extension should " + "be an asynchronous function rather than a normal function." + ) + await coro + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + async def __aenter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + await self.atrace(f"{self.name}.started", info) + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + await self.atrace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + await self.atrace(f"{self.name}.failed", info) diff --git a/python_embeded/Lib/site-packages/httpcore/_utils.py b/python_embeded/Lib/site-packages/httpcore/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c44ff93cb2f572afc6e679308024b744b65c3b0a --- /dev/null +++ b/python_embeded/Lib/site-packages/httpcore/_utils.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import select +import socket +import sys + + +def is_socket_readable(sock: socket.socket | None) -> bool: + """ + Return whether a socket, as identifed by its file descriptor, is readable. + "A socket is readable" means that the read buffer isn't empty, i.e. that calling + .recv() on it would immediately return some data. + """ + # NOTE: we want check for readability without actually attempting to read, because + # we don't want to block forever if it's not readable. + + # In the case that the socket no longer exists, or cannot return a file + # descriptor, we treat it as being readable, as if it the next read operation + # on it is ready to return the terminating `b""`. + sock_fd = None if sock is None else sock.fileno() + if sock_fd is None or sock_fd < 0: # pragma: nocover + return True + + # The implementation below was stolen from: + # https://github.com/python-trio/trio/blob/20ee2b1b7376db637435d80e266212a35837ddcc/trio/_socket.py#L471-L478 + # See also: https://github.com/encode/httpcore/pull/193#issuecomment-703129316 + + # Use select.select on Windows, and when poll is unavailable and select.poll + # everywhere else. (E.g. When eventlet is in use. See #327) + if ( + sys.platform == "win32" or getattr(select, "poll", None) is None + ): # pragma: nocover + rready, _, _ = select.select([sock_fd], [], [], 0) + return bool(rready) + p = select.poll() + p.register(sock_fd, select.POLLIN) + return bool(p.poll(0)) diff --git a/python_embeded/Lib/site-packages/httpcore/py.typed b/python_embeded/Lib/site-packages/httpcore/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ae3828669397e90260062082642f57cb75c6ffed --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/LICENSE @@ -0,0 +1,23 @@ +Httplib2 Software License + +Copyright (c) 2006 by Joe Gregorio + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/METADATA b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..933bfa0bda2cc032d975ce8ab5be357a840cb464 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/METADATA @@ -0,0 +1,75 @@ +Metadata-Version: 2.1 +Name: httplib2 +Version: 0.22.0 +Summary: A comprehensive HTTP client library. +Home-page: https://github.com/httplib2/httplib2 +Author: Joe Gregorio +Author-email: joe@bitworking.org +License: MIT +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* +License-File: LICENSE +Requires-Dist: pyparsing (<3,>=2.4.2) ; python_version < "3.0" +Requires-Dist: pyparsing (!=3.0.0,!=3.0.1,!=3.0.2,!=3.0.3,<4,>=2.4.2) ; python_version > "3.0" + + + +A comprehensive HTTP client library, ``httplib2`` supports many features left out of other HTTP libraries. + +**HTTP and HTTPS** + HTTPS support is only available if the socket module was compiled with SSL support. + + +**Keep-Alive** + Supports HTTP 1.1 Keep-Alive, keeping the socket open and performing multiple requests over the same connection if possible. + + +**Authentication** + The following three types of HTTP Authentication are supported. These can be used over both HTTP and HTTPS. + + * Digest + * Basic + * WSSE + +**Caching** + The module can optionally operate with a private cache that understands the Cache-Control: + header and uses both the ETag and Last-Modified cache validators. Both file system + and memcached based caches are supported. + + +**All Methods** + The module can handle any HTTP request method, not just GET and POST. + + +**Redirects** + Automatically follows 3XX redirects on GETs. + + +**Compression** + Handles both 'deflate' and 'gzip' types of compression. + + +**Lost update support** + Automatically adds back ETags into PUT requests to resources we have already cached. This implements Section 3.2 of Detecting the Lost Update Problem Using Unreserved Checkout + + +**Unit Tested** + A large and growing set of unit tests. diff --git a/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/RECORD b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..767df277b73c6613224b417ec781ccc3c096f139 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/RECORD @@ -0,0 +1,19 @@ +httplib2-0.22.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httplib2-0.22.0.dist-info/LICENSE,sha256=WJ7sOPct8r4gNxHTuMvs6bkIxef_ALw8q39juunjZrQ,1086 +httplib2-0.22.0.dist-info/METADATA,sha256=KKy58CVIaYnc6oBjD0upeaA1dgTbB6z7JK5I6FmDSEM,2618 +httplib2-0.22.0.dist-info/RECORD,, +httplib2-0.22.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92 +httplib2-0.22.0.dist-info/top_level.txt,sha256=BEY8ChKwagUWmu9x8yN9JObJpZKNeWCr1E-sIECb56I,9 +httplib2/__init__.py,sha256=UOzaxGwGweHiLsxKBc39_Ez0N8aDHwAu--TkTbYLWCw,69396 +httplib2/__pycache__/__init__.cpython-312.pyc,, +httplib2/__pycache__/auth.cpython-312.pyc,, +httplib2/__pycache__/certs.cpython-312.pyc,, +httplib2/__pycache__/error.cpython-312.pyc,, +httplib2/__pycache__/iri2uri.cpython-312.pyc,, +httplib2/__pycache__/socks.cpython-312.pyc,, +httplib2/auth.py,sha256=Fcb7KqrqRCpUaGD-5l84nT5F2aU6ore6ujWLk5idK0o,2158 +httplib2/cacerts.txt,sha256=AbmYP54iGeKRQ1APtfQvHlo9wul2jVmznmbTzy2fTV4,137365 +httplib2/certs.py,sha256=guhfjMNhDdKJEyYBb5ZyLxVO5q1I7Y_P-4BG8MniBk8,971 +httplib2/error.py,sha256=GyqPUvZeKdVLq0f3xg0uX4rjtv7jVGJuPerAdyc-jfk,954 +httplib2/iri2uri.py,sha256=PhIzEzeR6C73l7piwrNAJlVvlWgsqxtJTlFeXgznzQo,4153 +httplib2/socks.py,sha256=oaeEOnT2rkTNm6wnn0CSdhWzVaVshnnkAKiP4kxKzzc,19701 diff --git a/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1f37c02f2eb2e26b306202feaccb31e522b8b169 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.40.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb881ece05bf2f998d84be544449ac976da2897c --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2-0.22.0.dist-info/top_level.txt @@ -0,0 +1 @@ +httplib2 diff --git a/python_embeded/Lib/site-packages/httplib2/__init__.py b/python_embeded/Lib/site-packages/httplib2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..723a63c5b80fba698e7dba7904e6f1d610a3dd14 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2/__init__.py @@ -0,0 +1,1799 @@ +# -*- coding: utf-8 -*- +"""Small, fast HTTP client library for Python.""" + +__author__ = "Joe Gregorio (joe@bitworking.org)" +__copyright__ = "Copyright 2006, Joe Gregorio" +__contributors__ = [ + "Thomas Broyer (t.broyer@ltgt.net)", + "James Antill", + "Xavier Verges Farrero", + "Jonathan Feinberg", + "Blair Zajac", + "Sam Ruby", + "Louis Nyffenegger", + "Mark Pilgrim", + "Alex Yu", + "Lai Han", +] +__license__ = "MIT" +__version__ = "0.22.0" + +import base64 +import calendar +import copy +import email +import email.feedparser +from email import header +import email.message +import email.utils +import errno +from gettext import gettext as _ +import gzip +from hashlib import md5 as _md5 +from hashlib import sha1 as _sha +import hmac +import http.client +import io +import os +import random +import re +import socket +import ssl +import sys +import time +import urllib.parse +import zlib + +try: + import socks +except ImportError: + # TODO: remove this fallback and copypasted socksipy module upon py2/3 merge, + # idea is to have soft-dependency on any compatible module called socks + from . import socks +from . import auth +from .error import * +from .iri2uri import iri2uri + + +def has_timeout(timeout): + if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"): + return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT + return timeout is not None + + +__all__ = [ + "debuglevel", + "FailedToDecompressContent", + "Http", + "HttpLib2Error", + "ProxyInfo", + "RedirectLimit", + "RedirectMissingLocation", + "Response", + "RETRIES", + "UnimplementedDigestAuthOptionError", + "UnimplementedHmacDigestAuthOptionError", +] + +# The httplib debug level, set to a non-zero value to get debug output +debuglevel = 0 + +# A request will be tried 'RETRIES' times if it fails at the socket/connection level. +RETRIES = 2 + + +# Open Items: +# ----------- + +# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?) + +# Pluggable cache storage (supports storing the cache in +# flat files by default. We need a plug-in architecture +# that can support Berkeley DB and Squid) + +# == Known Issues == +# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator. +# Does not handle Cache-Control: max-stale +# Does not use Age: headers when calculating cache freshness. + +# The number of redirections to follow before giving up. +# Note that only GET redirects are automatically followed. +# Will also honor 301 requests by saving that info and never +# requesting that URI again. +DEFAULT_MAX_REDIRECTS = 5 + +# Which headers are hop-by-hop headers by default +HOP_BY_HOP = [ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailers", + "transfer-encoding", + "upgrade", +] + +# https://tools.ietf.org/html/rfc7231#section-8.1.3 +SAFE_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE") + +# To change, assign to `Http().redirect_codes` +REDIRECT_CODES = frozenset((300, 301, 302, 303, 307, 308)) + + +from httplib2 import certs + +CA_CERTS = certs.where() + +# PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated. +# Both PROTOCOL_TLS and PROTOCOL_SSLv23 are equivalent and means: +# > Selects the highest protocol version that both the client and server support. +# > Despite the name, this option can select “TLS” protocols as well as “SSL”. +# source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_SSLv23 + +# PROTOCOL_TLS_CLIENT is python 3.10.0+. PROTOCOL_TLS is deprecated. +# > Auto-negotiate the highest protocol version that both the client and server support, and configure the context client-side connections. +# > The protocol enables CERT_REQUIRED and check_hostname by default. +# source: https://docs.python.org/3.10/library/ssl.html#ssl.PROTOCOL_TLS + +DEFAULT_TLS_VERSION = getattr(ssl, "PROTOCOL_TLS_CLIENT", None) or getattr(ssl, "PROTOCOL_TLS", None) or getattr(ssl, "PROTOCOL_SSLv23") + + +def _build_ssl_context( + disable_ssl_certificate_validation, + ca_certs, + cert_file=None, + key_file=None, + maximum_version=None, + minimum_version=None, + key_password=None, +): + if not hasattr(ssl, "SSLContext"): + raise RuntimeError("httplib2 requires Python 3.2+ for ssl.SSLContext") + + context = ssl.SSLContext(DEFAULT_TLS_VERSION) + # check_hostname and verify_mode should be set in opposite order during disable + # https://bugs.python.org/issue31431 + if disable_ssl_certificate_validation and hasattr(context, "check_hostname"): + context.check_hostname = not disable_ssl_certificate_validation + context.verify_mode = ssl.CERT_NONE if disable_ssl_certificate_validation else ssl.CERT_REQUIRED + + # SSLContext.maximum_version and SSLContext.minimum_version are python 3.7+. + # source: https://docs.python.org/3/library/ssl.html#ssl.SSLContext.maximum_version + if maximum_version is not None: + if hasattr(context, "maximum_version"): + if isinstance(maximum_version, str): + maximum_version = getattr(ssl.TLSVersion, maximum_version) + context.maximum_version = maximum_version + else: + raise RuntimeError("setting tls_maximum_version requires Python 3.7 and OpenSSL 1.1 or newer") + if minimum_version is not None: + if hasattr(context, "minimum_version"): + if isinstance(minimum_version, str): + minimum_version = getattr(ssl.TLSVersion, minimum_version) + context.minimum_version = minimum_version + else: + raise RuntimeError("setting tls_minimum_version requires Python 3.7 and OpenSSL 1.1 or newer") + # check_hostname requires python 3.4+ + # we will perform the equivalent in HTTPSConnectionWithTimeout.connect() by calling ssl.match_hostname + # if check_hostname is not supported. + if hasattr(context, "check_hostname"): + context.check_hostname = not disable_ssl_certificate_validation + + context.load_verify_locations(ca_certs) + + if cert_file: + context.load_cert_chain(cert_file, key_file, key_password) + + return context + + +def _get_end2end_headers(response): + hopbyhop = list(HOP_BY_HOP) + hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")]) + return [header for header in list(response.keys()) if header not in hopbyhop] + + +_missing = object() + + +def _errno_from_exception(e): + # TODO python 3.11+ cheap try: return e.errno except AttributeError: pass + errno = getattr(e, "errno", _missing) + if errno is not _missing: + return errno + + # socket.error and common wrap in .args + args = getattr(e, "args", None) + if args: + return _errno_from_exception(args[0]) + + # pysocks.ProxyError wraps in .socket_err + # https://github.com/httplib2/httplib2/pull/202 + socket_err = getattr(e, "socket_err", None) + if socket_err: + return _errno_from_exception(socket_err) + + return None + + +URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?") + + +def parse_uri(uri): + """Parses a URI using the regex given in Appendix B of RFC 3986. + + (scheme, authority, path, query, fragment) = parse_uri(uri) + """ + groups = URI.match(uri).groups() + return (groups[1], groups[3], groups[4], groups[6], groups[8]) + + +def urlnorm(uri): + (scheme, authority, path, query, fragment) = parse_uri(uri) + if not scheme or not authority: + raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri) + authority = authority.lower() + scheme = scheme.lower() + if not path: + path = "/" + # Could do syntax based normalization of the URI before + # computing the digest. See Section 6.2.2 of Std 66. + request_uri = query and "?".join([path, query]) or path + scheme = scheme.lower() + defrag_uri = scheme + "://" + authority + request_uri + return scheme, authority, request_uri, defrag_uri + + +# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/) +re_url_scheme = re.compile(r"^\w+://") +re_unsafe = re.compile(r"[^\w\-_.()=!]+", re.ASCII) + + +def safename(filename): + """Return a filename suitable for the cache. + Strips dangerous and common characters to create a filename we + can use to store the cache in. + """ + if isinstance(filename, bytes): + filename_bytes = filename + filename = filename.decode("utf-8") + else: + filename_bytes = filename.encode("utf-8") + filemd5 = _md5(filename_bytes).hexdigest() + filename = re_url_scheme.sub("", filename) + filename = re_unsafe.sub("", filename) + + # limit length of filename (vital for Windows) + # https://github.com/httplib2/httplib2/pull/74 + # C:\Users\ \AppData\Local\Temp\ , + # 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars + # Thus max safe filename x = 93 chars. Let it be 90 to make a round sum: + filename = filename[:90] + + return ",".join((filename, filemd5)) + + +NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+") + + +def _normalize_headers(headers): + return dict( + [ + (_convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),) + for (key, value) in headers.items() + ] + ) + + +def _convert_byte_str(s): + if not isinstance(s, str): + return str(s, "utf-8") + return s + + +def _parse_cache_control(headers): + retval = {} + if "cache-control" in headers: + parts = headers["cache-control"].split(",") + parts_with_args = [ + tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") + ] + parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")] + retval = dict(parts_with_args + parts_wo_args) + return retval + + +# Whether to use a strict mode to parse WWW-Authenticate headers +# Might lead to bad results in case of ill-formed header value, +# so disabled by default, falling back to relaxed parsing. +# Set to true to turn on, useful for testing servers. +USE_WWW_AUTH_STRICT_PARSING = 0 + + +def _entry_disposition(response_headers, request_headers): + """Determine freshness from the Date, Expires and Cache-Control headers. + + We don't handle the following: + + 1. Cache-Control: max-stale + 2. Age: headers are not used in the calculations. + + Not that this algorithm is simpler than you might think + because we are operating as a private (non-shared) cache. + This lets us ignore 's-maxage'. We can also ignore + 'proxy-invalidate' since we aren't a proxy. + We will never return a stale document as + fresh as a design decision, and thus the non-implementation + of 'max-stale'. This also lets us safely ignore 'must-revalidate' + since we operate as if every server has sent 'must-revalidate'. + Since we are private we get to ignore both 'public' and + 'private' parameters. We also ignore 'no-transform' since + we don't do any transformations. + The 'no-store' parameter is handled at a higher level. + So the only Cache-Control parameters we look at are: + + no-cache + only-if-cached + max-age + min-fresh + """ + + retval = "STALE" + cc = _parse_cache_control(request_headers) + cc_response = _parse_cache_control(response_headers) + + if "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1: + retval = "TRANSPARENT" + if "cache-control" not in request_headers: + request_headers["cache-control"] = "no-cache" + elif "no-cache" in cc: + retval = "TRANSPARENT" + elif "no-cache" in cc_response: + retval = "STALE" + elif "only-if-cached" in cc: + retval = "FRESH" + elif "date" in response_headers: + date = calendar.timegm(email.utils.parsedate_tz(response_headers["date"])) + now = time.time() + current_age = max(0, now - date) + if "max-age" in cc_response: + try: + freshness_lifetime = int(cc_response["max-age"]) + except ValueError: + freshness_lifetime = 0 + elif "expires" in response_headers: + expires = email.utils.parsedate_tz(response_headers["expires"]) + if None == expires: + freshness_lifetime = 0 + else: + freshness_lifetime = max(0, calendar.timegm(expires) - date) + else: + freshness_lifetime = 0 + if "max-age" in cc: + try: + freshness_lifetime = int(cc["max-age"]) + except ValueError: + freshness_lifetime = 0 + if "min-fresh" in cc: + try: + min_fresh = int(cc["min-fresh"]) + except ValueError: + min_fresh = 0 + current_age += min_fresh + if freshness_lifetime > current_age: + retval = "FRESH" + return retval + + +def _decompressContent(response, new_content): + content = new_content + try: + encoding = response.get("content-encoding", None) + if encoding in ["gzip", "deflate"]: + if encoding == "gzip": + content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read() + if encoding == "deflate": + try: + content = zlib.decompress(content, zlib.MAX_WBITS) + except (IOError, zlib.error): + content = zlib.decompress(content, -zlib.MAX_WBITS) + response["content-length"] = str(len(content)) + # Record the historical presence of the encoding in a way the won't interfere. + response["-content-encoding"] = response["content-encoding"] + del response["content-encoding"] + except (IOError, zlib.error): + content = "" + raise FailedToDecompressContent( + _("Content purported to be compressed with %s but failed to decompress.") % response.get("content-encoding"), + response, + content, + ) + return content + + +def _bind_write_headers(msg): + def _write_headers(self): + # Self refers to the Generator object. + for h, v in msg.items(): + print("%s:" % h, end=" ", file=self._fp) + if isinstance(v, header.Header): + print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) + else: + # email.Header got lots of smarts, so use it. + headers = header.Header(v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h) + print(headers.encode(), file=self._fp) + # A blank line always separates headers from body. + print(file=self._fp) + + return _write_headers + + +def _updateCache(request_headers, response_headers, content, cache, cachekey): + if cachekey: + cc = _parse_cache_control(request_headers) + cc_response = _parse_cache_control(response_headers) + if "no-store" in cc or "no-store" in cc_response: + cache.delete(cachekey) + else: + info = email.message.Message() + for key, value in response_headers.items(): + if key not in ["status", "content-encoding", "transfer-encoding"]: + info[key] = value + + # Add annotations to the cache to indicate what headers + # are variant for this request. + vary = response_headers.get("vary", None) + if vary: + vary_headers = vary.lower().replace(" ", "").split(",") + for header in vary_headers: + key = "-varied-%s" % header + try: + info[key] = request_headers[header] + except KeyError: + pass + + status = response_headers.status + if status == 304: + status = 200 + + status_header = "status: %d\r\n" % status + + try: + header_str = info.as_string() + except UnicodeEncodeError: + setattr(info, "_write_headers", _bind_write_headers(info)) + header_str = info.as_string() + + header_str = re.sub("\r(?!\n)|(? 0: + service = "cl" + # No point in guessing Base or Spreadsheet + # elif request_uri.find("spreadsheets") > 0: + # service = "wise" + + auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers["user-agent"],) + resp, content = self.http.request( + "https://www.google.com/accounts/ClientLogin", + method="POST", + body=urlencode(auth), + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ) + lines = content.split("\n") + d = dict([tuple(line.split("=", 1)) for line in lines if line]) + if resp.status == 403: + self.Auth = "" + else: + self.Auth = d["Auth"] + + def request(self, method, request_uri, headers, content): + """Modify the request headers to add the appropriate + Authorization header.""" + headers["authorization"] = "GoogleLogin Auth=" + self.Auth + + +AUTH_SCHEME_CLASSES = { + "basic": BasicAuthentication, + "wsse": WsseAuthentication, + "digest": DigestAuthentication, + "hmacdigest": HmacDigestAuthentication, + "googlelogin": GoogleLoginAuthentication, +} + +AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"] + + +class FileCache(object): + """Uses a local directory as a store for cached files. + Not really safe to use if multiple threads or processes are going to + be running on the same cache. + """ + + def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior + self.cache = cache + self.safe = safe + if not os.path.exists(cache): + os.makedirs(self.cache) + + def get(self, key): + retval = None + cacheFullPath = os.path.join(self.cache, self.safe(key)) + try: + f = open(cacheFullPath, "rb") + retval = f.read() + f.close() + except IOError: + pass + return retval + + def set(self, key, value): + cacheFullPath = os.path.join(self.cache, self.safe(key)) + f = open(cacheFullPath, "wb") + f.write(value) + f.close() + + def delete(self, key): + cacheFullPath = os.path.join(self.cache, self.safe(key)) + if os.path.exists(cacheFullPath): + os.remove(cacheFullPath) + + +class Credentials(object): + def __init__(self): + self.credentials = [] + + def add(self, name, password, domain=""): + self.credentials.append((domain.lower(), name, password)) + + def clear(self): + self.credentials = [] + + def iter(self, domain): + for (cdomain, name, password) in self.credentials: + if cdomain == "" or domain == cdomain: + yield (name, password) + + +class KeyCerts(Credentials): + """Identical to Credentials except that + name/password are mapped to key/cert.""" + + def add(self, key, cert, domain, password): + self.credentials.append((domain.lower(), key, cert, password)) + + def iter(self, domain): + for (cdomain, key, cert, password) in self.credentials: + if cdomain == "" or domain == cdomain: + yield (key, cert, password) + + +class AllHosts(object): + pass + + +class ProxyInfo(object): + """Collect information required to use a proxy.""" + + bypass_hosts = () + + def __init__( + self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None, + ): + """Args: + + proxy_type: The type of proxy server. This must be set to one of + socks.PROXY_TYPE_XXX constants. For example: p = + ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', + proxy_port=8000) + proxy_host: The hostname or IP address of the proxy server. + proxy_port: The port that the proxy server is running on. + proxy_rdns: If True (default), DNS queries will not be performed + locally, and instead, handed to the proxy to resolve. This is useful + if the network does not allow resolution of non-local names. In + httplib2 0.9 and earlier, this defaulted to False. + proxy_user: The username used to authenticate with the proxy server. + proxy_pass: The password used to authenticate with the proxy server. + proxy_headers: Additional or modified headers for the proxy connect + request. + """ + if isinstance(proxy_user, bytes): + proxy_user = proxy_user.decode() + if isinstance(proxy_pass, bytes): + proxy_pass = proxy_pass.decode() + ( + self.proxy_type, + self.proxy_host, + self.proxy_port, + self.proxy_rdns, + self.proxy_user, + self.proxy_pass, + self.proxy_headers, + ) = ( + proxy_type, + proxy_host, + proxy_port, + proxy_rdns, + proxy_user, + proxy_pass, + proxy_headers, + ) + + def astuple(self): + return ( + self.proxy_type, + self.proxy_host, + self.proxy_port, + self.proxy_rdns, + self.proxy_user, + self.proxy_pass, + self.proxy_headers, + ) + + def isgood(self): + return socks and (self.proxy_host != None) and (self.proxy_port != None) + + def applies_to(self, hostname): + return not self.bypass_host(hostname) + + def bypass_host(self, hostname): + """Has this host been excluded from the proxy config""" + if self.bypass_hosts is AllHosts: + return True + + hostname = "." + hostname.lstrip(".") + for skip_name in self.bypass_hosts: + # *.suffix + if skip_name.startswith(".") and hostname.endswith(skip_name): + return True + # exact match + if hostname == "." + skip_name: + return True + return False + + def __repr__(self): + return ( + "" + ).format(p=self) + + +def proxy_info_from_environment(method="http"): + """Read proxy info from the environment variables. + """ + if method not in ("http", "https"): + return + + env_var = method + "_proxy" + url = os.environ.get(env_var, os.environ.get(env_var.upper())) + if not url: + return + return proxy_info_from_url(url, method, noproxy=None) + + +def proxy_info_from_url(url, method="http", noproxy=None): + """Construct a ProxyInfo from a URL (such as http_proxy env var) + """ + url = urllib.parse.urlparse(url) + + proxy_type = 3 # socks.PROXY_TYPE_HTTP + pi = ProxyInfo( + proxy_type=proxy_type, + proxy_host=url.hostname, + proxy_port=url.port or dict(https=443, http=80)[method], + proxy_user=url.username or None, + proxy_pass=url.password or None, + proxy_headers=None, + ) + + bypass_hosts = [] + # If not given an explicit noproxy value, respect values in env vars. + if noproxy is None: + noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", "")) + # Special case: A single '*' character means all hosts should be bypassed. + if noproxy == "*": + bypass_hosts = AllHosts + elif noproxy.strip(): + bypass_hosts = noproxy.split(",") + bypass_hosts = tuple(filter(bool, bypass_hosts)) # To exclude empty string. + + pi.bypass_hosts = bypass_hosts + return pi + + +class HTTPConnectionWithTimeout(http.client.HTTPConnection): + """HTTPConnection subclass that supports timeouts + + HTTPConnection subclass that supports timeouts + + All timeouts are in seconds. If None is passed for timeout then + Python's default timeout for sockets will be used. See for example + the docs of socket.setdefaulttimeout(): + http://docs.python.org/library/socket.html#socket.setdefaulttimeout + """ + + def __init__(self, host, port=None, timeout=None, proxy_info=None): + http.client.HTTPConnection.__init__(self, host, port=port, timeout=timeout) + + self.proxy_info = proxy_info + if proxy_info and not isinstance(proxy_info, ProxyInfo): + self.proxy_info = proxy_info("http") + + def connect(self): + """Connect to the host and port specified in __init__.""" + if self.proxy_info and socks is None: + raise ProxiesUnavailableError("Proxy support missing but proxy use was requested!") + if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host): + use_proxy = True + ( + proxy_type, + proxy_host, + proxy_port, + proxy_rdns, + proxy_user, + proxy_pass, + proxy_headers, + ) = self.proxy_info.astuple() + + host = proxy_host + port = proxy_port + else: + use_proxy = False + + host = self.host + port = self.port + proxy_type = None + + socket_err = None + + for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): + af, socktype, proto, canonname, sa = res + try: + if use_proxy: + self.sock = socks.socksocket(af, socktype, proto) + self.sock.setproxy( + proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, + ) + else: + self.sock = socket.socket(af, socktype, proto) + self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + if has_timeout(self.timeout): + self.sock.settimeout(self.timeout) + if self.debuglevel > 0: + print("connect: ({0}, {1}) ************".format(self.host, self.port)) + if use_proxy: + print( + "proxy: {0} ************".format( + str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) + ) + ) + + self.sock.connect((self.host, self.port) + sa[2:]) + except socket.error as e: + socket_err = e + if self.debuglevel > 0: + print("connect fail: ({0}, {1})".format(self.host, self.port)) + if use_proxy: + print( + "proxy: {0}".format( + str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) + ) + ) + if self.sock: + self.sock.close() + self.sock = None + continue + break + if not self.sock: + raise socket_err + + +class HTTPSConnectionWithTimeout(http.client.HTTPSConnection): + """This class allows communication via SSL. + + All timeouts are in seconds. If None is passed for timeout then + Python's default timeout for sockets will be used. See for example + the docs of socket.setdefaulttimeout(): + http://docs.python.org/library/socket.html#socket.setdefaulttimeout + """ + + def __init__( + self, + host, + port=None, + key_file=None, + cert_file=None, + timeout=None, + proxy_info=None, + ca_certs=None, + disable_ssl_certificate_validation=False, + tls_maximum_version=None, + tls_minimum_version=None, + key_password=None, + ): + + self.disable_ssl_certificate_validation = disable_ssl_certificate_validation + self.ca_certs = ca_certs if ca_certs else CA_CERTS + + self.proxy_info = proxy_info + if proxy_info and not isinstance(proxy_info, ProxyInfo): + self.proxy_info = proxy_info("https") + + context = _build_ssl_context( + self.disable_ssl_certificate_validation, + self.ca_certs, + cert_file, + key_file, + maximum_version=tls_maximum_version, + minimum_version=tls_minimum_version, + key_password=key_password, + ) + super(HTTPSConnectionWithTimeout, self).__init__( + host, port=port, timeout=timeout, context=context, + ) + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + + def connect(self): + """Connect to a host on a given (SSL) port.""" + if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host): + use_proxy = True + ( + proxy_type, + proxy_host, + proxy_port, + proxy_rdns, + proxy_user, + proxy_pass, + proxy_headers, + ) = self.proxy_info.astuple() + + host = proxy_host + port = proxy_port + else: + use_proxy = False + + host = self.host + port = self.port + proxy_type = None + proxy_headers = None + + socket_err = None + + address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM) + for family, socktype, proto, canonname, sockaddr in address_info: + try: + if use_proxy: + sock = socks.socksocket(family, socktype, proto) + + sock.setproxy( + proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, + ) + else: + sock = socket.socket(family, socktype, proto) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + if has_timeout(self.timeout): + sock.settimeout(self.timeout) + sock.connect((self.host, self.port)) + + self.sock = self._context.wrap_socket(sock, server_hostname=self.host) + + # Python 3.3 compatibility: emulate the check_hostname behavior + if not hasattr(self._context, "check_hostname") and not self.disable_ssl_certificate_validation: + try: + ssl.match_hostname(self.sock.getpeercert(), self.host) + except Exception: + self.sock.shutdown(socket.SHUT_RDWR) + self.sock.close() + raise + + if self.debuglevel > 0: + print("connect: ({0}, {1})".format(self.host, self.port)) + if use_proxy: + print( + "proxy: {0}".format( + str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) + ) + ) + except (ssl.SSLError, ssl.CertificateError) as e: + if sock: + sock.close() + if self.sock: + self.sock.close() + self.sock = None + raise + except (socket.timeout, socket.gaierror): + raise + except socket.error as e: + socket_err = e + if self.debuglevel > 0: + print("connect fail: ({0}, {1})".format(self.host, self.port)) + if use_proxy: + print( + "proxy: {0}".format( + str((proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers,)) + ) + ) + if self.sock: + self.sock.close() + self.sock = None + continue + break + if not self.sock: + raise socket_err + + +SCHEME_TO_CONNECTION = { + "http": HTTPConnectionWithTimeout, + "https": HTTPSConnectionWithTimeout, +} + + +class Http(object): + """An HTTP client that handles: + + - all methods + - caching + - ETags + - compression, + - HTTPS + - Basic + - Digest + - WSSE + + and more. + """ + + def __init__( + self, + cache=None, + timeout=None, + proxy_info=proxy_info_from_environment, + ca_certs=None, + disable_ssl_certificate_validation=False, + tls_maximum_version=None, + tls_minimum_version=None, + ): + """If 'cache' is a string then it is used as a directory name for + a disk cache. Otherwise it must be an object that supports the + same interface as FileCache. + + All timeouts are in seconds. If None is passed for timeout + then Python's default timeout for sockets will be used. See + for example the docs of socket.setdefaulttimeout(): + http://docs.python.org/library/socket.html#socket.setdefaulttimeout + + `proxy_info` may be: + - a callable that takes the http scheme ('http' or 'https') and + returns a ProxyInfo instance per request. By default, uses + proxy_info_from_environment. + - a ProxyInfo instance (static proxy config). + - None (proxy disabled). + + ca_certs is the path of a file containing root CA certificates for SSL + server certificate validation. By default, a CA cert file bundled with + httplib2 is used. + + If disable_ssl_certificate_validation is true, SSL cert validation will + not be performed. + + tls_maximum_version / tls_minimum_version require Python 3.7+ / + OpenSSL 1.1.0g+. A value of "TLSv1_3" requires OpenSSL 1.1.1+. + """ + self.proxy_info = proxy_info + self.ca_certs = ca_certs + self.disable_ssl_certificate_validation = disable_ssl_certificate_validation + self.tls_maximum_version = tls_maximum_version + self.tls_minimum_version = tls_minimum_version + # Map domain name to an httplib connection + self.connections = {} + # The location of the cache, for now a directory + # where cached responses are held. + if cache and isinstance(cache, str): + self.cache = FileCache(cache) + else: + self.cache = cache + + # Name/password + self.credentials = Credentials() + + # Key/cert + self.certificates = KeyCerts() + + # authorization objects + self.authorizations = [] + + # If set to False then no redirects are followed, even safe ones. + self.follow_redirects = True + + self.redirect_codes = REDIRECT_CODES + + # Which HTTP methods do we apply optimistic concurrency to, i.e. + # which methods get an "if-match:" etag header added to them. + self.optimistic_concurrency_methods = ["PUT", "PATCH"] + + self.safe_methods = list(SAFE_METHODS) + + # If 'follow_redirects' is True, and this is set to True then + # all redirecs are followed, including unsafe ones. + self.follow_all_redirects = False + + self.ignore_etag = False + + self.force_exception_to_status_code = False + + self.timeout = timeout + + # Keep Authorization: headers on a redirect. + self.forward_authorization_headers = False + + def close(self): + """Close persistent connections, clear sensitive data. + Not thread-safe, requires external synchronization against concurrent requests. + """ + existing, self.connections = self.connections, {} + for _, c in existing.items(): + c.close() + self.certificates.clear() + self.clear_credentials() + + def __getstate__(self): + state_dict = copy.copy(self.__dict__) + # In case request is augmented by some foreign object such as + # credentials which handle auth + if "request" in state_dict: + del state_dict["request"] + if "connections" in state_dict: + del state_dict["connections"] + return state_dict + + def __setstate__(self, state): + self.__dict__.update(state) + self.connections = {} + + def _auth_from_challenge(self, host, request_uri, headers, response, content): + """A generator that creates Authorization objects + that can be applied to requests. + """ + challenges = auth._parse_www_authenticate(response, "www-authenticate") + for cred in self.credentials.iter(host): + for scheme in AUTH_SCHEME_ORDER: + if scheme in challenges: + yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self) + + def add_credentials(self, name, password, domain=""): + """Add a name and password that will be used + any time a request requires authentication.""" + self.credentials.add(name, password, domain) + + def add_certificate(self, key, cert, domain, password=None): + """Add a key and cert that will be used + any time a request requires authentication.""" + self.certificates.add(key, cert, domain, password) + + def clear_credentials(self): + """Remove all the names and passwords + that are used for authentication""" + self.credentials.clear() + self.authorizations = [] + + def _conn_request(self, conn, request_uri, method, body, headers): + i = 0 + seen_bad_status_line = False + while i < RETRIES: + i += 1 + try: + if conn.sock is None: + conn.connect() + conn.request(method, request_uri, body, headers) + except socket.timeout: + conn.close() + raise + except socket.gaierror: + conn.close() + raise ServerNotFoundError("Unable to find the server at %s" % conn.host) + except socket.error as e: + errno_ = _errno_from_exception(e) + if errno_ in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES: + continue # retry on potentially transient errors + raise + except http.client.HTTPException: + if conn.sock is None: + if i < RETRIES - 1: + conn.close() + conn.connect() + continue + else: + conn.close() + raise + if i < RETRIES - 1: + conn.close() + conn.connect() + continue + # Just because the server closed the connection doesn't apparently mean + # that the server didn't send a response. + pass + try: + response = conn.getresponse() + except (http.client.BadStatusLine, http.client.ResponseNotReady): + # If we get a BadStatusLine on the first try then that means + # the connection just went stale, so retry regardless of the + # number of RETRIES set. + if not seen_bad_status_line and i == 1: + i = 0 + seen_bad_status_line = True + conn.close() + conn.connect() + continue + else: + conn.close() + raise + except socket.timeout: + raise + except (socket.error, http.client.HTTPException): + conn.close() + if i == 0: + conn.close() + conn.connect() + continue + else: + raise + else: + content = b"" + if method == "HEAD": + conn.close() + else: + content = response.read() + response = Response(response) + if method != "HEAD": + content = _decompressContent(response, content) + + break + return (response, content) + + def _request( + self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey, + ): + """Do the actual request using the connection object + and also follow one level of redirects if necessary""" + + auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)] + auth = auths and sorted(auths)[0][1] or None + if auth: + auth.request(method, request_uri, headers, body) + + (response, content) = self._conn_request(conn, request_uri, method, body, headers) + + if auth: + if auth.response(response, body): + auth.request(method, request_uri, headers, body) + (response, content) = self._conn_request(conn, request_uri, method, body, headers) + response._stale_digest = 1 + + if response.status == 401: + for authorization in self._auth_from_challenge(host, request_uri, headers, response, content): + authorization.request(method, request_uri, headers, body) + (response, content) = self._conn_request(conn, request_uri, method, body, headers) + if response.status != 401: + self.authorizations.append(authorization) + authorization.response(response, body) + break + + if self.follow_all_redirects or method in self.safe_methods or response.status in (303, 308): + if self.follow_redirects and response.status in self.redirect_codes: + # Pick out the location header and basically start from the beginning + # remembering first to strip the ETag header and decrement our 'depth' + if redirections: + if "location" not in response and response.status != 300: + raise RedirectMissingLocation( + _("Redirected but the response is missing a Location: header."), response, content, + ) + # Fix-up relative redirects (which violate an RFC 2616 MUST) + if "location" in response: + location = response["location"] + (scheme, authority, path, query, fragment) = parse_uri(location) + if authority == None: + response["location"] = urllib.parse.urljoin(absolute_uri, location) + if response.status == 308 or (response.status == 301 and (method in self.safe_methods)): + response["-x-permanent-redirect-url"] = response["location"] + if "content-location" not in response: + response["content-location"] = absolute_uri + _updateCache(headers, response, content, self.cache, cachekey) + if "if-none-match" in headers: + del headers["if-none-match"] + if "if-modified-since" in headers: + del headers["if-modified-since"] + if "authorization" in headers and not self.forward_authorization_headers: + del headers["authorization"] + if "location" in response: + location = response["location"] + old_response = copy.deepcopy(response) + if "content-location" not in old_response: + old_response["content-location"] = absolute_uri + redirect_method = method + if response.status in [302, 303]: + redirect_method = "GET" + body = None + (response, content) = self.request( + location, method=redirect_method, body=body, headers=headers, redirections=redirections - 1, + ) + response.previous = old_response + else: + raise RedirectLimit( + "Redirected more times than redirection_limit allows.", response, content, + ) + elif response.status in [200, 203] and method in self.safe_methods: + # Don't cache 206's since we aren't going to handle byte range requests + if "content-location" not in response: + response["content-location"] = absolute_uri + _updateCache(headers, response, content, self.cache, cachekey) + + return (response, content) + + def _normalize_headers(self, headers): + return _normalize_headers(headers) + + # Need to catch and rebrand some exceptions + # Then need to optionally turn all exceptions into status codes + # including all socket.* and httplib.* exceptions. + + def request( + self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, + ): + """ Performs a single HTTP request. +The 'uri' is the URI of the HTTP resource and can begin +with either 'http' or 'https'. The value of 'uri' must be an absolute URI. + +The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc. +There is no restriction on the methods allowed. + +The 'body' is the entity body to be sent with the request. It is a string +object. + +Any extra headers that are to be sent with the request should be provided in the +'headers' dictionary. + +The maximum number of redirect to follow before raising an +exception is 'redirections. The default is 5. + +The return value is a tuple of (response, content), the first +being and instance of the 'Response' class, the second being +a string that contains the response entity body. + """ + conn_key = "" + + try: + if headers is None: + headers = {} + else: + headers = self._normalize_headers(headers) + + if "user-agent" not in headers: + headers["user-agent"] = "Python-httplib2/%s (gzip)" % __version__ + + uri = iri2uri(uri) + # Prevent CWE-75 space injection to manipulate request via part of uri. + # Prevent CWE-93 CRLF injection to modify headers via part of uri. + uri = uri.replace(" ", "%20").replace("\r", "%0D").replace("\n", "%0A") + + (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) + + conn_key = scheme + ":" + authority + conn = self.connections.get(conn_key) + if conn is None: + if not connection_type: + connection_type = SCHEME_TO_CONNECTION[scheme] + certs = list(self.certificates.iter(authority)) + if issubclass(connection_type, HTTPSConnectionWithTimeout): + if certs: + conn = self.connections[conn_key] = connection_type( + authority, + key_file=certs[0][0], + cert_file=certs[0][1], + timeout=self.timeout, + proxy_info=self.proxy_info, + ca_certs=self.ca_certs, + disable_ssl_certificate_validation=self.disable_ssl_certificate_validation, + tls_maximum_version=self.tls_maximum_version, + tls_minimum_version=self.tls_minimum_version, + key_password=certs[0][2], + ) + else: + conn = self.connections[conn_key] = connection_type( + authority, + timeout=self.timeout, + proxy_info=self.proxy_info, + ca_certs=self.ca_certs, + disable_ssl_certificate_validation=self.disable_ssl_certificate_validation, + tls_maximum_version=self.tls_maximum_version, + tls_minimum_version=self.tls_minimum_version, + ) + else: + conn = self.connections[conn_key] = connection_type( + authority, timeout=self.timeout, proxy_info=self.proxy_info + ) + conn.set_debuglevel(debuglevel) + + if "range" not in headers and "accept-encoding" not in headers: + headers["accept-encoding"] = "gzip, deflate" + + info = email.message.Message() + cachekey = None + cached_value = None + if self.cache: + cachekey = defrag_uri + cached_value = self.cache.get(cachekey) + if cached_value: + try: + info, content = cached_value.split(b"\r\n\r\n", 1) + info = email.message_from_bytes(info) + for k, v in info.items(): + if v.startswith("=?") and v.endswith("?="): + info.replace_header(k, str(*email.header.decode_header(v)[0])) + except (IndexError, ValueError): + self.cache.delete(cachekey) + cachekey = None + cached_value = None + + if ( + method in self.optimistic_concurrency_methods + and self.cache + and "etag" in info + and not self.ignore_etag + and "if-match" not in headers + ): + # http://www.w3.org/1999/04/Editing/ + headers["if-match"] = info["etag"] + + # https://tools.ietf.org/html/rfc7234 + # A cache MUST invalidate the effective Request URI as well as [...] Location and Content-Location + # when a non-error status code is received in response to an unsafe request method. + if self.cache and cachekey and method not in self.safe_methods: + self.cache.delete(cachekey) + + # Check the vary header in the cache to see if this request + # matches what varies in the cache. + if method in self.safe_methods and "vary" in info: + vary = info["vary"] + vary_headers = vary.lower().replace(" ", "").split(",") + for header in vary_headers: + key = "-varied-%s" % header + value = info[key] + if headers.get(header, None) != value: + cached_value = None + break + + if ( + self.cache + and cached_value + and (method in self.safe_methods or info["status"] == "308") + and "range" not in headers + ): + redirect_method = method + if info["status"] not in ("307", "308"): + redirect_method = "GET" + if "-x-permanent-redirect-url" in info: + # Should cached permanent redirects be counted in our redirection count? For now, yes. + if redirections <= 0: + raise RedirectLimit( + "Redirected more times than redirection_limit allows.", {}, "", + ) + (response, new_content) = self.request( + info["-x-permanent-redirect-url"], + method=redirect_method, + headers=headers, + redirections=redirections - 1, + ) + response.previous = Response(info) + response.previous.fromcache = True + else: + # Determine our course of action: + # Is the cached entry fresh or stale? + # Has the client requested a non-cached response? + # + # There seems to be three possible answers: + # 1. [FRESH] Return the cache entry w/o doing a GET + # 2. [STALE] Do the GET (but add in cache validators if available) + # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request + entry_disposition = _entry_disposition(info, headers) + + if entry_disposition == "FRESH": + response = Response(info) + response.fromcache = True + return (response, content) + + if entry_disposition == "STALE": + if "etag" in info and not self.ignore_etag and not "if-none-match" in headers: + headers["if-none-match"] = info["etag"] + if "last-modified" in info and not "last-modified" in headers: + headers["if-modified-since"] = info["last-modified"] + elif entry_disposition == "TRANSPARENT": + pass + + (response, new_content) = self._request( + conn, authority, uri, request_uri, method, body, headers, redirections, cachekey, + ) + + if response.status == 304 and method == "GET": + # Rewrite the cache entry with the new end-to-end headers + # Take all headers that are in response + # and overwrite their values in info. + # unless they are hop-by-hop, or are listed in the connection header. + + for key in _get_end2end_headers(response): + info[key] = response[key] + merged_response = Response(info) + if hasattr(response, "_stale_digest"): + merged_response._stale_digest = response._stale_digest + _updateCache(headers, merged_response, content, self.cache, cachekey) + response = merged_response + response.status = 200 + response.fromcache = True + + elif response.status == 200: + content = new_content + else: + self.cache.delete(cachekey) + content = new_content + else: + cc = _parse_cache_control(headers) + if "only-if-cached" in cc: + info["status"] = "504" + response = Response(info) + content = b"" + else: + (response, content) = self._request( + conn, authority, uri, request_uri, method, body, headers, redirections, cachekey, + ) + except Exception as e: + is_timeout = isinstance(e, socket.timeout) + if is_timeout: + conn = self.connections.pop(conn_key, None) + if conn: + conn.close() + + if self.force_exception_to_status_code: + if isinstance(e, HttpLib2ErrorWithResponse): + response = e.response + content = e.content + response.status = 500 + response.reason = str(e) + elif isinstance(e, socket.timeout): + content = b"Request Timeout" + response = Response({"content-type": "text/plain", "status": "408", "content-length": len(content),}) + response.reason = "Request Timeout" + else: + content = str(e).encode("utf-8") + response = Response({"content-type": "text/plain", "status": "400", "content-length": len(content),}) + response.reason = "Bad Request" + else: + raise + + return (response, content) + + +class Response(dict): + """An object more like email.message than httplib.HTTPResponse.""" + + """Is this response from our local cache""" + fromcache = False + """HTTP protocol version used by server. + + 10 for HTTP/1.0, 11 for HTTP/1.1. + """ + version = 11 + + "Status code returned by server. " + status = 200 + """Reason phrase returned by server.""" + reason = "Ok" + + previous = None + + def __init__(self, info): + # info is either an email.message or + # an httplib.HTTPResponse object. + if isinstance(info, http.client.HTTPResponse): + for key, value in info.getheaders(): + key = key.lower() + prev = self.get(key) + if prev is not None: + value = ", ".join((prev, value)) + self[key] = value + self.status = info.status + self["status"] = str(self.status) + self.reason = info.reason + self.version = info.version + elif isinstance(info, email.message.Message): + for key, value in list(info.items()): + self[key.lower()] = value + self.status = int(self["status"]) + else: + for key, value in info.items(): + self[key.lower()] = value + self.status = int(self.get("status", self.status)) + + def __getattr__(self, name): + if name == "dict": + return self + else: + raise AttributeError(name) diff --git a/python_embeded/Lib/site-packages/httplib2/auth.py b/python_embeded/Lib/site-packages/httplib2/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..b8028ae2a75f3ff6e744deb01171414c1ffc4db7 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2/auth.py @@ -0,0 +1,69 @@ +import base64 +import re + +import pyparsing as pp + +from .error import * + + +try: # pyparsing>=3.0.0 + downcaseTokens = pp.common.downcaseTokens +except AttributeError: + downcaseTokens = pp.downcaseTokens + +UNQUOTE_PAIRS = re.compile(r"\\(.)") +unquote = lambda s, l, t: UNQUOTE_PAIRS.sub(r"\1", t[0][1:-1]) + +# https://tools.ietf.org/html/rfc7235#section-1.2 +# https://tools.ietf.org/html/rfc7235#appendix-B +tchar = "!#$%&'*+-.^_`|~" + pp.nums + pp.alphas +token = pp.Word(tchar).setName("token") +token68 = pp.Combine(pp.Word("-._~+/" + pp.nums + pp.alphas) + pp.Optional(pp.Word("=").leaveWhitespace())).setName( + "token68" +) + +quoted_string = pp.dblQuotedString.copy().setName("quoted-string").setParseAction(unquote) +auth_param_name = token.copy().setName("auth-param-name").addParseAction(downcaseTokens) +auth_param = auth_param_name + pp.Suppress("=") + (quoted_string | token) +params = pp.Dict(pp.delimitedList(pp.Group(auth_param))) + +scheme = token("scheme") +challenge = scheme + (params("params") | token68("token")) + +authentication_info = params.copy() +www_authenticate = pp.delimitedList(pp.Group(challenge)) + + +def _parse_authentication_info(headers, headername="authentication-info"): + """https://tools.ietf.org/html/rfc7615 + """ + header = headers.get(headername, "").strip() + if not header: + return {} + try: + parsed = authentication_info.parseString(header) + except pp.ParseException as ex: + # print(ex.explain(ex)) + raise MalformedHeader(headername) + + return parsed.asDict() + + +def _parse_www_authenticate(headers, headername="www-authenticate"): + """Returns a dictionary of dictionaries, one dict per auth_scheme.""" + header = headers.get(headername, "").strip() + if not header: + return {} + try: + parsed = www_authenticate.parseString(header) + except pp.ParseException as ex: + # print(ex.explain(ex)) + raise MalformedHeader(headername) + + retval = { + challenge["scheme"].lower(): challenge["params"].asDict() + if "params" in challenge + else {"token": challenge.get("token")} + for challenge in parsed + } + return retval diff --git a/python_embeded/Lib/site-packages/httplib2/cacerts.txt b/python_embeded/Lib/site-packages/httplib2/cacerts.txt new file mode 100644 index 0000000000000000000000000000000000000000..78a444c43af0a2ed7e0e69438c2ce6cc88ff6e93 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2/cacerts.txt @@ -0,0 +1,2225 @@ +# Issuer: CN=GTE CyberTrust Global Root O=GTE Corporation OU=GTE CyberTrust Solutions, Inc. +# Subject: CN=GTE CyberTrust Global Root O=GTE Corporation OU=GTE CyberTrust Solutions, Inc. +# Label: "GTE CyberTrust Global Root" +# Serial: 421 +# MD5 Fingerprint: ca:3d:d3:68:f1:03:5c:d0:32:fa:b8:2b:59:e8:5a:db +# SHA1 Fingerprint: 97:81:79:50:d8:1c:96:70:cc:34:d8:09:cf:79:44:31:36:7e:f4:74 +# SHA256 Fingerprint: a5:31:25:18:8d:21:10:aa:96:4b:02:c7:b7:c6:da:32:03:17:08:94:e5:fb:71:ff:fb:66:67:d5:e6:81:0a:36 +-----BEGIN CERTIFICATE----- +MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYD +VQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNv +bHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJv +b3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEzMjM1OTAwWjB1MQswCQYDVQQGEwJV +UzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU +cnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds +b2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrH +iM3dFw4usJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTS +r41tiGeA5u2ylc9yMcqlHHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X4 +04Wqk2kmhXBIgD8SFcd5tB8FLztimQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAG3r +GwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMWM4ETCJ57NE7fQMh017l9 +3PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OFNMQkpw0P +lZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/ +-----END CERTIFICATE----- + +# Issuer: CN=Thawte Server CA O=Thawte Consulting cc OU=Certification Services Division +# Subject: CN=Thawte Server CA O=Thawte Consulting cc OU=Certification Services Division +# Label: "Thawte Server CA" +# Serial: 1 +# MD5 Fingerprint: c5:70:c4:a2:ed:53:78:0c:c8:10:53:81:64:cb:d0:1d +# SHA1 Fingerprint: 23:e5:94:94:51:95:f2:41:48:03:b4:d5:64:d2:a3:a3:f5:d8:8b:8c +# SHA256 Fingerprint: b4:41:0b:73:e2:e6:ea:ca:47:fb:c4:2f:8f:a4:01:8a:f4:38:1d:c5:4c:fa:a8:44:50:46:1e:ed:09:45:4d:e9 +-----BEGIN CERTIFICATE----- +MIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkEx +FTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYD +VQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlv +biBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEm +MCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5jb20wHhcNOTYwODAx +MDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkGA1UEBhMCWkExFTATBgNVBAgT +DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3 +dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNl +cyBEaXZpc2lvbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3 +DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQAD +gY0AMIGJAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl/Kj0R1HahbUgdJSGHg91 +yekIYfUGbTBuFRkC6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg71CcEJRCX +L+eQbcAoQpnXTEPew/UhbVSfXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGj +EzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG +7oWDTSEwjsrZqG9JGubaUeNgcGyEYRGhGshIPllDfU+VPaGLtwtimHp1it2ITk6e +QNuozDJ0uW8NxuOzRAvZim+aKZuZGCg70eNAKJpaPNW15yAbi8qkq43pUdniTCxZ +qdq5snUb9kLy78fyGPmJvKP/iiMucEc= +-----END CERTIFICATE----- + +# Issuer: CN=Thawte Premium Server CA O=Thawte Consulting cc OU=Certification Services Division +# Subject: CN=Thawte Premium Server CA O=Thawte Consulting cc OU=Certification Services Division +# Label: "Thawte Premium Server CA" +# Serial: 1 +# MD5 Fingerprint: 06:9f:69:79:16:66:90:02:1b:8c:8c:a2:c3:07:6f:3a +# SHA1 Fingerprint: 62:7f:8d:78:27:65:63:99:d2:7d:7f:90:44:c9:fe:b3:f3:3e:fa:9a +# SHA256 Fingerprint: ab:70:36:36:5c:71:54:aa:29:c2:c2:9f:5d:41:91:16:3b:16:2a:22:25:01:13:57:d5:6d:07:ff:a7:bc:1f:72 +-----BEGIN CERTIFICATE----- +MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkEx +FTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYD +VQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlv +biBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UEAxMYVGhhd3RlIFByZW1pdW0gU2Vy +dmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZlckB0aGF3dGUuY29t +MB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYTAlpB +MRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsG +A1UEChMUVGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRp +b24gU2VydmljZXMgRGl2aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNl +cnZlciBDQTEoMCYGCSqGSIb3DQEJARYZcHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNv +bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2aovXwlue2oFBYo847kkE +VdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIhUdib0GfQ +ug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMR +uHM/qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG +9w0BAQQFAAOBgQAmSCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUI +hfzJATj/Tb7yFkJD57taRvvBxhEf8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JM +pAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7tUCemDaYj+bvLpgcUQg== +-----END CERTIFICATE----- + +# Issuer: O=Equifax OU=Equifax Secure Certificate Authority +# Subject: O=Equifax OU=Equifax Secure Certificate Authority +# Label: "Equifax Secure CA" +# Serial: 903804111 +# MD5 Fingerprint: 67:cb:9d:c0:13:24:8a:82:9b:b2:17:1e:d1:1b:ec:d4 +# SHA1 Fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a +# SHA256 Fingerprint: 08:29:7a:40:47:db:a2:36:80:c7:31:db:6e:31:76:53:ca:78:48:e1:be:bd:3a:0b:01:79:a7:07:f9:2c:f1:78 +-----BEGIN CERTIFICATE----- +MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV +UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy +dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1 +MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx +dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B +AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f +BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A +cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC +AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ +MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm +aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw +ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj +IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF +MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA +A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y +7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh +1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4 +-----END CERTIFICATE----- + +# Issuer: O=VeriSign, Inc. OU=Class 3 Public Primary Certification Authority - G2/(c) 1998 VeriSign, Inc. - For authorized use only/VeriSign Trust Network +# Subject: O=VeriSign, Inc. OU=Class 3 Public Primary Certification Authority - G2/(c) 1998 VeriSign, Inc. - For authorized use only/VeriSign Trust Network +# Label: "Verisign Class 3 Public Primary Certification Authority - G2" +# Serial: 167285380242319648451154478808036881606 +# MD5 Fingerprint: a2:33:9b:4c:74:78:73:d4:6c:e7:c1:f3:8d:cb:5c:e9 +# SHA1 Fingerprint: 85:37:1c:a6:e5:50:14:3d:ce:28:03:47:1b:de:3a:09:e8:f8:77:0f +# SHA256 Fingerprint: 83:ce:3c:12:29:68:8a:59:3d:48:5f:81:97:3c:0f:91:95:43:1e:da:37:cc:5e:36:43:0e:79:c7:a8:88:63:8b +-----BEGIN CERTIFICATE----- +MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJ +BgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xh +c3MgMyBQdWJsaWMgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcy +MTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp +emVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMB4X +DTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVTMRcw +FQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMg +UHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEo +YykgMTk5OCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5 +MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEB +AQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCOFoUgRm1HP9SFIIThbbP4 +pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71lSk8UOg0 +13gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwID +AQABMA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSk +U01UbSuvDV1Ai2TT1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7i +F6YM40AIOw7n60RzKprxaZLvcRTDOaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpY +oJ2daZH9 +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA +# Subject: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA +# Label: "GlobalSign Root CA" +# Serial: 4835703278459707669005204 +# MD5 Fingerprint: 3e:45:52:15:09:51:92:e1:b7:5d:37:9f:b1:87:29:8a +# SHA1 Fingerprint: b1:bc:96:8b:d4:f4:9d:62:2a:a8:9a:81:f2:15:01:52:a4:1d:82:9c +# SHA256 Fingerprint: eb:d4:10:40:e4:bb:3e:c7:42:c9:e3:81:d3:1e:f2:a4:1a:48:b6:68:5c:96:e7:ce:f3:c1:df:6c:d4:33:1c:99 +-----BEGIN CERTIFICATE----- +MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG +A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv +b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw +MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i +YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT +aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ +jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp +xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp +1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG +snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ +U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8 +9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E +BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B +AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz +yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE +38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP +AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad +DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME +HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R2 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R2 +# Label: "GlobalSign Root CA - R2" +# Serial: 4835703278459682885658125 +# MD5 Fingerprint: 94:14:77:7e:3e:5e:fd:8f:30:bd:41:b0:cf:e7:d0:30 +# SHA1 Fingerprint: 75:e0:ab:b6:13:85:12:27:1c:04:f8:5f:dd:de:38:e4:b7:24:2e:fe +# SHA256 Fingerprint: ca:42:dd:41:74:5f:d0:b8:1e:b9:02:36:2c:f9:d8:bf:71:9d:a1:bd:1b:1e:fc:94:6f:5b:4c:99:f4:2c:1b:9e +-----BEGIN CERTIFICATE----- +MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G +A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp +Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1 +MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG +A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL +v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8 +eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq +tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd +C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa +zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB +mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH +V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n +bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG +3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs +J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO +291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS +ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd +AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 +TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== +-----END CERTIFICATE----- + +# Issuer: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 1 Policy Validation Authority +# Subject: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 1 Policy Validation Authority +# Label: "ValiCert Class 1 VA" +# Serial: 1 +# MD5 Fingerprint: 65:58:ab:15:ad:57:6c:1e:a8:a7:b5:69:ac:bf:ff:eb +# SHA1 Fingerprint: e5:df:74:3c:b6:01:c4:9b:98:43:dc:ab:8c:e8:6a:81:10:9f:e4:8e +# SHA256 Fingerprint: f4:c1:49:55:1a:30:13:a3:5b:c7:bf:fe:17:a7:f3:44:9b:c1:ab:5b:5a:0a:e7:4b:06:c2:3b:90:00:4c:01:04 +-----BEGIN CERTIFICATE----- +MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0 +IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz +BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y +aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG +9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIyMjM0OFoXDTE5MDYy +NTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y +azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs +YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw +Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl +cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9Y +LqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIiGQj4/xEjm84H9b9pGib+ +TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCmDuJWBQ8Y +TfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0 +LBwGlN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLW +I8sogTLDAHkY7FkXicnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPw +nXS3qT6gpf+2SQMT2iLM7XGCK5nPOrf1LXLI +-----END CERTIFICATE----- + +# Issuer: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 2 Policy Validation Authority +# Subject: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 2 Policy Validation Authority +# Label: "ValiCert Class 2 VA" +# Serial: 1 +# MD5 Fingerprint: a9:23:75:9b:ba:49:36:6e:31:c2:db:f2:e7:66:ba:87 +# SHA1 Fingerprint: 31:7a:2a:d0:7f:2b:33:5e:f5:a1:c3:4e:4b:57:e8:b7:d8:f1:fc:a6 +# SHA256 Fingerprint: 58:d0:17:27:9c:d4:dc:63:ab:dd:b1:96:a6:c9:90:6c:30:c4:e0:87:83:ea:e8:c1:60:99:54:d6:93:55:59:6b +-----BEGIN CERTIFICATE----- +MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0 +IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz +BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y +aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG +9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMTk1NFoXDTE5MDYy +NjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y +azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs +YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw +Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl +cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOOnHK5avIWZJV16vY +dA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVCCSRrCl6zfN1SLUzm1NZ9 +WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7RfZHM047QS +v4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9v +UJSZSWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTu +IYEZoDJJKPTEjlbVUjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwC +W/POuZ6lcg5Ktz885hZo+L7tdEy8W9ViH0Pd +-----END CERTIFICATE----- + +# Issuer: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 3 Policy Validation Authority +# Subject: CN=http://www.valicert.com/ O=ValiCert, Inc. OU=ValiCert Class 3 Policy Validation Authority +# Label: "RSA Root Certificate 1" +# Serial: 1 +# MD5 Fingerprint: a2:6f:53:b7:ee:40:db:4a:68:e7:fa:18:d9:10:4b:72 +# SHA1 Fingerprint: 69:bd:8c:f4:9c:d3:00:fb:59:2e:17:93:ca:55:6a:f3:ec:aa:35:fb +# SHA256 Fingerprint: bc:23:f9:8a:31:3c:b9:2d:e3:bb:fc:3a:5a:9f:44:61:ac:39:49:4c:4a:e1:5a:9e:9d:f1:31:e9:9b:73:01:9a +-----BEGIN CERTIFICATE----- +MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0 +IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz +BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y +aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG +9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMjIzM1oXDTE5MDYy +NjAwMjIzM1owgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y +azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs +YXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw +Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl +cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjmFGWHOjVsQaBalfD +cnWTq8+epvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td3zZxFJmP3MKS8edgkpfs +2Ejcv8ECIMYkpChMMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89HBFx1cQqY +JJgpp0lZpd34t0NiYfPT4tBVPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliE +Zwgs3x/be0kz9dNnnfS0ChCzycUs4pJqcXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJ +n0WuPIqpsHEzXcjFV9+vqDWzf4mH6eglkrh/hXqu1rweN1gqZ8mRzyqBPu3GOd/A +PhmcGcwTTYJBtYze4D1gCCAPRX5ron+jjBXu +-----END CERTIFICATE----- + +# Issuer: CN=VeriSign Class 3 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only +# Subject: CN=VeriSign Class 3 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only +# Label: "Verisign Class 3 Public Primary Certification Authority - G3" +# Serial: 206684696279472310254277870180966723415 +# MD5 Fingerprint: cd:68:b6:a7:c7:c4:ce:75:e0:1d:4f:57:44:61:92:09 +# SHA1 Fingerprint: 13:2d:0d:45:53:4b:69:97:cd:b2:d5:c3:39:e2:55:76:60:9b:5c:c6 +# SHA256 Fingerprint: eb:04:cf:5e:b1:f3:9a:fa:76:2f:2b:b1:20:f2:96:cb:a5:20:c1:b9:7d:b1:58:95:65:b8:1c:b9:a1:7b:72:44 +-----BEGIN CERTIFICATE----- +MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZl +cmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWdu +LCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlT +aWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQswCQYD +VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlT +aWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJ +bmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWdu +IENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg +LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMu6nFL8eB8aHm8b +N3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1EUGO+i2t +KmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGu +kxUccLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBm +CC+Vk7+qRy+oRpfwEuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJ +Xwzw3sJ2zq/3avL6QaaiMxTJ5Xpj055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWu +imi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAERSWwauSCPc/L8my/uRan2Te +2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5fj267Cz3qWhMe +DGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC +/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565p +F4ErWjfJXir0xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGt +TxzhT5yvDwyd93gN2PQ1VoDat20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ== +-----END CERTIFICATE----- + +# Issuer: CN=VeriSign Class 4 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only +# Subject: CN=VeriSign Class 4 Public Primary Certification Authority - G3 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 1999 VeriSign, Inc. - For authorized use only +# Label: "Verisign Class 4 Public Primary Certification Authority - G3" +# Serial: 314531972711909413743075096039378935511 +# MD5 Fingerprint: db:c8:f2:27:2e:b1:ea:6a:29:23:5d:fe:56:3e:33:df +# SHA1 Fingerprint: c8:ec:8c:87:92:69:cb:4b:ab:39:e9:8d:7e:57:67:f3:14:95:73:9d +# SHA256 Fingerprint: e3:89:36:0d:0f:db:ae:b3:d2:50:58:4b:47:30:31:4e:22:2f:39:c1:56:a0:20:14:4e:8d:96:05:61:79:15:06 +-----BEGIN CERTIFICATE----- +MIIEGjCCAwICEQDsoKeLbnVqAc/EfMwvlF7XMA0GCSqGSIb3DQEBBQUAMIHKMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZl +cmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWdu +LCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlT +aWduIENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQswCQYD +VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlT +aWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJ +bmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWdu +IENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg +LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK3LpRFpxlmr8Y+1 +GQ9Wzsy1HyDkniYlS+BzZYlZ3tCD5PUPtbut8XzoIfzk6AzufEUiGXaStBO3IFsJ ++mGuqPKljYXCKtbeZjbSmwL0qJJgfJxptI8kHtCGUvYynEFYHiK9zUVilQhu0Gbd +U6LM8BDcVHOLBKFGMzNcF0C5nk3T875Vg+ixiY5afJqWIpA7iCXy0lOIAgwLePLm +NxdLMEYH5IBtptiWLugs+BGzOA1mppvqySNb247i8xOOGlktqgLw7KSHZtzBP/XY +ufTsgsbSPZUd5cBPhMnZo0QoBmrXRazwa2rvTl/4EYIeOGM0ZlDUPpNz+jDDZq3/ +ky2X7wMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAj/ola09b5KROJ1WrIhVZPMq1 +CtRK26vdoV9TxaBXOcLORyu+OshWv8LZJxA6sQU8wHcxuzrTBXttmhwwjIDLk5Mq +g6sFUYICABFna/OIYUdfA5PVWw3g8dShMjWFsjrbsIKr0csKvE+MW8VLADsfKoKm +fjaF3H48ZwC15DtS4KjrXRX5xm3wrR0OhbepmnMUWluPQSjA1egtTaRezarZ7c7c +2NU8Qh0XwRJdRTjDOPP8hS6DRkiy1yBfkjaP53kPmF6Z6PDQpLv1U70qzlmwr25/ +bLvSHgCwIe34QWKCudiyxLtGUPMxxY8BqHTr9Xgn2uf3ZkPznoM+IKrDNWCRzg== +-----END CERTIFICATE----- + +# Issuer: CN=Entrust.net Secure Server Certification Authority O=Entrust.net OU=www.entrust.net/CPS incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Subject: CN=Entrust.net Secure Server Certification Authority O=Entrust.net OU=www.entrust.net/CPS incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Label: "Entrust.net Secure Server CA" +# Serial: 927650371 +# MD5 Fingerprint: df:f2:80:73:cc:f1:e6:61:73:fc:f5:42:e9:c5:7c:ee +# SHA1 Fingerprint: 99:a6:9b:e6:1a:fe:88:6b:4d:2b:82:00:7c:b8:54:fc:31:7e:15:39 +# SHA256 Fingerprint: 62:f2:40:27:8c:56:4c:4d:d8:bf:7d:9d:4f:6f:36:6e:a8:94:d2:2f:5f:34:d9:89:a9:83:ac:ec:2f:ff:ed:50 +-----BEGIN CERTIFICATE----- +MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMC +VVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5u +ZXQvQ1BTIGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMc +KGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDE6MDgGA1UEAxMxRW50cnVzdC5u +ZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05OTA1 +MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIGA1UE +ChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5j +b3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF +bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUg +U2VydmVyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUA +A4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQaO2f55M28Qpku0f1BBc/ +I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5gXpa0zf3 +wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OC +AdcwggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHb +oIHYpIHVMIHSMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5 +BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1p +dHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1pdGVk +MTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRp +b24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu +dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0 +MFqBDzIwMTkwNTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8Bdi +E1U9s/8KAGv7UISX8+1i0BowHQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAa +MAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI +hvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyNEwr75Ji174z4xRAN +95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9n9cd +2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI= +-----END CERTIFICATE----- + +# Issuer: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Subject: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited +# Label: "Entrust.net Premium 2048 Secure Server CA" +# Serial: 946059622 +# MD5 Fingerprint: ba:21:ea:20:d6:dd:db:8f:c1:57:8b:40:ad:a1:fc:fc +# SHA1 Fingerprint: 80:1d:62:d0:7b:44:9d:5c:5c:03:5c:98:ea:61:fa:44:3c:2a:58:fe +# SHA256 Fingerprint: d1:c3:39:ea:27:84:eb:87:0f:93:4f:c5:63:4e:4a:a9:ad:55:05:01:64:01:f2:64:65:d3:7a:57:46:63:35:9f +-----BEGIN CERTIFICATE----- +MIIEXDCCA0SgAwIBAgIEOGO5ZjANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChML +RW50cnVzdC5uZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBp +bmNvcnAuIGJ5IHJlZi4gKGxpbWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5 +IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQxNzUwNTFaFw0xOTEy +MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3 +LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp +YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG +A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq +K0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOLGp18EzoOH1u3Hs/lJBQe +sYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSrhRSGlVuX +MlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVT +XTzWnLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/ +HoZdenoVve8AjhUiVBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH +4QIDAQABo3QwcjARBglghkgBhvhCAQEEBAMCAAcwHwYDVR0jBBgwFoAUVeSB0RGA +vtiJuQijMfmhJAkWuXAwHQYDVR0OBBYEFFXkgdERgL7YibkIozH5oSQJFrlwMB0G +CSqGSIb2fQdBAAQQMA4bCFY1LjA6NC4wAwIEkDANBgkqhkiG9w0BAQUFAAOCAQEA +WUesIYSKF8mciVMeuoCFGsY8Tj6xnLZ8xpJdGGQC49MGCBFhfGPjK50xA3B20qMo +oPS7mmNz7W3lKtvtFKkrxjYR0CvrB4ul2p5cGZ1WEvVUKcgF7bISKo30Axv/55IQ +h7A6tcOdBTcSo8f0FbnVpDkWm1M6I5HxqIKiaohowXkCIryqptau37AUX7iH0N18 +f3v/rxzP5tsHrV7bhZ3QKw0z2wTR5klAEyt2+z7pnIkPFc4YsIV4IU9rTw76NmfN +B/L/CNDi3tm/Kq+4h4YhPATKt5Rof8886ZjXOP/swNlQ8C5LWK5Gb9Auw2DaclVy +vUxFnmG6v4SBkgPR0ml8xQ== +-----END CERTIFICATE----- + +# Issuer: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust +# Subject: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust +# Label: "Baltimore CyberTrust Root" +# Serial: 33554617 +# MD5 Fingerprint: ac:b6:94:a5:9c:17:e0:d7:91:52:9b:b1:97:06:a6:e4 +# SHA1 Fingerprint: d4:de:20:d0:5e:66:fc:53:fe:1a:50:88:2c:78:db:28:52:ca:e4:74 +# SHA256 Fingerprint: 16:af:57:a9:f6:76:b0:ab:12:60:95:aa:5e:ba:de:f2:2a:b3:11:19:d6:44:ac:95:cd:4b:93:db:f3:f2:6a:eb +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ +RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD +VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX +DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y +ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy +VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr +mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr +IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK +mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu +XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy +dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye +jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1 +BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3 +DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92 +9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx +jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0 +Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz +ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS +R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp +-----END CERTIFICATE----- + +# Issuer: CN=Equifax Secure Global eBusiness CA-1 O=Equifax Secure Inc. +# Subject: CN=Equifax Secure Global eBusiness CA-1 O=Equifax Secure Inc. +# Label: "Equifax Secure Global eBusiness CA" +# Serial: 1 +# MD5 Fingerprint: 8f:5d:77:06:27:c4:98:3c:5b:93:78:e7:d7:7d:9b:cc +# SHA1 Fingerprint: 7e:78:4a:10:1c:82:65:cc:2d:e1:f1:6d:47:b4:40:ca:d9:0a:19:45 +# SHA256 Fingerprint: 5f:0b:62:ea:b5:e3:53:ea:65:21:65:16:58:fb:b6:53:59:f4:43:28:0a:4a:fb:d1:04:d7:7d:10:f9:f0:4c:07 +-----BEGIN CERTIFICATE----- +MIICkDCCAfmgAwIBAgIBATANBgkqhkiG9w0BAQQFADBaMQswCQYDVQQGEwJVUzEc +MBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5jLjEtMCsGA1UEAxMkRXF1aWZheCBT +ZWN1cmUgR2xvYmFsIGVCdXNpbmVzcyBDQS0xMB4XDTk5MDYyMTA0MDAwMFoXDTIw +MDYyMTA0MDAwMFowWjELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0VxdWlmYXggU2Vj +dXJlIEluYy4xLTArBgNVBAMTJEVxdWlmYXggU2VjdXJlIEdsb2JhbCBlQnVzaW5l +c3MgQ0EtMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuucXkAJlsTRVPEnC +UdXfp9E3j9HngXNBUmCbnaEXJnitx7HoJpQytd4zjTov2/KaelpzmKNc6fuKcxtc +58O/gGzNqfTWK8D3+ZmqY6KxRwIP1ORROhI8bIpaVIRw28HFkM9yRcuoWcDNM50/ +o5brhTMhHD4ePmBudpxnhcXIw2ECAwEAAaNmMGQwEQYJYIZIAYb4QgEBBAQDAgAH +MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUvqigdHJQa0S3ySPY+6j/s1dr +aGwwHQYDVR0OBBYEFL6ooHRyUGtEt8kj2Puo/7NXa2hsMA0GCSqGSIb3DQEBBAUA +A4GBADDiAVGqx+pf2rnQZQ8w1j7aDRRJbpGTJxQx78T3LUX47Me/okENI7SS+RkA +Z70Br83gcfxaz2TE4JaY0KNA4gGK7ycH8WUBikQtBmV1UsCGECAhX2xrD2yuCRyv +8qIYNMR1pHMc8Y3c7635s3a0kr/clRAevsvIO1qEYBlWlKlV +-----END CERTIFICATE----- + +# Issuer: CN=Equifax Secure eBusiness CA-1 O=Equifax Secure Inc. +# Subject: CN=Equifax Secure eBusiness CA-1 O=Equifax Secure Inc. +# Label: "Equifax Secure eBusiness CA 1" +# Serial: 4 +# MD5 Fingerprint: 64:9c:ef:2e:44:fc:c6:8f:52:07:d0:51:73:8f:cb:3d +# SHA1 Fingerprint: da:40:18:8b:91:89:a3:ed:ee:ae:da:97:fe:2f:9d:f5:b7:d1:8a:41 +# SHA256 Fingerprint: cf:56:ff:46:a4:a1:86:10:9d:d9:65:84:b5:ee:b5:8a:51:0c:42:75:b0:e5:f9:4f:40:bb:ae:86:5e:19:f6:73 +-----BEGIN CERTIFICATE----- +MIICgjCCAeugAwIBAgIBBDANBgkqhkiG9w0BAQQFADBTMQswCQYDVQQGEwJVUzEc +MBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBT +ZWN1cmUgZUJ1c2luZXNzIENBLTEwHhcNOTkwNjIxMDQwMDAwWhcNMjAwNjIxMDQw +MDAwWjBTMQswCQYDVQQGEwJVUzEcMBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5j +LjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNzIENBLTEwgZ8wDQYJ +KoZIhvcNAQEBBQADgY0AMIGJAoGBAM4vGbwXt3fek6lfWg0XTzQaDJj0ItlZ1MRo +RvC0NcWFAyDGr0WlIVFFQesWWDYyb+JQYmT5/VGcqiTZ9J2DKocKIdMSODRsjQBu +WqDZQu4aIZX5UkxVWsUPOE9G+m34LjXWHXzr4vCwdYDIqROsvojvOm6rXyo4YgKw +Env+j6YDAgMBAAGjZjBkMBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTAD +AQH/MB8GA1UdIwQYMBaAFEp4MlIR21kWNl7fwRQ2QGpHfEyhMB0GA1UdDgQWBBRK +eDJSEdtZFjZe38EUNkBqR3xMoTANBgkqhkiG9w0BAQQFAAOBgQB1W6ibAxHm6VZM +zfmpTMANmvPMZWnmJXbMWbfWVMMdzZmsGd20hdXgPfxiIKeES1hl8eL5lSE/9dR+ +WB5Hh1Q+WKG1tfgq73HnvMP2sUlG4tega+VWeponmHxGYhTnyfxuAxJ5gDgdSIKN +/Bf+KpYrtWKmpj29f5JZzVoqgrI3eQ== +-----END CERTIFICATE----- + +# Issuer: O=Equifax Secure OU=Equifax Secure eBusiness CA-2 +# Subject: O=Equifax Secure OU=Equifax Secure eBusiness CA-2 +# Label: "Equifax Secure eBusiness CA 2" +# Serial: 930140085 +# MD5 Fingerprint: aa:bf:bf:64:97:da:98:1d:6f:c6:08:3a:95:70:33:ca +# SHA1 Fingerprint: 39:4f:f6:85:0b:06:be:52:e5:18:56:cc:10:e1:80:e8:82:b3:85:cc +# SHA256 Fingerprint: 2f:27:4e:48:ab:a4:ac:7b:76:59:33:10:17:75:50:6d:c3:0e:e3:8e:f6:ac:d5:c0:49:32:cf:e0:41:23:42:20 +-----BEGIN CERTIFICATE----- +MIIDIDCCAomgAwIBAgIEN3DPtTANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV +UzEXMBUGA1UEChMORXF1aWZheCBTZWN1cmUxJjAkBgNVBAsTHUVxdWlmYXggU2Vj +dXJlIGVCdXNpbmVzcyBDQS0yMB4XDTk5MDYyMzEyMTQ0NVoXDTE5MDYyMzEyMTQ0 +NVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkVxdWlmYXggU2VjdXJlMSYwJAYD +VQQLEx1FcXVpZmF4IFNlY3VyZSBlQnVzaW5lc3MgQ0EtMjCBnzANBgkqhkiG9w0B +AQEFAAOBjQAwgYkCgYEA5Dk5kx5SBhsoNviyoynF7Y6yEb3+6+e0dMKP/wXn2Z0G +vxLIPw7y1tEkshHe0XMJitSxLJgJDR5QRrKDpkWNYmi7hRsgcDKqQM2mll/EcTc/ +BPO3QSQ5BxoeLmFYoBIL5aXfxavqN3HMHMg3OrmXUqesxWoklE6ce8/AatbfIb0C +AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEX +MBUGA1UEChMORXF1aWZheCBTZWN1cmUxJjAkBgNVBAsTHUVxdWlmYXggU2VjdXJl +IGVCdXNpbmVzcyBDQS0yMQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTkw +NjIzMTIxNDQ1WjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUUJ4L6q9euSBIplBq +y/3YIHqngnYwHQYDVR0OBBYEFFCeC+qvXrkgSKZQasv92CB6p4J2MAwGA1UdEwQF +MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA +A4GBAAyGgq3oThr1jokn4jVYPSm0B482UJW/bsGe68SQsoWou7dC4A8HOd/7npCy +0cE+U58DRLB+S/Rv5Hwf5+Kx5Lia78O9zt4LMjTZ3ijtM2vE1Nc9ElirfQkty3D1 +E4qUoSek1nDFbZS1yX2doNLGCEnZZpum0/QL3MUmV+GRMOrN +-----END CERTIFICATE----- + +# Issuer: CN=AddTrust Class 1 CA Root O=AddTrust AB OU=AddTrust TTP Network +# Subject: CN=AddTrust Class 1 CA Root O=AddTrust AB OU=AddTrust TTP Network +# Label: "AddTrust Low-Value Services Root" +# Serial: 1 +# MD5 Fingerprint: 1e:42:95:02:33:92:6b:b9:5f:c0:7f:da:d6:b2:4b:fc +# SHA1 Fingerprint: cc:ab:0e:a0:4c:23:01:d6:69:7b:dd:37:9f:cd:12:eb:24:e3:94:9d +# SHA256 Fingerprint: 8c:72:09:27:9a:c0:4e:27:5e:16:d0:7f:d3:b7:75:e8:01:54:b5:96:80:46:e3:1f:52:dd:25:76:63:24:e9:a7 +-----BEGIN CERTIFICATE----- +MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJTRTEU +MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3 +b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwHhcNMDAwNTMw +MTAzODMxWhcNMjAwNTMwMTAzODMxWjBlMQswCQYDVQQGEwJTRTEUMBIGA1UEChML +QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYD +VQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUA +A4IBDwAwggEKAoIBAQCWltQhSWDia+hBBwzexODcEyPNwTXH+9ZOEQpnXvUGW2ul +CDtbKRY654eyNAbFvAWlA3yCyykQruGIgb3WntP+LVbBFc7jJp0VLhD7Bo8wBN6n +tGO0/7Gcrjyvd7ZWxbWroulpOj0OM3kyP3CCkplhbY0wCI9xP6ZIVxn4JdxLZlyl +dI+Yrsj5wAYi56xz36Uu+1LcsRVlIPo1Zmne3yzxbrww2ywkEtvrNTVokMsAsJch +PXQhI2U0K7t4WaPW4XY5mqRJjox0r26kmqPZm9I4XJuiGMx1I4S+6+JNM3GOGvDC ++Mcdoq0Dlyz4zyXG9rgkMbFjXZJ/Y/AlyVMuH79NAgMBAAGjgdIwgc8wHQYDVR0O +BBYEFJWxtPCUtr3H2tERCSG+wa9J/RB7MAsGA1UdDwQEAwIBBjAPBgNVHRMBAf8E +BTADAQH/MIGPBgNVHSMEgYcwgYSAFJWxtPCUtr3H2tERCSG+wa9J/RB7oWmkZzBl +MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFk +ZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENB +IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBACxtZBsfzQ3duQH6lmM0MkhHma6X +7f1yFqZzR1r0693p9db7RcwpiURdv0Y5PejuvE1Uhh4dbOMXJ0PhiVYrqW9yTkkz +43J8KiOavD7/KCrto/8cI7pDVwlnTUtiBi34/2ydYB7YHEt9tTEv2dB8Xfjea4MY +eDdXL+gzB2ffHsdrKpV2ro9Xo/D0UrSpUwjP4E/TelOL/bscVjby/rK25Xa71SJl +pz/+0WatC7xrmYbvP33zGDLKe8bjq2RGlfgmadlVg3sslgf/WSxEo8bl6ancoWOA +WiFeIc9TVPC6b4nbqKqVz4vjccweGyBECMB6tkD9xOQ14R0WHNC8K47Wcdk= +-----END CERTIFICATE----- + +# Issuer: CN=AddTrust External CA Root O=AddTrust AB OU=AddTrust External TTP Network +# Subject: CN=AddTrust External CA Root O=AddTrust AB OU=AddTrust External TTP Network +# Label: "AddTrust External Root" +# Serial: 1 +# MD5 Fingerprint: 1d:35:54:04:85:78:b0:3f:42:42:4d:bf:20:73:0a:3f +# SHA1 Fingerprint: 02:fa:f3:e2:91:43:54:68:60:78:57:69:4d:f5:e4:5b:68:85:18:68 +# SHA256 Fingerprint: 68:7f:a4:51:38:22:78:ff:f0:c8:b1:1f:8d:43:d5:76:67:1c:6e:b2:bc:ea:b4:13:fb:83:d9:65:d0:6d:2f:f2 +-----BEGIN CERTIFICATE----- +MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEU +MBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFs +IFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290 +MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFowbzELMAkGA1UEBhMCU0Ux +FDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRUcnVzdCBFeHRlcm5h +bCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0EgUm9v +dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvt +H7xsD821+iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9 +uMq/NzgtHj6RQa1wVsfwTz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzX +mk6vBbOmcZSccbNQYArHE504B4YCqOmoaSYYkKtMsE8jqzpPhNjfzp/haW+710LX +a0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy2xSoRcRdKn23tNbE7qzN +E0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv77+ldU9U0 +WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYD +VR0PBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0 +Jvf6xCZU7wO94CTLVBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRU +cnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsx +IjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3SCAQEwDQYJKoZIhvcN +AQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZlj7DYd7usQWxH +YINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 +6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvC +Nr4TDea9Y355e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEX +c4g/VhsxOBi0cQ+azcgOno4uG+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5a +mnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= +-----END CERTIFICATE----- + +# Issuer: CN=AddTrust Public CA Root O=AddTrust AB OU=AddTrust TTP Network +# Subject: CN=AddTrust Public CA Root O=AddTrust AB OU=AddTrust TTP Network +# Label: "AddTrust Public Services Root" +# Serial: 1 +# MD5 Fingerprint: c1:62:3e:23:c5:82:73:9c:03:59:4b:2b:e9:77:49:7f +# SHA1 Fingerprint: 2a:b6:28:48:5e:78:fb:f3:ad:9e:79:10:dd:6b:df:99:72:2c:96:e5 +# SHA256 Fingerprint: 07:91:ca:07:49:b2:07:82:aa:d3:c7:d7:bd:0c:df:c9:48:58:35:84:3e:b2:d7:99:60:09:ce:43:ab:6c:69:27 +-----BEGIN CERTIFICATE----- +MIIEFTCCAv2gAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJTRTEU +MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3 +b3JrMSAwHgYDVQQDExdBZGRUcnVzdCBQdWJsaWMgQ0EgUm9vdDAeFw0wMDA1MzAx +MDQxNTBaFw0yMDA1MzAxMDQxNTBaMGQxCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtB +ZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5ldHdvcmsxIDAeBgNV +BAMTF0FkZFRydXN0IFB1YmxpYyBDQSBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEA6Rowj4OIFMEg2Dybjxt+A3S72mnTRqX4jsIMEZBRpS9mVEBV +6tsfSlbunyNu9DnLoblv8n75XYcmYZ4c+OLspoH4IcUkzBEMP9smcnrHAZcHF/nX +GCwwfQ56HmIexkvA/X1id9NEHif2P0tEs7c42TkfYNVRknMDtABp4/MUTu7R3AnP +dzRGULD4EfL+OHn3Bzn+UZKXC1sIXzSGAa2Il+tmzV7R/9x98oTaunet3IAIx6eH +1lWfl2royBFkuucZKT8Rs3iQhCBSWxHveNCD9tVIkNAwHM+A+WD+eeSI8t0A65RF +62WUaUC6wNW0uLp9BBGo6zEFlpROWCGOn9Bg/QIDAQABo4HRMIHOMB0GA1UdDgQW +BBSBPjfYkrAfd59ctKtzquf2NGAv+jALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/BAUw +AwEB/zCBjgYDVR0jBIGGMIGDgBSBPjfYkrAfd59ctKtzquf2NGAv+qFopGYwZDEL +MAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRU +cnVzdCBUVFAgTmV0d29yazEgMB4GA1UEAxMXQWRkVHJ1c3QgUHVibGljIENBIFJv +b3SCAQEwDQYJKoZIhvcNAQEFBQADggEBAAP3FUr4JNojVhaTdt02KLmuG7jD8WS6 +IBh4lSknVwW8fCr0uVFV2ocC3g8WFzH4qnkuCRO7r7IgGRLlk/lL+YPoRNWyQSW/ +iHVv/xD8SlTQX/D67zZzfRs2RcYhbbQVuE7PnFylPVoAjgbjPGsye/Kf8Lb93/Ao +GEjwxrzQvzSAlsJKsW2Ox5BF3i9nrEUEo3rcVZLJR2bYGozH7ZxOmuASu7VqTITh +4SINhwBk/ox9Yjllpu9CtoAlEmEBqCQTcAARJl/6NVDFSMwGR+gn2HCNX2TmoUQm +XiLsks3/QppEIW1cxeMiHV9HEufOX1362KqxMy3ZdvJOOjMMK7MtkAY= +-----END CERTIFICATE----- + +# Issuer: CN=AddTrust Qualified CA Root O=AddTrust AB OU=AddTrust TTP Network +# Subject: CN=AddTrust Qualified CA Root O=AddTrust AB OU=AddTrust TTP Network +# Label: "AddTrust Qualified Certificates Root" +# Serial: 1 +# MD5 Fingerprint: 27:ec:39:47:cd:da:5a:af:e2:9a:01:65:21:a9:4c:bb +# SHA1 Fingerprint: 4d:23:78:ec:91:95:39:b5:00:7f:75:8f:03:3b:21:1e:c5:4d:8b:cf +# SHA256 Fingerprint: 80:95:21:08:05:db:4b:bc:35:5e:44:28:d8:fd:6e:c2:cd:e3:ab:5f:b9:7a:99:42:98:8e:b8:f4:dc:d0:60:16 +-----BEGIN CERTIFICATE----- +MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJTRTEU +MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3 +b3JrMSMwIQYDVQQDExpBZGRUcnVzdCBRdWFsaWZpZWQgQ0EgUm9vdDAeFw0wMDA1 +MzAxMDQ0NTBaFw0yMDA1MzAxMDQ0NTBaMGcxCzAJBgNVBAYTAlNFMRQwEgYDVQQK +EwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5ldHdvcmsxIzAh +BgNVBAMTGkFkZFRydXN0IFF1YWxpZmllZCBDQSBSb290MIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEA5B6a/twJWoekn0e+EV+vhDTbYjx5eLfpMLXsDBwq +xBb/4Oxx64r1EW7tTw2R0hIYLUkVAcKkIhPHEWT/IhKauY5cLwjPcWqzZwFZ8V1G +87B4pfYOQnrjfxvM0PC3KP0q6p6zsLkEqv32x7SxuCqg+1jxGaBvcCV+PmlKfw8i +2O+tCBGaKZnhqkRFmhJePp1tUvznoD1oL/BLcHwTOK28FSXx1s6rosAx1i+f4P8U +WfyEk9mHfExUE+uf0S0R+Bg6Ot4l2ffTQO2kBhLEO+GRwVY18BTcZTYJbqukB8c1 +0cIDMzZbdSZtQvESa0NvS3GU+jQd7RNuyoB/mC9suWXY6QIDAQABo4HUMIHRMB0G +A1UdDgQWBBQ5lYtii1zJ1IC6WA+XPxUIQ8yYpzALBgNVHQ8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zCBkQYDVR0jBIGJMIGGgBQ5lYtii1zJ1IC6WA+XPxUIQ8yYp6Fr +pGkwZzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQL +ExRBZGRUcnVzdCBUVFAgTmV0d29yazEjMCEGA1UEAxMaQWRkVHJ1c3QgUXVhbGlm +aWVkIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBABmrder4i2VhlRO6aQTv +hsoToMeqT2QbPxj2qC0sVY8FtzDqQmodwCVRLae/DLPt7wh/bDxGGuoYQ992zPlm +hpwsaPXpF/gxsxjE1kh9I0xowX67ARRvxdlu3rsEQmr49lx95dr6h+sNNVJn0J6X +dgWTP5XHAeZpVTh/EGGZyeNfpso+gmNIquIISD6q8rKFYqa0p9m9N5xotS1WfbC3 +P6CxB9bpT9zeRXEwMn8bLgn5v1Kh7sKAPgZcLlVAwRv1cEWw3F369nJad9Jjzc9Y +iQBCYz95OdBEsIJuQRno3eDBiFrRHnGTHyQwdOUeqN48Jzd/g66ed8/wMLH/S5no +xqE= +-----END CERTIFICATE----- + +# Issuer: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc. +# Subject: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc. +# Label: "Entrust Root Certification Authority" +# Serial: 1164660820 +# MD5 Fingerprint: d6:a5:c3:ed:5d:dd:3e:00:c1:3d:87:92:1f:1d:3f:e4 +# SHA1 Fingerprint: b3:1e:b1:b7:40:e3:6c:84:02:da:dc:37:d4:4d:f5:d4:67:49:52:f9 +# SHA256 Fingerprint: 73:c1:76:43:4f:1b:c6:d5:ad:f4:5b:0e:76:e7:27:28:7c:8d:e5:76:16:c1:e6:e6:14:1a:2b:2c:bc:7d:8e:4c +-----BEGIN CERTIFICATE----- +MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC +VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0 +Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW +KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl +cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw +NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw +NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy +ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV +BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo +Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4 +4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9 +KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI +rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi +94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB +sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi +gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo +kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE +vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA +A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t +O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua +AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP +9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/ +eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m +0vdXcDazv/wor3ElhVsT/h5/WrQ8 +-----END CERTIFICATE----- + +# Issuer: CN=GeoTrust Global CA O=GeoTrust Inc. +# Subject: CN=GeoTrust Global CA O=GeoTrust Inc. +# Label: "GeoTrust Global CA" +# Serial: 144470 +# MD5 Fingerprint: f7:75:ab:29:fb:51:4e:b7:77:5e:ff:05:3c:99:8e:f5 +# SHA1 Fingerprint: de:28:f4:a4:ff:e5:b9:2f:a3:c5:03:d1:a3:49:a7:f9:96:2a:82:12 +# SHA256 Fingerprint: ff:85:6a:2d:25:1d:cd:88:d3:66:56:f4:50:12:67:98:cf:ab:aa:de:40:79:9c:72:2d:e4:d2:b5:db:36:a7:3a +-----BEGIN CERTIFICATE----- +MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT +MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i +YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG +EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg +R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9 +9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq +fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv +iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU +1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+ +bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW +MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA +ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l +uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn +Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS +tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF +PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un +hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV +5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw== +-----END CERTIFICATE----- + +# Issuer: CN=GeoTrust Global CA 2 O=GeoTrust Inc. +# Subject: CN=GeoTrust Global CA 2 O=GeoTrust Inc. +# Label: "GeoTrust Global CA 2" +# Serial: 1 +# MD5 Fingerprint: 0e:40:a7:6c:de:03:5d:8f:d1:0f:e4:d1:8d:f9:6c:a9 +# SHA1 Fingerprint: a9:e9:78:08:14:37:58:88:f2:05:19:b0:6d:2b:0d:2b:60:16:90:7d +# SHA256 Fingerprint: ca:2d:82:a0:86:77:07:2f:8a:b6:76:4f:f0:35:67:6c:fe:3e:5e:32:5e:01:21:72:df:3f:92:09:6d:b7:9b:85 +-----BEGIN CERTIFICATE----- +MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBEMQswCQYDVQQGEwJVUzEW +MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFs +IENBIDIwHhcNMDQwMzA0MDUwMDAwWhcNMTkwMzA0MDUwMDAwWjBEMQswCQYDVQQG +EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3Qg +R2xvYmFsIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDvPE1A +PRDfO1MA4Wf+lGAVPoWI8YkNkMgoI5kF6CsgncbzYEbYwbLVjDHZ3CB5JIG/NTL8 +Y2nbsSpr7iFY8gjpeMtvy/wWUsiRxP89c96xPqfCfWbB9X5SJBri1WeR0IIQ13hL +TytCOb1kLUCgsBDTOEhGiKEMuzozKmKY+wCdE1l/bztyqu6mD4b5BWHqZ38MN5aL +5mkWRxHCJ1kDs6ZgwiFAVvqgx306E+PsV8ez1q6diYD3Aecs9pYrEw15LNnA5IZ7 +S4wMcoKK+xfNAGw6EzywhIdLFnopsk/bHdQL82Y3vdj2V7teJHq4PIu5+pIaGoSe +2HSPqht/XvT+RSIhAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE +FHE4NvICMVNHK266ZUapEBVYIAUJMB8GA1UdIwQYMBaAFHE4NvICMVNHK266ZUap +EBVYIAUJMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQUFAAOCAQEAA/e1K6td +EPx7srJerJsOflN4WT5CBP51o62sgU7XAotexC3IUnbHLB/8gTKY0UvGkpMzNTEv +/NgdRN3ggX+d6YvhZJFiCzkIjKx0nVnZellSlxG5FntvRdOW2TF9AjYPnDtuzywN +A0ZF66D0f0hExghAzN4bcLUprbqLOzRldRtxIR0sFAqwlpW41uryZfspuk/qkZN0 +abby/+Ea0AzRdoXLiiW9l14sbxWZJue2Kf8i7MkCx1YAzUm5s2x7UwQa4qjJqhIF +I8LO57sEAszAR6LkxCkvW0VXiVHuPOtSCP8HNR6fNWpHSlaY0VqFH4z1Ir+rzoPz +4iIprn2DQKi6bA== +-----END CERTIFICATE----- + +# Issuer: CN=GeoTrust Universal CA O=GeoTrust Inc. +# Subject: CN=GeoTrust Universal CA O=GeoTrust Inc. +# Label: "GeoTrust Universal CA" +# Serial: 1 +# MD5 Fingerprint: 92:65:58:8b:a2:1a:31:72:73:68:5c:b4:a5:7a:07:48 +# SHA1 Fingerprint: e6:21:f3:35:43:79:05:9a:4b:68:30:9d:8a:2f:74:22:15:87:ec:79 +# SHA256 Fingerprint: a0:45:9b:9f:63:b2:25:59:f5:fa:5d:4c:6d:b3:f9:f7:2f:f1:93:42:03:35:78:f0:73:bf:1d:1b:46:cb:b9:12 +-----BEGIN CERTIFICATE----- +MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEW +MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVy +c2FsIENBMB4XDTA0MDMwNDA1MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UE +BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xHjAcBgNVBAMTFUdlb1RydXN0 +IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKYV +VaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9tJPi8 +cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTT +QjOgNB0eRXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFh +F7em6fgemdtzbvQKoiFs7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2v +c7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d8Lsrlh/eezJS/R27tQahsiFepdaVaH/w +mZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7VqnJNk22CDtucvc+081xd +VHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3CgaRr0BHdCX +teGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZ +f9hBZ3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfRe +Bi9Fi1jUIxaS5BZuKGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+ +nhutxx9z3SxPGWX9f5NAEC7S8O08ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB +/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0XG0D08DYj3rWMB8GA1UdIwQY +MBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG +9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc +aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fX +IwjhmF7DWgh2qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzyn +ANXH/KttgCJwpQzgXQQpAvvLoJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0z +uzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsKxr2EoyNB3tZ3b4XUhRxQ4K5RirqN +Pnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxFKyDuSN/n3QmOGKja +QI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2DFKW +koRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9 +ER/frslKxfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQt +DF4JbAiXfKM9fJP/P6EUp8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/Sfuvm +bJxPgWp6ZKy7PtXny3YuxadIwVyQD8vIP/rmMuGNG2+k5o7Y+SlIis5z/iw= +-----END CERTIFICATE----- + +# Issuer: CN=GeoTrust Universal CA 2 O=GeoTrust Inc. +# Subject: CN=GeoTrust Universal CA 2 O=GeoTrust Inc. +# Label: "GeoTrust Universal CA 2" +# Serial: 1 +# MD5 Fingerprint: 34:fc:b8:d0:36:db:9e:14:b3:c2:f2:db:8f:e4:94:c7 +# SHA1 Fingerprint: 37:9a:19:7b:41:85:45:35:0c:a6:03:69:f3:3c:2e:af:47:4f:20:79 +# SHA256 Fingerprint: a0:23:4f:3b:c8:52:7c:a5:62:8e:ec:81:ad:5d:69:89:5d:a5:68:0d:c9:1d:1c:b8:47:7f:33:f8:78:b9:5b:0b +-----BEGIN CERTIFICATE----- +MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEW +MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVy +c2FsIENBIDIwHhcNMDQwMzA0MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYD +VQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1 +c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC +AQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0DE81 +WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUG +FF+3Qs17j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdq +XbboW0W63MOhBW9Wjo8QJqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxL +se4YuU6W3Nx2/zu+z18DwPw76L5GG//aQMJS9/7jOvdqdzXQ2o3rXhhqMcceujwb +KNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2WP0+GfPtDCapkzj4T8Fd +IgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP20gaXT73 +y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRt +hAAnZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgoc +QIgfksILAAX/8sgCSqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4 +Lt1ZrtmhN79UNdxzMk+MBB4zsslG8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAfBgNV +HSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8EBAMCAYYwDQYJ +KoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z +dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQ +L1EuxBRa3ugZ4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgr +Fg5fNuH8KrUwJM/gYwx7WBr+mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSo +ag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpqA1Ihn0CoZ1Dy81of398j9tx4TuaY +T1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpgY+RdM4kX2TGq2tbz +GDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiPpm8m +1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJV +OCiNUW7dFGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH +6aLcr34YEoP9VhdBLtUpgn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwX +QMAJKOSLakhT2+zNVVXxxvjpoixMptEmX36vWkzaH6byHCx+rgIW0lbQL1dTR+iS +-----END CERTIFICATE----- + +# Issuer: CN=America Online Root Certification Authority 1 O=America Online Inc. +# Subject: CN=America Online Root Certification Authority 1 O=America Online Inc. +# Label: "America Online Root Certification Authority 1" +# Serial: 1 +# MD5 Fingerprint: 14:f1:08:ad:9d:fa:64:e2:89:e7:1c:cf:a8:ad:7d:5e +# SHA1 Fingerprint: 39:21:c1:15:c1:5d:0e:ca:5c:cb:5b:c4:f0:7d:21:d8:05:0b:56:6a +# SHA256 Fingerprint: 77:40:73:12:c6:3a:15:3d:5b:c0:0b:4e:51:75:9c:df:da:c2:37:dc:2a:33:b6:79:46:e9:8e:9b:fa:68:0a:e3 +-----BEGIN CERTIFICATE----- +MIIDpDCCAoygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEc +MBoGA1UEChMTQW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBP +bmxpbmUgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAxMB4XDTAyMDUyODA2 +MDAwMFoXDTM3MTExOTIwNDMwMFowYzELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0Ft +ZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2EgT25saW5lIFJvb3Qg +Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMTCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAKgv6KRpBgNHw+kqmP8ZonCaxlCyfqXfaE0bfA+2l2h9LaaLl+lk +hsmj76CGv2BlnEtUiMJIxUo5vxTjWVXlGbR0yLQFOVwWpeKVBeASrlmLojNoWBym +1BW32J/X3HGrfpq/m44zDyL9Hy7nBzbvYjnF3cu6JRQj3gzGPTzOggjmZj7aUTsW +OqMFf6Dch9Wc/HKpoH145LcxVR5lu9RhsCFg7RAycsWSJR74kEoYeEfffjA3PlAb +2xzTa5qGUwew76wGePiEmf4hjUyAtgyC9mZweRrTT6PP8c9GsEsPPt2IYriMqQko +O3rHl+Ee5fSfwMCuJKDIodkP1nsmgmkyPacCAwEAAaNjMGEwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUAK3Zo/Z59m50qX8zPYEX10zPM94wHwYDVR0jBBgwFoAU +AK3Zo/Z59m50qX8zPYEX10zPM94wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB +BQUAA4IBAQB8itEfGDeC4Liwo+1WlchiYZwFos3CYiZhzRAW18y0ZTTQEYqtqKkF +Zu90821fnZmv9ov761KyBZiibyrFVL0lvV+uyIbqRizBs73B6UlwGBaXCBOMIOAb +LjpHyx7kADCVW/RFo8AasAFOq73AI25jP4BKxQft3OJvx8Fi8eNy1gTIdGcL+oir +oQHIb/AUr9KZzVGTfu0uOMe9zkZQPXLjeSWdm4grECDdpbgyn43gKd8hdIaC2y+C +MMbHNYaz+ZZfRtsMRf3zUMNvxsNIrUam4SdHCh0Om7bCd39j8uB9Gr784N/Xx6ds +sPmuujz9dLQR6FgNgLzTqIA6me11zEZ7 +-----END CERTIFICATE----- + +# Issuer: CN=America Online Root Certification Authority 2 O=America Online Inc. +# Subject: CN=America Online Root Certification Authority 2 O=America Online Inc. +# Label: "America Online Root Certification Authority 2" +# Serial: 1 +# MD5 Fingerprint: d6:ed:3c:ca:e2:66:0f:af:10:43:0d:77:9b:04:09:bf +# SHA1 Fingerprint: 85:b5:ff:67:9b:0c:79:96:1f:c8:6e:44:22:00:46:13:db:17:92:84 +# SHA256 Fingerprint: 7d:3b:46:5a:60:14:e5:26:c0:af:fc:ee:21:27:d2:31:17:27:ad:81:1c:26:84:2d:00:6a:f3:73:06:cc:80:bd +-----BEGIN CERTIFICATE----- +MIIFpDCCA4ygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEc +MBoGA1UEChMTQW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBP +bmxpbmUgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyODA2 +MDAwMFoXDTM3MDkyOTE0MDgwMFowYzELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0Ft +ZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2EgT25saW5lIFJvb3Qg +Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIP +ADCCAgoCggIBAMxBRR3pPU0Q9oyxQcngXssNt79Hc9PwVU3dxgz6sWYFas14tNwC +206B89enfHG8dWOgXeMHDEjsJcQDIPT/DjsS/5uN4cbVG7RtIuOx238hZK+GvFci +KtZHgVdEglZTvYYUAQv8f3SkWq7xuhG1m1hagLQ3eAkzfDJHA1zEpYNI9FdWboE2 +JxhP7JsowtS013wMPgwr38oE18aO6lhOqKSlGBxsRZijQdEt0sdtjRnxrXm3gT+9 +BoInLRBYBbV4Bbkv2wxrkJB+FFk4u5QkE+XRnRTf04JNRvCAOVIyD+OEsnpD8l7e +Xz8d3eOyG6ChKiMDbi4BFYdcpnV1x5dhvt6G3NRI270qv0pV2uh9UPu0gBe4lL8B +PeraunzgWGcXuVjgiIZGZ2ydEEdYMtA1fHkqkKJaEBEjNa0vzORKW6fIJ/KD3l67 +Xnfn6KVuY8INXWHQjNJsWiEOyiijzirplcdIz5ZvHZIlyMbGwcEMBawmxNJ10uEq +Z8A9W6Wa6897GqidFEXlD6CaZd4vKL3Ob5Rmg0gp2OpljK+T2WSfVVcmv2/LNzGZ +o2C7HK2JNDJiuEMhBnIMoVxtRsX6Kc8w3onccVvdtjc+31D1uAclJuW8tf48ArO3 ++L5DwYcRlJ4jbBeKuIonDFRH8KmzwICMoCfrHRnjB453cMor9H124HhnAgMBAAGj +YzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFE1FwWg4u3OpaaEg5+31IqEj +FNeeMB8GA1UdIwQYMBaAFE1FwWg4u3OpaaEg5+31IqEjFNeeMA4GA1UdDwEB/wQE +AwIBhjANBgkqhkiG9w0BAQUFAAOCAgEAZ2sGuV9FOypLM7PmG2tZTiLMubekJcmn +xPBUlgtk87FYT15R/LKXeydlwuXK5w0MJXti4/qftIe3RUavg6WXSIylvfEWK5t2 +LHo1YGwRgJfMqZJS5ivmae2p+DYtLHe/YUjRYwu5W1LtGLBDQiKmsXeu3mnFzccc +obGlHBD7GL4acN3Bkku+KVqdPzW+5X1R+FXgJXUjhx5c3LqdsKyzadsXg8n33gy8 +CNyRnqjQ1xU3c6U1uPx+xURABsPr+CKAXEfOAuMRn0T//ZoyzH1kUQ7rVyZ2OuMe +IjzCpjbdGe+n/BLzJsBZMYVMnNjP36TMzCmT/5RtdlwTCJfy7aULTd3oyWgOZtMA +DjMSW7yV5TKQqLPGbIOtd+6Lfn6xqavT4fG2wLHqiMDn05DpKJKUe2h7lyoKZy2F +AjgQ5ANh1NolNscIWC2hp1GvMApJ9aZphwctREZ2jirlmjvXGKL8nDgQzMY70rUX +Om/9riW99XJZZLF0KjhfGEzfz3EEWjbUvy+ZnOjZurGV5gJLIaFb1cFPj65pbVPb +AZO1XB4Y3WRayhgoPmMEEf0cjQAPuDffZ4qdZqkCapH/E8ovXYO8h5Ns3CRRFgQl +Zvqz2cK6Kb6aSDiCmfS/O0oxGfm/jiEzFMpPVF/7zvuPcX/9XhmgD0uRuMRUvAaw +RY8mkaKO/qk= +-----END CERTIFICATE----- + +# Issuer: CN=AAA Certificate Services O=Comodo CA Limited +# Subject: CN=AAA Certificate Services O=Comodo CA Limited +# Label: "Comodo AAA Services root" +# Serial: 1 +# MD5 Fingerprint: 49:79:04:b0:eb:87:19:ac:47:b0:bc:11:51:9b:74:d0 +# SHA1 Fingerprint: d1:eb:23:a4:6d:17:d6:8f:d9:25:64:c2:f1:f1:60:17:64:d8:e3:49 +# SHA256 Fingerprint: d7:a7:a0:fb:5d:7e:27:31:d7:71:e9:48:4e:bc:de:f7:1d:5f:0c:3e:0a:29:48:78:2b:c8:3e:e0:ea:69:9e:f4 +-----BEGIN CERTIFICATE----- +MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb +MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow +GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj +YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM +GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua +BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe +3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4 +YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR +rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm +ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU +oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF +MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v +QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t +b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF +AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q +GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz +Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2 +G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi +l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3 +smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== +-----END CERTIFICATE----- + +# Issuer: CN=Secure Certificate Services O=Comodo CA Limited +# Subject: CN=Secure Certificate Services O=Comodo CA Limited +# Label: "Comodo Secure Services root" +# Serial: 1 +# MD5 Fingerprint: d3:d9:bd:ae:9f:ac:67:24:b3:c8:1b:52:e1:b9:a9:bd +# SHA1 Fingerprint: 4a:65:d5:f4:1d:ef:39:b8:b8:90:4a:4a:d3:64:81:33:cf:c7:a1:d1 +# SHA256 Fingerprint: bd:81:ce:3b:4f:65:91:d1:1a:67:b5:fc:7a:47:fd:ef:25:52:1b:f9:aa:4e:18:b9:e3:df:2e:34:a7:80:3b:e8 +-----BEGIN CERTIFICATE----- +MIIEPzCCAyegAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJHQjEb +MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow +GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEkMCIGA1UEAwwbU2VjdXJlIENlcnRp +ZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVow +fjELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxJDAiBgNV +BAMMG1NlY3VyZSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBAMBxM4KK0HDrc4eCQNUd5MvJDkKQ+d40uaG6EfQlhfPM +cm3ye5drswfxdySRXyWP9nQ95IDC+DwN879A6vfIUtFyb+/Iq0G4bi4XKpVpDM3S +HpR7LZQdqnXXs5jLrLxkU0C8j6ysNstcrbvd4JQX7NFc0L/vpZXJkMWwrPsbQ996 +CF23uPJAGysnnlDOXmWCiIxe004MeuoIkbY2qitC++rCoznl2yY4rYsK7hljxxwk +3wN42ubqwUcaCwtGCd0C/N7Lh1/XMGNooa7cMqG6vv5Eq2i2pRcV/b3Vp6ea5EQz +6YiO/O1R65NxTq0B50SOqy3LqP4BSUjwwN3HaNiS/j0CAwEAAaOBxzCBxDAdBgNV +HQ4EFgQUPNiTiMLAggnMAZkGkyDpnnAJY08wDgYDVR0PAQH/BAQDAgEGMA8GA1Ud +EwEB/wQFMAMBAf8wgYEGA1UdHwR6MHgwO6A5oDeGNWh0dHA6Ly9jcmwuY29tb2Rv +Y2EuY29tL1NlY3VyZUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDmgN6A1hjNodHRw +Oi8vY3JsLmNvbW9kby5uZXQvU2VjdXJlQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmww +DQYJKoZIhvcNAQEFBQADggEBAIcBbSMdflsXfcFhMs+P5/OKlFlm4J4oqF7Tt/Q0 +5qo5spcWxYJvMqTpjOev/e/C6LlLqqP05tqNZSH7uoDrJiiFGv45jN5bBAS0VPmj +Z55B+glSzAVIqMk/IQQezkhr/IXownuvf7fM+F86/TXGDe+X3EyrEeFryzHRbPtI +gKvcnDe4IRRLDXE97IMzbtFuMhbsmMcWi1mmNKsFVy2T96oTy9IT4rcuO81rUBcJ +aD61JlfutuC23bkpgHl9j6PwpCikFcSF9CfUa7/lXORlAnZUtOM3ZiTTGWHIUhDl +izeauan5Hb/qmZJhlv8BzaFfDbxxvA6sCx1HRR3B7Hzs/Sk= +-----END CERTIFICATE----- + +# Issuer: CN=Trusted Certificate Services O=Comodo CA Limited +# Subject: CN=Trusted Certificate Services O=Comodo CA Limited +# Label: "Comodo Trusted Services root" +# Serial: 1 +# MD5 Fingerprint: 91:1b:3f:6e:cd:9e:ab:ee:07:fe:1f:71:d2:b3:61:27 +# SHA1 Fingerprint: e1:9f:e3:0e:8b:84:60:9e:80:9b:17:0d:72:a8:c5:ba:6e:14:09:bd +# SHA256 Fingerprint: 3f:06:e5:56:81:d4:96:f5:be:16:9e:b5:38:9f:9f:2b:8f:f6:1e:17:08:df:68:81:72:48:49:cd:5d:27:cb:69 +-----BEGIN CERTIFICATE----- +MIIEQzCCAyugAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEb +MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow +GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDElMCMGA1UEAwwcVHJ1c3RlZCBDZXJ0 +aWZpY2F0ZSBTZXJ2aWNlczAeFw0wNDAxMDEwMDAwMDBaFw0yODEyMzEyMzU5NTla +MH8xCzAJBgNVBAYTAkdCMRswGQYDVQQIDBJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO +BgNVBAcMB1NhbGZvcmQxGjAYBgNVBAoMEUNvbW9kbyBDQSBMaW1pdGVkMSUwIwYD +VQQDDBxUcnVzdGVkIENlcnRpZmljYXRlIFNlcnZpY2VzMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEA33FvNlhTWvI2VFeAxHQIIO0Yfyod5jWaHiWsnOWW +fnJSoBVC21ndZHoa0Lh73TkVvFVIxO06AOoxEbrycXQaZ7jPM8yoMa+j49d/vzMt +TGo87IvDktJTdyR0nAducPy9C1t2ul/y/9c3S0pgePfw+spwtOpZqqPOSC+pw7IL +fhdyFgymBwwbOM/JYrc/oJOlh0Hyt3BAd9i+FHzjqMB6juljatEPmsbS9Is6FARW +1O24zG71++IsWL1/T2sr92AkWCTOJu80kTrV44HQsvAEAtdbtz6SrGsSivnkBbA7 +kUlcsutT6vifR4buv5XAwAaf0lteERv0xwQ1KdJVXOTt6wIDAQABo4HJMIHGMB0G +A1UdDgQWBBTFe1i97doladL3WRaoszLAeydb9DAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zCBgwYDVR0fBHwwejA8oDqgOIY2aHR0cDovL2NybC5jb21v +ZG9jYS5jb20vVHJ1c3RlZENlcnRpZmljYXRlU2VydmljZXMuY3JsMDqgOKA2hjRo +dHRwOi8vY3JsLmNvbW9kby5uZXQvVHJ1c3RlZENlcnRpZmljYXRlU2VydmljZXMu +Y3JsMA0GCSqGSIb3DQEBBQUAA4IBAQDIk4E7ibSvuIQSTI3S8NtwuleGFTQQuS9/ +HrCoiWChisJ3DFBKmwCL2Iv0QeLQg4pKHBQGsKNoBXAxMKdTmw7pSqBYaWcOrp32 +pSxBvzwGa+RZzG0Q8ZZvH9/0BAKkn0U+yNj6NkZEUD+Cl5EfKNsYEYwq5GWDVxIS +jBc/lDb+XbDABHcTuPQV1T84zJQ6VdCsmPW6AF/ghhmBeC8owH7TzEIK9a5QoNE+ +xqFx7D+gIIxmOom0jtTYsU0lR+4viMi14QVFwL4Ucd56/Y57fU0IlqUSc/Atyjcn +dBInTMu2l+nZrghtWjlA3QVHdWpaIbOjGM9O9y5Xt5hwXsjEeLBi +-----END CERTIFICATE----- + +# Issuer: CN=UTN - DATACorp SGC O=The USERTRUST Network OU=http://www.usertrust.com +# Subject: CN=UTN - DATACorp SGC O=The USERTRUST Network OU=http://www.usertrust.com +# Label: "UTN DATACorp SGC Root CA" +# Serial: 91374294542884689855167577680241077609 +# MD5 Fingerprint: b3:a5:3e:77:21:6d:ac:4a:c0:c9:fb:d5:41:3d:ca:06 +# SHA1 Fingerprint: 58:11:9f:0e:12:82:87:ea:50:fd:d9:87:45:6f:4f:78:dc:fa:d6:d4 +# SHA256 Fingerprint: 85:fb:2f:91:dd:12:27:5a:01:45:b6:36:53:4f:84:02:4a:d6:8b:69:b8:ee:88:68:4f:f7:11:37:58:05:b3:48 +-----BEGIN CERTIFICATE----- +MIIEXjCCA0agAwIBAgIQRL4Mi1AAIbQR0ypoBqmtaTANBgkqhkiG9w0BAQUFADCB +kzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug +Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho +dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZBgNVBAMTElVUTiAtIERBVEFDb3Jw +IFNHQzAeFw05OTA2MjQxODU3MjFaFw0xOTA2MjQxOTA2MzBaMIGTMQswCQYDVQQG +EwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4wHAYD +VQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cu +dXNlcnRydXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNvcnAgU0dDMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3+5YEKIrblXEjr8uRgnn4AgPLit6 +E5Qbvfa2gI5lBZMAHryv4g+OGQ0SR+ysraP6LnD43m77VkIVni5c7yPeIbkFdicZ +D0/Ww5y0vpQZY/KmEQrrU0icvvIpOxboGqBMpsn0GFlowHDyUwDAXlCCpVZvNvlK +4ESGoE1O1kduSUrLZ9emxAW5jh70/P/N5zbgnAVssjMiFdC04MwXwLLA9P4yPykq +lXvY8qdOD1R8oQ2AswkDwf9c3V6aPryuvEeKaq5xyh+xKrhfQgUL7EYw0XILyulW +bfXv33i+Ybqypa4ETLyorGkVl73v67SMvzX41MPRKA5cOp9wGDMgd8SirwIDAQAB +o4GrMIGoMAsGA1UdDwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRT +MtGzz3/64PGgXYVOktKeRR20TzA9BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vY3Js +LnVzZXJ0cnVzdC5jb20vVVROLURBVEFDb3JwU0dDLmNybDAqBgNVHSUEIzAhBggr +BgEFBQcDAQYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GCSqGSIb3DQEBBQUAA4IB +AQAnNZcAiosovcYzMB4p/OL31ZjUQLtgyr+rFywJNn9Q+kHcrpY6CiM+iVnJowft +Gzet/Hy+UUla3joKVAgWRcKZsYfNjGjgaQPpxE6YsjuMFrMOoAyYUJuTqXAJyCyj +j98C5OBxOvG0I3KgqgHf35g+FFCgMSa9KOlaMCZ1+XtgHI3zzVAmbQQnmt/VDUVH +KWss5nbZqSl9Mt3JNjy9rjXxEZ4du5A/EkdOjtd+D2JzHVImOBwYSf0wdJrE5SIv +2MCN7ZF6TACPcn9d2t0bi0Vr591pl6jFVkwPDPafepE39peC4N1xaf92P2BNPM/3 +mfnGV/TJVTl4uix5yaaIK/QI +-----END CERTIFICATE----- + +# Issuer: CN=UTN-USERFirst-Hardware O=The USERTRUST Network OU=http://www.usertrust.com +# Subject: CN=UTN-USERFirst-Hardware O=The USERTRUST Network OU=http://www.usertrust.com +# Label: "UTN USERFirst Hardware Root CA" +# Serial: 91374294542884704022267039221184531197 +# MD5 Fingerprint: 4c:56:41:e5:0d:bb:2b:e8:ca:a3:ed:18:08:ad:43:39 +# SHA1 Fingerprint: 04:83:ed:33:99:ac:36:08:05:87:22:ed:bc:5e:46:00:e3:be:f9:d7 +# SHA256 Fingerprint: 6e:a5:47:41:d0:04:66:7e:ed:1b:48:16:63:4a:a3:a7:9e:6e:4b:96:95:0f:82:79:da:fc:8d:9b:d8:81:21:37 +-----BEGIN CERTIFICATE----- +MIIEdDCCA1ygAwIBAgIQRL4Mi1AAJLQR0zYq/mUK/TANBgkqhkiG9w0BAQUFADCB +lzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug +Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho +dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3Qt +SGFyZHdhcmUwHhcNOTkwNzA5MTgxMDQyWhcNMTkwNzA5MTgxOTIyWjCBlzELMAkG +A1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEe +MBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8v +d3d3LnVzZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdh +cmUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCx98M4P7Sof885glFn +0G2f0v9Y8+efK+wNiVSZuTiZFvfgIXlIwrthdBKWHTxqctU8EGc6Oe0rE81m65UJ +M6Rsl7HoxuzBdXmcRl6Nq9Bq/bkqVRcQVLMZ8Jr28bFdtqdt++BxF2uiiPsA3/4a +MXcMmgF6sTLjKwEHOG7DpV4jvEWbe1DByTCP2+UretNb+zNAHqDVmBe8i4fDidNd +oI6yqqr2jmmIBsX6iSHzCJ1pLgkzmykNRg+MzEk0sGlRvfkGzWitZky8PqxhvQqI +DsjfPe58BEydCl5rkdbux+0ojatNh4lz0G6k0B4WixThdkQDf2Os5M1JnMWS9Ksy +oUhbAgMBAAGjgbkwgbYwCwYDVR0PBAQDAgHGMA8GA1UdEwEB/wQFMAMBAf8wHQYD +VR0OBBYEFKFyXyYbKJhDlV0HN9WFlp1L0sNFMEQGA1UdHwQ9MDswOaA3oDWGM2h0 +dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VVE4tVVNFUkZpcnN0LUhhcmR3YXJlLmNy +bDAxBgNVHSUEKjAoBggrBgEFBQcDAQYIKwYBBQUHAwUGCCsGAQUFBwMGBggrBgEF +BQcDBzANBgkqhkiG9w0BAQUFAAOCAQEARxkP3nTGmZev/K0oXnWO6y1n7k57K9cM +//bey1WiCuFMVGWTYGufEpytXoMs61quwOQt9ABjHbjAbPLPSbtNk28Gpgoiskli +CE7/yMgUsogWXecB5BKV5UU0s4tpvc+0hY91UZ59Ojg6FEgSxvunOxqNDYJAB+gE +CJChicsZUN/KHAG8HQQZexB2lzvukJDKxA4fFm517zP4029bHpbj4HR3dHuKom4t +3XbWOTCC8KucUvIqx69JXn7HaOWCgchqJ/kniCrVWFCVH/A7HFe7fRQ5YiuayZSS +KqMiDP+JJn1fIytH1xUdqWqeUQ0qUZ6B+dQ7XnASfxAynB67nfhmqA== +-----END CERTIFICATE----- + +# Issuer: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com +# Subject: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com +# Label: "XRamp Global CA Root" +# Serial: 107108908803651509692980124233745014957 +# MD5 Fingerprint: a1:0b:44:b3:ca:10:d8:00:6e:9d:0f:d8:0f:92:0a:d1 +# SHA1 Fingerprint: b8:01:86:d1:eb:9c:86:a5:41:04:cf:30:54:f3:4c:52:b7:e5:58:c6 +# SHA256 Fingerprint: ce:cd:dc:90:50:99:d8:da:df:c5:b1:d2:09:b7:37:cb:e2:c1:8c:fb:2c:10:c0:ff:0b:cf:0d:32:86:fc:1a:a2 +-----BEGIN CERTIFICATE----- +MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCB +gjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEk +MCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRY +UmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQxMTAxMTcx +NDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3 +dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2Vy +dmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS6 +38eMpSe2OAtp87ZOqCwuIR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCP +KZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMxfoArtYzAQDsRhtDLooY2YKTVMIJt2W7Q +DxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FEzG+gSqmUsE3a56k0enI4 +qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqsAxcZZPRa +JSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNVi +PvryxS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0P +BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASs +jVy16bYbMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0 +eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQEwDQYJKoZIhvcNAQEFBQAD +ggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc/Kh4ZzXxHfAR +vbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt +qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLa +IR9NmXmd4c8nnxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSy +i6mx5O+aGtA9aZnuqCij4Tyz8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQ +O+7ETPTsJ3xCwnR8gooJybQDJbw= +-----END CERTIFICATE----- + +# Issuer: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority +# Subject: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority +# Label: "Go Daddy Class 2 CA" +# Serial: 0 +# MD5 Fingerprint: 91:de:06:25:ab:da:fd:32:17:0c:bb:25:17:2a:84:67 +# SHA1 Fingerprint: 27:96:ba:e6:3f:18:01:e2:77:26:1b:a0:d7:77:70:02:8f:20:ee:e4 +# SHA256 Fingerprint: c3:84:6b:f2:4b:9e:93:ca:64:27:4c:0e:c6:7c:1e:cc:5e:02:4f:fc:ac:d2:d7:40:19:35:0e:81:fe:54:6a:e4 +-----BEGIN CERTIFICATE----- +MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh +MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE +YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3 +MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo +ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg +MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN +ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA +PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w +wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi +EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY +avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+ +YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE +sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h +/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5 +IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj +YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD +ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy +OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P +TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ +HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER +dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf +ReYNnyicsbkqWletNw+vHX/bvZ8= +-----END CERTIFICATE----- + +# Issuer: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority +# Subject: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority +# Label: "Starfield Class 2 CA" +# Serial: 0 +# MD5 Fingerprint: 32:4a:4b:bb:c8:63:69:9b:be:74:9a:c6:dd:1d:46:24 +# SHA1 Fingerprint: ad:7e:1c:28:b0:64:ef:8f:60:03:40:20:14:c3:d0:e3:37:0e:b5:8a +# SHA256 Fingerprint: 14:65:fa:20:53:97:b8:76:fa:a6:f0:a9:95:8e:55:90:e4:0f:cc:7f:aa:4f:b7:c2:c8:67:75:21:fb:5f:b6:58 +-----BEGIN CERTIFICATE----- +MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl +MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp +U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw +NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE +ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp +ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3 +DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf +8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN ++lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0 +X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa +K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA +1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G +A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR +zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0 +YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD +bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w +DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3 +L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D +eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl +xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp +VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY +WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q= +-----END CERTIFICATE----- + +# Issuer: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing +# Subject: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing +# Label: "StartCom Certification Authority" +# Serial: 1 +# MD5 Fingerprint: 22:4d:8f:8a:fc:f7:35:c2:bb:57:34:90:7b:8b:22:16 +# SHA1 Fingerprint: 3e:2b:f7:f2:03:1b:96:f3:8c:e6:c4:d8:a8:5d:3e:2d:58:47:6a:0f +# SHA256 Fingerprint: c7:66:a9:be:f2:d4:07:1c:86:3a:31:aa:49:20:e8:13:b2:d1:98:60:8c:b7:b7:cf:e2:11:43:b8:36:df:09:ea +-----BEGIN CERTIFICATE----- +MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW +MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg +Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM2WhcNMzYwOTE3MTk0NjM2WjB9 +MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi +U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh +cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk +pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf +OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C +Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT +Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi +HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM +Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w ++2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+ +Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3 +Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B +26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID +AQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE +FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9j +ZXJ0LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3Js +LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFM +BgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUHAgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0 +Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRwOi8vY2VydC5zdGFy +dGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYgU3Rh +cnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlh +YmlsaXR5LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg +dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp +bGFibGUgYXQgaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3BvbGljeS5wZGYwEQYJ +YIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNT +TCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOCAgEAFmyZ +9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8 +jhvh3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUW +FjgKXlf2Ysd6AgXmvB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJz +ewT4F+irsfMuXGRuczE6Eri8sxHkfY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1 +ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3fsNrarnDy0RLrHiQi+fHLB5L +EUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZEoalHmdkrQYu +L6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq +yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuC +O3NJo2pXh5Tl1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6V +um0ABj6y6koQOdjQK/W/7HW/lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkySh +NOsF/5oirpt9P/FlUQqmMGqz9IgcgA38corog14= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root CA" +# Serial: 17154717934120587862167794914071425081 +# MD5 Fingerprint: 87:ce:0b:7b:2a:0e:49:00:e1:58:71:9b:37:a8:93:72 +# SHA1 Fingerprint: 05:63:b8:63:0d:62:d7:5a:bb:c8:ab:1e:4b:df:b5:a8:99:b2:4d:43 +# SHA256 Fingerprint: 3e:90:99:b5:01:5e:8f:48:6c:00:bc:ea:9d:11:1e:e7:21:fa:ba:35:5a:89:bc:f1:df:69:56:1e:3d:c6:32:5c +-----BEGIN CERTIFICATE----- +MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv +b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl +cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c +JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP +mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+ +wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4 +VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/ +AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB +AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun +pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC +dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf +fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm +NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx +H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe ++o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root CA" +# Serial: 10944719598952040374951832963794454346 +# MD5 Fingerprint: 79:e4:a9:84:0d:7d:3a:96:d7:c0:4f:e2:43:4c:89:2e +# SHA1 Fingerprint: a8:98:5d:3a:65:e5:e5:c4:b2:d7:d6:6d:40:c6:dd:2f:b1:9c:54:36 +# SHA256 Fingerprint: 43:48:a0:e9:44:4c:78:cb:26:5e:05:8d:5e:89:44:b4:d8:4f:96:62:bd:26:db:25:7f:89:34:a4:43:c7:01:61 +-----BEGIN CERTIFICATE----- +MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD +QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB +CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 +nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt +43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P +T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 +gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO +BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR +TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw +DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr +hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg +06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF +PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls +YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk +CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert High Assurance EV Root CA" +# Serial: 3553400076410547919724730734378100087 +# MD5 Fingerprint: d4:74:de:57:5c:39:b2:d3:9c:85:83:c5:c0:65:49:8a +# SHA1 Fingerprint: 5f:b7:ee:06:33:e2:59:db:ad:0c:4c:9a:e6:d3:8f:1a:61:c7:dc:25 +# SHA256 Fingerprint: 74:31:e5:f4:c3:c1:ce:46:90:77:4f:0b:61:e0:54:40:88:3b:a9:a0:1e:d0:0b:a6:ab:d7:80:6e:d3:b1:18:cf +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j +ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL +MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 +LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug +RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm ++9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW +PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM +xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB +Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 +hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg +EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA +FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec +nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z +eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF +hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 +Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe +vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep ++OkuE6N36B9K +-----END CERTIFICATE----- + +# Issuer: CN=GeoTrust Primary Certification Authority O=GeoTrust Inc. +# Subject: CN=GeoTrust Primary Certification Authority O=GeoTrust Inc. +# Label: "GeoTrust Primary Certification Authority" +# Serial: 32798226551256963324313806436981982369 +# MD5 Fingerprint: 02:26:c3:01:5e:08:30:37:43:a9:d0:7d:cf:37:e6:bf +# SHA1 Fingerprint: 32:3c:11:8e:1b:f7:b8:b6:52:54:e2:e2:10:0d:d6:02:90:37:f0:96 +# SHA256 Fingerprint: 37:d5:10:06:c5:12:ea:ab:62:64:21:f1:ec:8c:92:01:3f:c5:f8:2a:e9:8e:e5:33:eb:46:19:b8:de:b4:d0:6c +-----BEGIN CERTIFICATE----- +MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBY +MQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMo +R2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEx +MjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgxCzAJBgNVBAYTAlVTMRYwFAYDVQQK +Ew1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQcmltYXJ5IENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9 +AWbK7hWNb6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjA +ZIVcFU2Ix7e64HXprQU9nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE0 +7e9GceBrAqg1cmuXm2bgyxx5X9gaBGgeRwLmnWDiNpcB3841kt++Z8dtd1k7j53W +kBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGttm/81w7a4DSwDRp35+MI +mO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4G +A1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJ +KoZIhvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ1 +6CePbJC/kRYkRj5KTs4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl +4b7UVXGYNTq+k+qurUKykG/g/CFNNWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6K +oKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHaFloxt/m0cYASSJlyc1pZU8Fj +UjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG1riR/aYNKxoU +AT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk= +-----END CERTIFICATE----- + +# Issuer: CN=thawte Primary Root CA O=thawte, Inc. OU=Certification Services Division/(c) 2006 thawte, Inc. - For authorized use only +# Subject: CN=thawte Primary Root CA O=thawte, Inc. OU=Certification Services Division/(c) 2006 thawte, Inc. - For authorized use only +# Label: "thawte Primary Root CA" +# Serial: 69529181992039203566298953787712940909 +# MD5 Fingerprint: 8c:ca:dc:0b:22:ce:f5:be:72:ac:41:1a:11:a8:d8:12 +# SHA1 Fingerprint: 91:c6:d6:ee:3e:8a:c8:63:84:e5:48:c2:99:29:5c:75:6c:81:7b:81 +# SHA256 Fingerprint: 8d:72:2f:81:a9:c1:13:c0:79:1d:f1:36:a2:96:6d:b2:6c:95:0a:97:1d:b4:6b:41:99:f4:ea:54:b7:8b:fb:9f +-----BEGIN CERTIFICATE----- +MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCB +qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf +Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw +MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV +BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3MDAwMDAwWhcNMzYw +NzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5j +LjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYG +A1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl +IG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCsoPD7gFnUnMekz52hWXMJEEUMDSxuaPFs +W0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ1CRfBsDMRJSUjQJib+ta +3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGcq/gcfomk +6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6 +Sk/KaAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94J +NqR32HuHUETVPm4pafs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBA +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XP +r87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUFAAOCAQEAeRHAS7ORtvzw6WfU +DW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeEuzLlQRHAd9mz +YJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX +xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2 +/qxAeeWsEG89jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/ +LHbTY5xZ3Y+m4Q6gLkH3LpVHz7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7 +jVaMaA== +-----END CERTIFICATE----- + +# Issuer: CN=VeriSign Class 3 Public Primary Certification Authority - G5 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2006 VeriSign, Inc. - For authorized use only +# Subject: CN=VeriSign Class 3 Public Primary Certification Authority - G5 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2006 VeriSign, Inc. - For authorized use only +# Label: "VeriSign Class 3 Public Primary Certification Authority - G5" +# Serial: 33037644167568058970164719475676101450 +# MD5 Fingerprint: cb:17:e4:31:67:3e:e2:09:fe:45:57:93:f3:0a:fa:1c +# SHA1 Fingerprint: 4e:b6:d5:78:49:9b:1c:cf:5f:58:1e:ad:56:be:3d:9b:67:44:a5:e5 +# SHA256 Fingerprint: 9a:cf:ab:7e:43:c8:d8:80:d0:6b:26:2a:94:de:ee:e4:b4:65:99:89:c3:d0:ca:f1:9b:af:64:05:e4:1a:b7:df +-----BEGIN CERTIFICATE----- +MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB +yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL +ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp +U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW +ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL +MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW +ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln +biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp +U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y +aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1 +nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex +t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz +SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG +BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+ +rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/ +NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E +BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH +BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy +aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv +MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE +p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y +5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK +WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ +4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N +hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq +-----END CERTIFICATE----- + +# Issuer: CN=COMODO Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO Certification Authority O=COMODO CA Limited +# Label: "COMODO Certification Authority" +# Serial: 104350513648249232941998508985834464573 +# MD5 Fingerprint: 5c:48:dc:f7:42:72:ec:56:94:6d:1c:cc:71:35:80:75 +# SHA1 Fingerprint: 66:31:bf:9e:f7:4f:9e:b6:c9:d5:a6:0c:ba:6a:be:d1:f7:bd:ef:7b +# SHA256 Fingerprint: 0c:2c:d6:3d:f7:80:6f:a3:99:ed:e8:09:11:6b:57:5b:f8:79:89:f0:65:18:f9:80:8c:86:05:03:17:8b:af:66 +-----BEGIN CERTIFICATE----- +MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB +gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV +BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw +MDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl +YXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P +RE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3 +UcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI +2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8 +Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp ++2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+ +DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O +nKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW +/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g +PKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u +QXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY +SdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv +IC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ +RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4 +zJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd +BA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB +ZQ== +-----END CERTIFICATE----- + +# Issuer: CN=Network Solutions Certificate Authority O=Network Solutions L.L.C. +# Subject: CN=Network Solutions Certificate Authority O=Network Solutions L.L.C. +# Label: "Network Solutions Certificate Authority" +# Serial: 116697915152937497490437556386812487904 +# MD5 Fingerprint: d3:f3:a6:16:c0:fa:6b:1d:59:b1:2d:96:4d:0e:11:2e +# SHA1 Fingerprint: 74:f8:a3:c3:ef:e7:b3:90:06:4b:83:90:3c:21:64:60:20:e5:df:ce +# SHA256 Fingerprint: 15:f0:ba:00:a3:ac:7a:f3:ac:88:4c:07:2b:10:11:a0:77:bd:77:c0:97:f4:01:64:b2:f8:59:8a:bd:83:86:0c +-----BEGIN CERTIFICATE----- +MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBi +MQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu +MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3Jp +dHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJV +UzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydO +ZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwz +c7MEL7xxjOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPP +OCwGJgl6cvf6UDL4wpPTaaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rl +mGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXTcrA/vGp97Eh/jcOrqnErU2lBUzS1sLnF +BgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc/Qzpf14Dl847ABSHJ3A4 +qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMBAAGjgZcw +gZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIB +BjAPBgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwu +bmV0c29sc3NsLmNvbS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3Jp +dHkuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc8 +6fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q4LqILPxFzBiwmZVRDuwduIj/ +h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/GGUsyfJj4akH +/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv +wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHN +pGxlaKFJdlxDydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey +-----END CERTIFICATE----- + +# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Label: "COMODO ECC Certification Authority" +# Serial: 41578283867086692638256921589707938090 +# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23 +# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11 +# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7 +-----BEGIN CERTIFICATE----- +MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT +IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw +MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy +ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N +T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR +FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J +cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW +BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm +fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv +GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= +-----END CERTIFICATE----- + +# Issuer: CN=TC TrustCenter Class 2 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 2 CA +# Subject: CN=TC TrustCenter Class 2 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 2 CA +# Label: "TC TrustCenter Class 2 CA II" +# Serial: 941389028203453866782103406992443 +# MD5 Fingerprint: ce:78:33:5c:59:78:01:6e:18:ea:b9:36:a0:b9:2e:23 +# SHA1 Fingerprint: ae:50:83:ed:7c:f4:5c:bc:8f:61:c6:21:fe:68:5d:79:42:21:15:6e +# SHA256 Fingerprint: e6:b8:f8:76:64:85:f8:07:ae:7f:8d:ac:16:70:46:1f:07:c0:a1:3e:ef:3a:1f:f7:17:53:8d:7a:ba:d3:91:b4 +-----BEGIN CERTIFICATE----- +MIIEqjCCA5KgAwIBAgIOLmoAAQACH9dSISwRXDswDQYJKoZIhvcNAQEFBQAwdjEL +MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNV +BAsTGVRDIFRydXN0Q2VudGVyIENsYXNzIDIgQ0ExJTAjBgNVBAMTHFRDIFRydXN0 +Q2VudGVyIENsYXNzIDIgQ0EgSUkwHhcNMDYwMTEyMTQzODQzWhcNMjUxMjMxMjI1 +OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1c3RDZW50ZXIgR21i +SDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQTElMCMGA1UEAxMc +VEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAKuAh5uO8MN8h9foJIIRszzdQ2Lu+MNF2ujhoF/RKrLqk2jf +tMjWQ+nEdVl//OEd+DFwIxuInie5e/060smp6RQvkL4DUsFJzfb95AhmC1eKokKg +uNV/aVyQMrKXDcpK3EY+AlWJU+MaWss2xgdW94zPEfRMuzBwBJWl9jmM/XOBCH2J +XjIeIqkiRUuwZi4wzJ9l/fzLganx4Duvo4bRierERXlQXa7pIXSSTYtZgo+U4+lK +8edJsBTj9WLL1XK9H7nSn6DNqPoByNkN39r8R52zyFTfSUrxIan+GE7uSNQZu+99 +5OKdy1u2bv/jzVrndIIFuoAlOMvkaZ6vQaoahPUCAwEAAaOCATQwggEwMA8GA1Ud +EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTjq1RMgKHbVkO3 +kUrL84J6E1wIqzCB7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRy +dXN0Y2VudGVyLmRlL2NybC92Mi90Y19jbGFzc18yX2NhX0lJLmNybIaBn2xkYXA6 +Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBUcnVzdENlbnRlciUyMENsYXNz +JTIwMiUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21iSCxPVT1yb290 +Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u +TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEAjNfffu4bgBCzg/XbEeprS6iS +GNn3Bzn1LL4GdXpoUxUc6krtXvwjshOg0wn/9vYua0Fxec3ibf2uWWuFHbhOIprt +ZjluS5TmVfwLG4t3wVMTZonZKNaL80VKY7f9ewthXbhtvsPcW3nS7Yblok2+XnR8 +au0WOB9/WIFaGusyiC2y8zl3gK9etmF1KdsjTYjKUCjLhdLTEKJZbtOTVAB6okaV +hgWcqRmY5TFyDADiZ9lA4CQze28suVyrZZ0srHbqNZn1l7kPJOzHdiEoZa5X6AeI +dUpWoNIFOqTmjZKILPPy4cHGYdtBxceb9w4aUUXCYWvcZCcXjFq32nQozZfkvQ== +-----END CERTIFICATE----- + +# Issuer: CN=TC TrustCenter Class 3 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 3 CA +# Subject: CN=TC TrustCenter Class 3 CA II O=TC TrustCenter GmbH OU=TC TrustCenter Class 3 CA +# Label: "TC TrustCenter Class 3 CA II" +# Serial: 1506523511417715638772220530020799 +# MD5 Fingerprint: 56:5f:aa:80:61:12:17:f6:67:21:e6:2b:6d:61:56:8e +# SHA1 Fingerprint: 80:25:ef:f4:6e:70:c8:d4:72:24:65:84:fe:40:3b:8a:8d:6a:db:f5 +# SHA256 Fingerprint: 8d:a0:84:fc:f9:9c:e0:77:22:f8:9b:32:05:93:98:06:fa:5c:b8:11:e1:c8:13:f6:a1:08:c7:d3:36:b3:40:8e +-----BEGIN CERTIFICATE----- +MIIEqjCCA5KgAwIBAgIOSkcAAQAC5aBd1j8AUb8wDQYJKoZIhvcNAQEFBQAwdjEL +MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNV +BAsTGVRDIFRydXN0Q2VudGVyIENsYXNzIDMgQ0ExJTAjBgNVBAMTHFRDIFRydXN0 +Q2VudGVyIENsYXNzIDMgQ0EgSUkwHhcNMDYwMTEyMTQ0MTU3WhcNMjUxMjMxMjI1 +OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1c3RDZW50ZXIgR21i +SDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQTElMCMGA1UEAxMc +VEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBALTgu1G7OVyLBMVMeRwjhjEQY0NVJz/GRcekPewJDRoeIMJW +Ht4bNwcwIi9v8Qbxq63WyKthoy9DxLCyLfzDlml7forkzMA5EpBCYMnMNWju2l+Q +Vl/NHE1bWEnrDgFPZPosPIlY2C8u4rBo6SI7dYnWRBpl8huXJh0obazovVkdKyT2 +1oQDZogkAHhg8fir/gKya/si+zXmFtGt9i4S5Po1auUZuV3bOx4a+9P/FRQI2Alq +ukWdFHlgfa9Aigdzs5OW03Q0jTo3Kd5c7PXuLjHCINy+8U9/I1LZW+Jk2ZyqBwi1 +Rb3R0DHBq1SfqdLDYmAD8bs5SpJKPQq5ncWg/jcCAwEAAaOCATQwggEwMA8GA1Ud +EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTUovyfs8PYA9NX +XAek0CSnwPIA1DCB7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRy +dXN0Y2VudGVyLmRlL2NybC92Mi90Y19jbGFzc18zX2NhX0lJLmNybIaBn2xkYXA6 +Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBUcnVzdENlbnRlciUyMENsYXNz +JTIwMyUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21iSCxPVT1yb290 +Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u +TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEANmDkcPcGIEPZIxpC8vijsrlN +irTzwppVMXzEO2eatN9NDoqTSheLG43KieHPOh6sHfGcMrSOWXaiQYUlN6AT0PV8 +TtXqluJucsG7Kv5sbviRmEb8yRtXW+rIGjs/sFGYPAfaLFkB2otE6OF0/ado3VS6 +g0bsyEa1+K+XwDsJHI/OcpY9M1ZwvJbL2NV9IJqDnxrcOfHFcqMRA/07QlIp2+gB +95tejNaNhk4Z+rwcvsUhpYeeeC422wlxo3I0+GzjBgnyXlal092Y+tTmBvTwtiBj +S+opvaqCZh77gaqnN60TGOaSw4HBM7uIHqHn4rS9MWwOUT1v+5ZWgOI2F9Hc5A== +-----END CERTIFICATE----- + +# Issuer: CN=TC TrustCenter Universal CA I O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA +# Subject: CN=TC TrustCenter Universal CA I O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA +# Label: "TC TrustCenter Universal CA I" +# Serial: 601024842042189035295619584734726 +# MD5 Fingerprint: 45:e1:a5:72:c5:a9:36:64:40:9e:f5:e4:58:84:67:8c +# SHA1 Fingerprint: 6b:2f:34:ad:89:58:be:62:fd:b0:6b:5c:ce:bb:9d:d9:4f:4e:39:f3 +# SHA256 Fingerprint: eb:f3:c0:2a:87:89:b1:fb:7d:51:19:95:d6:63:b7:29:06:d9:13:ce:0d:5e:10:56:8a:8a:77:e2:58:61:67:e7 +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIOHaIAAQAC7LdggHiNtgYwDQYJKoZIhvcNAQEFBQAweTEL +MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNV +BAsTG1RDIFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQTEmMCQGA1UEAxMdVEMgVHJ1 +c3RDZW50ZXIgVW5pdmVyc2FsIENBIEkwHhcNMDYwMzIyMTU1NDI4WhcNMjUxMjMx +MjI1OTU5WjB5MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1c3RDZW50ZXIg +R21iSDEkMCIGA1UECxMbVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBMSYwJAYD +VQQDEx1UQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0EgSTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAKR3I5ZEr5D0MacQ9CaHnPM42Q9e3s9B6DGtxnSR +JJZ4Hgmgm5qVSkr1YnwCqMqs+1oEdjneX/H5s7/zA1hV0qq34wQi0fiU2iIIAI3T +fCZdzHd55yx4Oagmcw6iXSVphU9VDprvxrlE4Vc93x9UIuVvZaozhDrzznq+VZeu +jRIPFDPiUHDDSYcTvFHe15gSWu86gzOSBnWLknwSaHtwag+1m7Z3W0hZneTvWq3z +wZ7U10VOylY0Ibw+F1tvdwxIAUMpsN0/lm7mlaoMwCC2/T42J5zjXM9OgdwZu5GQ +fezmlwQek8wiSdeXhrYTCjxDI3d+8NzmzSQfO4ObNDqDNOMCAwEAAaNjMGEwHwYD +VR0jBBgwFoAUkqR1LKSevoFE63n8isWVpesQdXMwDwYDVR0TAQH/BAUwAwEB/zAO +BgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFJKkdSyknr6BROt5/IrFlaXrEHVzMA0G +CSqGSIb3DQEBBQUAA4IBAQAo0uCG1eb4e/CX3CJrO5UUVg8RMKWaTzqwOuAGy2X1 +7caXJ/4l8lfmXpWMPmRgFVp/Lw0BxbFg/UU1z/CyvwbZ71q+s2IhtNerNXxTPqYn +8aEt2hojnczd7Dwtnic0XQ/CNnm8yUpiLe1r2X1BQ3y2qsrtYbE3ghUJGooWMNjs +ydZHcnhLEEYUjl8Or+zHL6sQ17bxbuyGssLoDZJz3KL0Dzq/YSMQiZxIQG5wALPT +ujdEWBF6AmqI8Dc08BnprNRlc/ZpjGSUOnmFKbAWKwyCPwacx/0QK54PLLae4xW/ +2TYcuiUaUj0a7CIMHOCkoj3w6DnPgcB77V0fb8XQC9eY +-----END CERTIFICATE----- + +# Issuer: CN=Cybertrust Global Root O=Cybertrust, Inc +# Subject: CN=Cybertrust Global Root O=Cybertrust, Inc +# Label: "Cybertrust Global Root" +# Serial: 4835703278459682877484360 +# MD5 Fingerprint: 72:e4:4a:87:e3:69:40:80:77:ea:bc:e3:f4:ff:f0:e1 +# SHA1 Fingerprint: 5f:43:e5:b1:bf:f8:78:8c:ac:1c:c7:ca:4a:9a:c6:22:2b:cc:34:c6 +# SHA256 Fingerprint: 96:0a:df:00:63:e9:63:56:75:0c:29:65:dd:0a:08:67:da:0b:9c:bd:6e:77:71:4a:ea:fb:23:49:ab:39:3d:a3 +-----BEGIN CERTIFICATE----- +MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYG +A1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2Jh +bCBSb290MB4XDTA2MTIxNTA4MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UE +ChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBS +b290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+Mi8vRRQZhP/8NN5 +7CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW0ozS +J8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2y +HLtgwEZLAfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iP +t3sMpTjr3kfb1V05/Iin89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNz +FtApD0mpSPCzqrdsxacwOUBdrsTiXSZT8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAY +XSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/ +MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2MDSgMqAw +hi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3Js +MB8GA1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUA +A4IBAQBW7wojoFROlZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMj +Wqd8BfP9IjsO0QbE2zZMcwSO5bAi5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUx +XOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2hO0j9n0Hq0V+09+zv+mKts2o +omcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+TX3EJIrduPuoc +A06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW +WL1WMRJOEcgh4LMRkWXbtKaIOM5V +-----END CERTIFICATE----- + +# Issuer: CN=GeoTrust Primary Certification Authority - G3 O=GeoTrust Inc. OU=(c) 2008 GeoTrust Inc. - For authorized use only +# Subject: CN=GeoTrust Primary Certification Authority - G3 O=GeoTrust Inc. OU=(c) 2008 GeoTrust Inc. - For authorized use only +# Label: "GeoTrust Primary Certification Authority - G3" +# Serial: 28809105769928564313984085209975885599 +# MD5 Fingerprint: b5:e8:34:36:c9:10:44:58:48:70:6d:2e:83:d4:b8:05 +# SHA1 Fingerprint: 03:9e:ed:b8:0b:e7:a0:3c:69:53:89:3b:20:d2:d9:32:3a:4c:2a:fd +# SHA256 Fingerprint: b4:78:b8:12:25:0d:f8:78:63:5c:2a:a7:ec:7d:15:5e:aa:62:5e:e8:29:16:e2:cd:29:43:61:88:6c:d1:fb:d4 +-----BEGIN CERTIFICATE----- +MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCB +mDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsT +MChjKSAyMDA4IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25s +eTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhv +cml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIzNTk1OVowgZgxCzAJ +BgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg +MjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0 +BgNVBAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg +LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz ++uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5jK/BGvESyiaHAKAxJcCGVn2TAppMSAmUm +hsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdEc5IiaacDiGydY8hS2pgn +5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3CIShwiP/W +JmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exAL +DmKudlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZC +huOl1UcCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYw +HQYDVR0OBBYEFMR5yo6hTgMdHNxr2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IB +AQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9cr5HqQ6XErhK8WTTOd8lNNTB +zU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbEAp7aDHdlDkQN +kv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD +AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUH +SJsMC8tJP33st/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2G +spki4cErx5z481+oghLrGREt +-----END CERTIFICATE----- + +# Issuer: CN=thawte Primary Root CA - G2 O=thawte, Inc. OU=(c) 2007 thawte, Inc. - For authorized use only +# Subject: CN=thawte Primary Root CA - G2 O=thawte, Inc. OU=(c) 2007 thawte, Inc. - For authorized use only +# Label: "thawte Primary Root CA - G2" +# Serial: 71758320672825410020661621085256472406 +# MD5 Fingerprint: 74:9d:ea:60:24:c4:fd:22:53:3e:cc:3a:72:d9:29:4f +# SHA1 Fingerprint: aa:db:bc:22:23:8f:c4:01:a1:27:bb:38:dd:f4:1d:db:08:9e:f0:12 +# SHA256 Fingerprint: a4:31:0d:50:af:18:a6:44:71:90:37:2a:86:af:af:8b:95:1f:fb:43:1d:83:7f:1e:56:88:b4:59:71:ed:15:57 +-----BEGIN CERTIFICATE----- +MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDEL +MAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMp +IDIwMDcgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAi +BgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMjAeFw0wNzExMDUwMDAw +MDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh +d3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBGb3Ig +YXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9v +dCBDQSAtIEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/ +BebfowJPDQfGAFG6DAJSLSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6 +papu+7qzcMBniKI11KOasf2twu8x+qi58/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUmtgAMADna3+FGO6Lts6K +DPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUNG4k8VIZ3 +KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41ox +XZ3Krr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg== +-----END CERTIFICATE----- + +# Issuer: CN=thawte Primary Root CA - G3 O=thawte, Inc. OU=Certification Services Division/(c) 2008 thawte, Inc. - For authorized use only +# Subject: CN=thawte Primary Root CA - G3 O=thawte, Inc. OU=Certification Services Division/(c) 2008 thawte, Inc. - For authorized use only +# Label: "thawte Primary Root CA - G3" +# Serial: 127614157056681299805556476275995414779 +# MD5 Fingerprint: fb:1b:5d:43:8a:94:cd:44:c6:76:f2:43:4b:47:e7:31 +# SHA1 Fingerprint: f1:8b:53:8d:1b:e9:03:b6:a6:f0:56:43:5b:17:15:89:ca:f3:6b:f2 +# SHA256 Fingerprint: 4b:03:f4:58:07:ad:70:f2:1b:fc:2c:ae:71:c9:fd:e4:60:4c:06:4c:f5:ff:b6:86:ba:e5:db:aa:d7:fd:d3:4c +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCB +rjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf +Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw +MDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNV +BAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0wODA0MDIwMDAwMDBa +Fw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3Rl +LCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9u +MTgwNgYDVQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXpl +ZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEcz +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsr8nLPvb2FvdeHsbnndm +gcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2AtP0LMqmsywCPLLEHd5N/8 +YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC+BsUa0Lf +b1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS9 +9irY7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2S +zhkGcuYMXDhpxwTWvGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUk +OQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV +HQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJKoZIhvcNAQELBQADggEBABpA +2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweKA3rD6z8KLFIW +oCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu +t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7c +KUGRIjxpp7sC8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fM +m7v/OeZWYdMKp8RcTGB7BXcmer/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZu +MdRAGmI0Nj81Aa6sY6A= +-----END CERTIFICATE----- + +# Issuer: CN=GeoTrust Primary Certification Authority - G2 O=GeoTrust Inc. OU=(c) 2007 GeoTrust Inc. - For authorized use only +# Subject: CN=GeoTrust Primary Certification Authority - G2 O=GeoTrust Inc. OU=(c) 2007 GeoTrust Inc. - For authorized use only +# Label: "GeoTrust Primary Certification Authority - G2" +# Serial: 80682863203381065782177908751794619243 +# MD5 Fingerprint: 01:5e:d8:6b:bd:6f:3d:8e:a1:31:f8:12:e0:98:73:6a +# SHA1 Fingerprint: 8d:17:84:d5:37:f3:03:7d:ec:70:fe:57:8b:51:9a:99:e6:10:d7:b0 +# SHA256 Fingerprint: 5e:db:7a:c4:3b:82:a0:6a:87:61:e8:d7:be:49:79:eb:f2:61:1f:7d:d7:9b:f9:1c:1c:6b:56:6a:21:9e:d7:66 +-----BEGIN CERTIFICATE----- +MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDEL +MAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChj +KSAyMDA3IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2 +MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 +eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1OVowgZgxCzAJBgNV +BAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykgMjAw +NyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNV +BAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBH +MjB2MBAGByqGSM49AgEGBSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcL +So17VDs6bl8VAsBQps8lL33KSLjHUGMcKiEIfJo22Av+0SbFWDEwKCXzXV2juLal +tJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO +BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+EVXVMAoG +CCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGT +qQ7mndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBucz +rD6ogRLQy7rQkgu2npaqBA+K +-----END CERTIFICATE----- + +# Issuer: CN=VeriSign Universal Root Certification Authority O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2008 VeriSign, Inc. - For authorized use only +# Subject: CN=VeriSign Universal Root Certification Authority O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2008 VeriSign, Inc. - For authorized use only +# Label: "VeriSign Universal Root Certification Authority" +# Serial: 85209574734084581917763752644031726877 +# MD5 Fingerprint: 8e:ad:b5:01:aa:4d:81:e4:8c:1d:d1:e1:14:00:95:19 +# SHA1 Fingerprint: 36:79:ca:35:66:87:72:30:4d:30:a5:fb:87:3b:0f:a7:7b:b7:0d:54 +# SHA256 Fingerprint: 23:99:56:11:27:a5:71:25:de:8c:ef:ea:61:0d:df:2f:a0:78:b5:c8:06:7f:4e:82:82:90:bf:b8:60:e8:4b:3c +-----BEGIN CERTIFICATE----- +MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCB +vTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL +ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJp +U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MTgwNgYDVQQDEy9W +ZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe +Fw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJVUzEX +MBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0 +IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9y +IGF1dGhvcml6ZWQgdXNlIG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNh +bCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj1mCOkdeQmIN65lgZOIzF +9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGPMiJhgsWH +H26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+H +LL729fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN +/BMReYTtXlT2NJ8IAfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPT +rJ9VAMf2CGqUuV/c4DPxhGD5WycRtPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1Ud +EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0GCCsGAQUFBwEMBGEwX6FdoFsw +WTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2Oa8PPgGrUSBgs +exkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud +DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4 +sAPmLGd75JR3Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+ +seQxIcaBlVZaDrHC1LGmWazxY8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz +4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTxP/jgdFcrGJ2BtMQo2pSXpXDrrB2+ +BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+PwGZsY6rp2aQW9IHR +lRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4mJO3 +7M2CYfE45k+XmCpajQ== +-----END CERTIFICATE----- + +# Issuer: CN=VeriSign Class 3 Public Primary Certification Authority - G4 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2007 VeriSign, Inc. - For authorized use only +# Subject: CN=VeriSign Class 3 Public Primary Certification Authority - G4 O=VeriSign, Inc. OU=VeriSign Trust Network/(c) 2007 VeriSign, Inc. - For authorized use only +# Label: "VeriSign Class 3 Public Primary Certification Authority - G4" +# Serial: 63143484348153506665311985501458640051 +# MD5 Fingerprint: 3a:52:e1:e7:fd:6f:3a:e3:6f:f3:6f:99:1b:f9:22:41 +# SHA1 Fingerprint: 22:d5:d8:df:8f:02:31:d1:8d:f7:9d:b7:cf:8a:2d:64:c9:3f:6c:3a +# SHA256 Fingerprint: 69:dd:d7:ea:90:bb:57:c9:3e:13:5d:c8:5e:a6:fc:d5:48:0b:60:32:39:bd:c4:54:fc:75:8b:2a:26:cf:7f:79 +-----BEGIN CERTIFICATE----- +MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjEL +MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW +ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2ln +biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp +U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y +aXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjELMAkG +A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJp +U2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwg +SW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2ln +biBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5 +IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8Utpkmw4tXNherJI9/gHm +GUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGzrl0Bp3ve +fLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUw +AwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJ +aW1hZ2UvZ2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYj +aHR0cDovL2xvZ28udmVyaXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMW +kf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMDA2gAMGUCMGYhDBgmYFo4e1ZC +4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIxAJw9SDkjOVga +FRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Label: "GlobalSign Root CA - R3" +# Serial: 4835703278459759426209954 +# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28 +# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad +# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b +-----BEGIN CERTIFICATE----- +MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G +A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp +Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 +MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG +A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 +RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT +gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm +KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd +QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ +XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw +DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o +LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU +RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp +jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK +6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX +mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs +Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH +WD9f +-----END CERTIFICATE----- + +# Issuer: CN=TC TrustCenter Universal CA III O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA +# Subject: CN=TC TrustCenter Universal CA III O=TC TrustCenter GmbH OU=TC TrustCenter Universal CA +# Label: "TC TrustCenter Universal CA III" +# Serial: 2010889993983507346460533407902964 +# MD5 Fingerprint: 9f:dd:db:ab:ff:8e:ff:45:21:5f:f0:6c:9d:8f:fe:2b +# SHA1 Fingerprint: 96:56:cd:7b:57:96:98:95:d0:e1:41:46:68:06:fb:b8:c6:11:06:87 +# SHA256 Fingerprint: 30:9b:4a:87:f6:ca:56:c9:31:69:aa:a9:9c:6d:98:88:54:d7:89:2b:d5:43:7e:2d:07:b2:9c:be:da:55:d3:5d +-----BEGIN CERTIFICATE----- +MIID4TCCAsmgAwIBAgIOYyUAAQACFI0zFQLkbPQwDQYJKoZIhvcNAQEFBQAwezEL +MAkGA1UEBhMCREUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNV +BAsTG1RDIFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQTEoMCYGA1UEAxMfVEMgVHJ1 +c3RDZW50ZXIgVW5pdmVyc2FsIENBIElJSTAeFw0wOTA5MDkwODE1MjdaFw0yOTEy +MzEyMzU5NTlaMHsxCzAJBgNVBAYTAkRFMRwwGgYDVQQKExNUQyBUcnVzdENlbnRl +ciBHbWJIMSQwIgYDVQQLExtUQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0ExKDAm +BgNVBAMTH1RDIFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQSBJSUkwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDC2pxisLlxErALyBpXsq6DFJmzNEubkKLF +5+cvAqBNLaT6hdqbJYUtQCggbergvbFIgyIpRJ9Og+41URNzdNW88jBmlFPAQDYv +DIRlzg9uwliT6CwLOunBjvvya8o84pxOjuT5fdMnnxvVZ3iHLX8LR7PH6MlIfK8v +zArZQe+f/prhsq75U7Xl6UafYOPfjdN/+5Z+s7Vy+EutCHnNaYlAJ/Uqwa1D7KRT +yGG299J5KmcYdkhtWyUB0SbFt1dpIxVbYYqt8Bst2a9c8SaQaanVDED1M4BDj5yj +dipFtK+/fz6HP3bFzSreIMUWWMv5G/UPyw0RUmS40nZid4PxWJ//AgMBAAGjYzBh +MB8GA1UdIwQYMBaAFFbn4VslQ4Dg9ozhcbyO5YAvxEjiMA8GA1UdEwEB/wQFMAMB +Af8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRW5+FbJUOA4PaM4XG8juWAL8RI +4jANBgkqhkiG9w0BAQUFAAOCAQEAg8ev6n9NCjw5sWi+e22JLumzCecYV42Fmhfz +dkJQEw/HkG8zrcVJYCtsSVgZ1OK+t7+rSbyUyKu+KGwWaODIl0YgoGhnYIg5IFHY +aAERzqf2EQf27OysGh+yZm5WZ2B6dF7AbZc2rrUNXWZzwCUyRdhKBgePxLcHsU0G +DeGl6/R1yrqc0L2z0zIkTO5+4nYES0lT2PLpVDP85XEfPRRclkvxOvIAu2y0+pZV +CIgJwcyRGSmwIC3/yzikQOEXvnlhgP8HA4ZMTnsGnxGGjYnuJ8Tb4rwZjgvDwxPH +LQNjO9Po5KIqwoIIlBZU8O8fJ5AluA0OKBtHd0e9HKgl8ZS0Zg== +-----END CERTIFICATE----- + +# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Label: "Go Daddy Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01 +# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b +# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT +EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp +ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz +NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH +EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE +AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD +E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH +/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy +DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh +GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR +tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA +AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX +WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu +9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr +gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo +2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO +LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI +4uJEvlz36hz1 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96 +# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e +# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5 +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs +ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw +MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 +b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj +aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp +Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg +nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1 +HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N +Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN +dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0 +HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO +BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G +CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU +sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3 +4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg +8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K +pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1 +mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Services Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2 +# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f +# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5 +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs +ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 +MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD +VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy +ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy +dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p +OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2 +8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K +Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe +hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk +6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw +DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q +AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI +bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB +ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z +qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd +iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn +0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN +sSi6 +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Commercial O=AffirmTrust +# Subject: CN=AffirmTrust Commercial O=AffirmTrust +# Label: "AffirmTrust Commercial" +# Serial: 8608355977964138876 +# MD5 Fingerprint: 82:92:ba:5b:ef:cd:8a:6f:a6:3d:55:f9:84:f6:d6:b7 +# SHA1 Fingerprint: f9:b5:b6:32:45:5f:9c:be:ec:57:5f:80:dc:e9:6e:2c:c7:b2:78:b7 +# SHA256 Fingerprint: 03:76:ab:1d:54:c5:f9:80:3c:e4:b2:e2:01:a0:ee:7e:ef:7b:57:b6:36:e8:a9:3c:9b:8d:48:60:c9:6f:5f:a7 +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz +dCBDb21tZXJjaWFsMB4XDTEwMDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDEL +MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp +cm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6EqdbDuKP +Hx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yr +ba0F8PrVC8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPAL +MeIrJmqbTFeurCA+ukV6BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1 +yHp52UKqK39c/s4mT6NmgTWvRLpUHhwwMmWd5jyTXlBOeuM61G7MGvv50jeuJCqr +VwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNVHQ4EFgQUnZPGU4teyq8/ +nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ +KoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYG +XUPGhi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNj +vbz4YYCanrHOQnDiqX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivt +Z8SOyUOyXGsViQK8YvxO8rUzqrJv0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9g +N53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0khsUlHRUe072o0EclNmsxZt9YC +nlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Networking O=AffirmTrust +# Subject: CN=AffirmTrust Networking O=AffirmTrust +# Label: "AffirmTrust Networking" +# Serial: 8957382827206547757 +# MD5 Fingerprint: 42:65:ca:be:01:9a:9a:4c:a9:8c:41:49:cd:c0:d5:7f +# SHA1 Fingerprint: 29:36:21:02:8b:20:ed:02:f5:66:c5:32:d1:d6:ed:90:9f:45:00:2f +# SHA256 Fingerprint: 0a:81:ec:5a:92:97:77:f1:45:90:4a:f3:8d:5d:50:9f:66:b5:e2:c5:8f:cd:b5:31:05:8b:0e:17:f3:f0:b4:1b +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz +dCBOZXR3b3JraW5nMB4XDTEwMDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDEL +MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp +cm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC +AQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SEHi3y +YJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbua +kCNrmreIdIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRL +QESxG9fhwoXA3hA/Pe24/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp +6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gbh+0t+nvujArjqWaJGctB+d1ENmHP4ndG +yH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNVHQ4EFgQUBx/S55zawm6i +QLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ +KoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfO +tDIuUFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzu +QY0x2+c06lkh1QF612S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZ +Lgo/bNjR9eUJtGxUAArgFU2HdW23WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4u +olu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9/ZFvgrG+CJPbFEfxojfHRZ48 +x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s= +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Premium O=AffirmTrust +# Subject: CN=AffirmTrust Premium O=AffirmTrust +# Label: "AffirmTrust Premium" +# Serial: 7893706540734352110 +# MD5 Fingerprint: c4:5d:0e:48:b6:ac:28:30:4e:0a:bc:f9:38:16:87:57 +# SHA1 Fingerprint: d8:a6:33:2c:e0:03:6f:b1:85:f6:63:4f:7d:6a:06:65:26:32:28:27 +# SHA256 Fingerprint: 70:a7:3f:7f:37:6b:60:07:42:48:90:45:34:b1:14:82:d5:bf:0e:69:8e:cc:49:8d:f5:25:77:eb:f2:e9:3b:9a +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UE +BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVz +dCBQcmVtaXVtMB4XDTEwMDEyOTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkG +A1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1U +cnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxBLf +qV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtnBKAQ +JG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ ++jjeRFcV5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrS +s8PhaJyJ+HoAVt70VZVs+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5 +HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmdGPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d7 +70O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5Rp9EixAqnOEhss/n/fauG +V+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NIS+LI+H+S +qHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S +5u046uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4Ia +C1nEWTJ3s7xgaVY5/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TX +OwF0lkLgAOIua+rF7nKsu7/+6qqo+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYE +FJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ +BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByvMiPIs0laUZx2 +KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg +Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B +8OWycvpEgjNC6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQ +MKSOyARiqcTtNd56l+0OOF6SL5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc +0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK+4w1IX2COPKpVJEZNZOUbWo6xbLQ +u4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmVBtWVyuEklut89pMF +u+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFgIxpH +YoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8 +GKa1qF60g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaO +RtGdFNrHF+QFlozEJLUbzxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6e +KeC2uAloGRwYQw== +-----END CERTIFICATE----- + +# Issuer: CN=AffirmTrust Premium ECC O=AffirmTrust +# Subject: CN=AffirmTrust Premium ECC O=AffirmTrust +# Label: "AffirmTrust Premium ECC" +# Serial: 8401224907861490260 +# MD5 Fingerprint: 64:b0:09:55:cf:b1:d5:99:e2:be:13:ab:a6:5d:ea:4d +# SHA1 Fingerprint: b8:23:6b:00:2f:1d:16:86:53:01:55:6c:11:a4:37:ca:eb:ff:c3:bb +# SHA256 Fingerprint: bd:71:fd:f6:da:97:e4:cf:62:d1:64:7a:dd:25:81:b0:7d:79:ad:f8:39:7e:b4:ec:ba:9c:5e:84:88:82:14:23 +-----BEGIN CERTIFICATE----- +MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMC +VVMxFDASBgNVBAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQ +cmVtaXVtIEVDQzAeFw0xMDAxMjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJ +BgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEgMB4GA1UEAwwXQWZmaXJt +VHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQNMF4bFZ0D +0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQN8O9 +ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0G +A1UdDgQWBBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4G +A1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/Vs +aobgxCd05DhT1wV/GzTjxi+zygk8N53X57hG8f2h4nECMEJZh0PUUd+60wkyWs6I +flc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKMeQ== +-----END CERTIFICATE----- + +# Issuer: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing +# Subject: CN=StartCom Certification Authority O=StartCom Ltd. OU=Secure Digital Certificate Signing +# Label: "StartCom Certification Authority" +# Serial: 45 +# MD5 Fingerprint: c9:3b:0d:84:41:fc:a4:76:79:23:08:57:de:10:19:16 +# SHA1 Fingerprint: a3:f1:33:3f:e2:42:bf:cf:c5:d1:4e:8f:39:42:98:40:68:10:d1:a0 +# SHA256 Fingerprint: e1:78:90:ee:09:a3:fb:f4:f4:8b:9c:41:4a:17:d6:37:b7:a5:06:47:e9:bc:75:23:22:72:7f:cc:17:42:a9:11 +-----BEGIN CERTIFICATE----- +MIIHhzCCBW+gAwIBAgIBLTANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJJTDEW +MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg +Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM3WhcNMzYwOTE3MTk0NjM2WjB9 +MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi +U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh +cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk +pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf +OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C +Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT +Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi +HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM +Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w ++2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+ +Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3 +Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B +26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID +AQABo4ICEDCCAgwwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD +VR0OBBYEFE4L7xqkQFulF2mHMMo0aEPQQa7yMB8GA1UdIwQYMBaAFE4L7xqkQFul +F2mHMMo0aEPQQa7yMIIBWgYDVR0gBIIBUTCCAU0wggFJBgsrBgEEAYG1NwEBATCC +ATgwLgYIKwYBBQUHAgEWImh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5w +ZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2ludGVybWVk +aWF0ZS5wZGYwgc8GCCsGAQUFBwICMIHCMCcWIFN0YXJ0IENvbW1lcmNpYWwgKFN0 +YXJ0Q29tKSBMdGQuMAMCAQEagZZMaW1pdGVkIExpYWJpbGl0eSwgcmVhZCB0aGUg +c2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFydENvbSBDZXJ0 +aWZpY2F0aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0IGh0dHA6Ly93 +d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgG +CWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1 +dGhvcml0eTANBgkqhkiG9w0BAQsFAAOCAgEAjo/n3JR5fPGFf59Jb2vKXfuM/gTF +wWLRfUKKvFO3lANmMD+x5wqnUCBVJX92ehQN6wQOQOY+2IirByeDqXWmN3PH/UvS +Ta0XQMhGvjt/UfzDtgUx3M2FIk5xt/JxXrAaxrqTi3iSSoX4eA+D/i+tLPfkpLst +0OcNOrg+zvZ49q5HJMqjNTbOx8aHmNrs++myziebiMMEofYLWWivydsQD032ZGNc +pRJvkrKTlMeIFw6Ttn5ii5B/q06f/ON1FE8qMt9bDeD1e5MNq6HPh+GlBEXoPBKl +CcWw0bdT82AUuoVpaiF8H3VhFyAXe2w7QSlc4axa0c2Mm+tgHRns9+Ww2vl5GKVF +P0lDV9LdJNUso/2RjSe15esUBppMeyG7Oq0wBhjA2MFrLH9ZXF2RsXAiV+uKa0hK +1Q8p7MZAwC+ITGgBF3f0JBlPvfrhsiAhS90a2Cl9qrjeVOwhVYBsHvUwyKMQ5bLm +KhQxw4UtjJixhlpPiVktucf3HMiKf8CdBUrmQk9io20ppB+Fq9vlgcitKj1MXVuE +JnHEhV5xJMqlG2zYYdMa4FTbzrqpMrUi9nNBCV24F10OD5mQ1kfabwo6YigUZ4LZ +8dCAWZvLMdibD4x3TrVoivJs9iQOLWxwxXPR3hTQcY+203sC9uO41Alua551hDnm +fyWl8kgAwKQB2j8= +-----END CERTIFICATE----- + +# Issuer: CN=StartCom Certification Authority G2 O=StartCom Ltd. +# Subject: CN=StartCom Certification Authority G2 O=StartCom Ltd. +# Label: "StartCom Certification Authority G2" +# Serial: 59 +# MD5 Fingerprint: 78:4b:fb:9e:64:82:0a:d3:b8:4c:62:f3:64:f2:90:64 +# SHA1 Fingerprint: 31:f1:fd:68:22:63:20:ee:c6:3b:3f:9d:ea:4a:3e:53:7c:7c:39:17 +# SHA256 Fingerprint: c7:ba:65:67:de:93:a7:98:ae:1f:aa:79:1e:71:2d:37:8f:ae:1f:93:c4:39:7f:ea:44:1b:b7:cb:e6:fd:59:95 +-----BEGIN CERTIFICATE----- +MIIFYzCCA0ugAwIBAgIBOzANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJJTDEW +MBQGA1UEChMNU3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlm +aWNhdGlvbiBBdXRob3JpdHkgRzIwHhcNMTAwMTAxMDEwMDAxWhcNMzkxMjMxMjM1 +OTAxWjBTMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjEsMCoG +A1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgRzIwggIiMA0G +CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2iTZbB7cgNr2Cu+EWIAOVeq8Oo1XJ +JZlKxdBWQYeQTSFgpBSHO839sj60ZwNq7eEPS8CRhXBF4EKe3ikj1AENoBB5uNsD +vfOpL9HG4A/LnooUCri99lZi8cVytjIl2bLzvWXFDSxu1ZJvGIsAQRSCb0AgJnoo +D/Uefyf3lLE3PbfHkffiAez9lInhzG7TNtYKGXmu1zSCZf98Qru23QumNK9LYP5/ +Q0kGi4xDuFby2X8hQxfqp0iVAXV16iulQ5XqFYSdCI0mblWbq9zSOdIxHWDirMxW +RST1HFSr7obdljKF+ExP6JV2tgXdNiNnvP8V4so75qbsO+wmETRIjfaAKxojAuuK +HDp2KntWFhxyKrOq42ClAJ8Em+JvHhRYW6Vsi1g8w7pOOlz34ZYrPu8HvKTlXcxN +nw3h3Kq74W4a7I/htkxNeXJdFzULHdfBR9qWJODQcqhaX2YtENwvKhOuJv4KHBnM +0D4LnMgJLvlblnpHnOl68wVQdJVznjAJ85eCXuaPOQgeWeU1FEIT/wCc976qUM/i +UUjXuG+v+E5+M5iSFGI6dWPPe/regjupuznixL0sAA7IF6wT700ljtizkC+p2il9 +Ha90OrInwMEePnWjFqmveiJdnxMaz6eg6+OGCtP95paV1yPIN93EfKo2rJgaErHg +TuixO/XWb/Ew1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE +AwIBBjAdBgNVHQ4EFgQUS8W0QGutHLOlHGVuRjaJhwUMDrYwDQYJKoZIhvcNAQEL +BQADggIBAHNXPyzVlTJ+N9uWkusZXn5T50HsEbZH77Xe7XRcxfGOSeD8bpkTzZ+K +2s06Ctg6Wgk/XzTQLwPSZh0avZyQN8gMjgdalEVGKua+etqhqaRpEpKwfTbURIfX +UfEpY9Z1zRbkJ4kd+MIySP3bmdCPX1R0zKxnNBFi2QwKN4fRoxdIjtIXHfbX/dtl +6/2o1PXWT6RbdejF0mCy2wl+JYt7ulKSnj7oxXehPOBKc2thz4bcQ///If4jXSRK +9dNtD2IEBVeC2m6kMyV5Sy5UGYvMLD0w6dEG/+gyRr61M3Z3qAFdlsHB1b6uJcDJ +HgoJIIihDsnzb02CVAAgp9KP5DlUFy6NHrgbuxu9mk47EDTcnIhT76IxW1hPkWLI +wpqazRVdOKnWvvgTtZ8SafJQYqz7Fzf07rh1Z2AQ+4NQ+US1dZxAF7L+/XldblhY +XzD8AK6vM8EOTmy6p6ahfzLbOOCxchcKK5HsamMm7YnUeMx0HgX4a/6ManY5Ka5l +IxKVCCIcl85bBu4M4ru8H0ST9tg4RQUh7eStqxK2A6RCLi3ECToDZ2mEmuFZkIoo +hdVddLHRDiBYmxOlsGOm7XtH/UVVMKTumtTm4ofvmMkyghEpIrwACjFeLQ/Ajulr +so8uBtjRkcfGEvRM/TAXw8HaOFvjqermobp573PYtlNXLfbQ4ddI +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root G2, OU=www.digicert.com, O=DigiCert Inc, C=US +# Subject: CN=DigiCert Global Root G2, OU=www.digicert.com, O=DigiCert Inc, C=US +# Serial: 33af1e6a711a9a0bb2864b11d09fae5 +# MD5 Fingerprint: E4:A6:8A:C8:54:AC:52:42:46:0A:FD:72:48:1B:2A:44 +# SHA1 Fingerprint: DF:3C:24:F9:BF:D6:66:76:1B:26:80:73:FE:06:D1:CC:8D:4F:82:A4 +# SHA256 Fingerprint: CB:3C:CB:B7:60:31:E5:E0:13:8F:8D:D3:9A:23:F9:DE:47:FF:C3:5E:43:C1:14:4C:EA:27:D4:6A:5A:B1:CB:5F +-----BEGIN CERTIFICATE----- +MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH +MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI +2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx +1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ +q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz +tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ +vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV +5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY +1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4 +NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG +Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91 +8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe +pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl +MrY= +-----END CERTIFICATE----- + +# Issuer: /C=US/O=Internet Security Research Group/CN=ISRG Root X1 +# Subject: /C=US/O=Internet Security Research Group/CN=ISRG Root X1 +# Serial: 8210CFB0D240E3594463E0BB63828B00 +# SHA1 Fingerprint: CA:BD:2A:79:A1:07:6A:31:F2:1D:25:36:35:CB:03:9D:43:29:A5:E8 +# SHA256 Fingerprint: 96:BC:EC:06:26:49:76:F3:74:60:77:9A:CF:28:C5:A7:CF:E8:A3:C0:AA:E1:1A:8F:FC:EE:05:C0:BD:DF:08:C6 +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- + +# Issuer: /C=US/O=Internet Security Research Group/CN=ISRG Root X2 +# Subject: /C=US/O=Internet Security Research Group/CN=ISRG Root X2 +# Serial: 41D29DD172EAEEA780C12C6CE92F8752 +# SHA1 Fingerprint: BD:B1:B9:3C:D5:97:8D:45:C6:26:14:55:F8:DB:95:C7:5A:D1:53:AF +# SHA256 Fingerprint: 69:72:9B:8E:15:A8:6E:FC:17:7A:57:AF:B7:17:1D:FC:64:AD:D2:8C:2F:CA:8C:F1:50:7E:34:45:3C:CB:14:70 +-----BEGIN CERTIFICATE----- +MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw +CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg +R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 +MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT +ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw +EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW ++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 +ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI +zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW +tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 +/q4AaOeMSQ+2b1tbFfLn +-----END CERTIFICATE----- diff --git a/python_embeded/Lib/site-packages/httplib2/certs.py b/python_embeded/Lib/site-packages/httplib2/certs.py new file mode 100644 index 0000000000000000000000000000000000000000..59d1ffc7027352415ebf522eb55e7ce4dd9833b4 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2/certs.py @@ -0,0 +1,42 @@ +"""Utilities for certificate management.""" + +import os + +certifi_available = False +certifi_where = None +try: + from certifi import where as certifi_where + certifi_available = True +except ImportError: + pass + +custom_ca_locater_available = False +custom_ca_locater_where = None +try: + from ca_certs_locater import get as custom_ca_locater_where + custom_ca_locater_available = True +except ImportError: + pass + + +BUILTIN_CA_CERTS = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "cacerts.txt" +) + + +def where(): + env = os.environ.get("HTTPLIB2_CA_CERTS") + if env is not None: + if os.path.isfile(env): + return env + else: + raise RuntimeError("Environment variable HTTPLIB2_CA_CERTS not a valid file") + if custom_ca_locater_available: + return custom_ca_locater_where() + if certifi_available: + return certifi_where() + return BUILTIN_CA_CERTS + + +if __name__ == "__main__": + print(where()) diff --git a/python_embeded/Lib/site-packages/httplib2/error.py b/python_embeded/Lib/site-packages/httplib2/error.py new file mode 100644 index 0000000000000000000000000000000000000000..0e68c12a852c88cace86d476b5cb9a8151196a6c --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2/error.py @@ -0,0 +1,48 @@ +# All exceptions raised here derive from HttpLib2Error +class HttpLib2Error(Exception): + pass + + +# Some exceptions can be caught and optionally +# be turned back into responses. +class HttpLib2ErrorWithResponse(HttpLib2Error): + def __init__(self, desc, response, content): + self.response = response + self.content = content + HttpLib2Error.__init__(self, desc) + + +class RedirectMissingLocation(HttpLib2ErrorWithResponse): + pass + + +class RedirectLimit(HttpLib2ErrorWithResponse): + pass + + +class FailedToDecompressContent(HttpLib2ErrorWithResponse): + pass + + +class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): + pass + + +class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): + pass + + +class MalformedHeader(HttpLib2Error): + pass + + +class RelativeURIError(HttpLib2Error): + pass + + +class ServerNotFoundError(HttpLib2Error): + pass + + +class ProxiesUnavailableError(HttpLib2Error): + pass diff --git a/python_embeded/Lib/site-packages/httplib2/iri2uri.py b/python_embeded/Lib/site-packages/httplib2/iri2uri.py new file mode 100644 index 0000000000000000000000000000000000000000..86e361e62ae8dd603d2a982b22bd79ee8653a726 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2/iri2uri.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +"""Converts an IRI to a URI.""" + +__author__ = "Joe Gregorio (joe@bitworking.org)" +__copyright__ = "Copyright 2006, Joe Gregorio" +__contributors__ = [] +__version__ = "1.0.0" +__license__ = "MIT" + +import urllib.parse + +# Convert an IRI to a URI following the rules in RFC 3987 +# +# The characters we need to enocde and escape are defined in the spec: +# +# iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD +# ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF +# / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD +# / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD +# / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD +# / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD +# / %xD0000-DFFFD / %xE1000-EFFFD + +escape_range = [ + (0xA0, 0xD7FF), + (0xE000, 0xF8FF), + (0xF900, 0xFDCF), + (0xFDF0, 0xFFEF), + (0x10000, 0x1FFFD), + (0x20000, 0x2FFFD), + (0x30000, 0x3FFFD), + (0x40000, 0x4FFFD), + (0x50000, 0x5FFFD), + (0x60000, 0x6FFFD), + (0x70000, 0x7FFFD), + (0x80000, 0x8FFFD), + (0x90000, 0x9FFFD), + (0xA0000, 0xAFFFD), + (0xB0000, 0xBFFFD), + (0xC0000, 0xCFFFD), + (0xD0000, 0xDFFFD), + (0xE1000, 0xEFFFD), + (0xF0000, 0xFFFFD), + (0x100000, 0x10FFFD), +] + + +def encode(c): + retval = c + i = ord(c) + for low, high in escape_range: + if i < low: + break + if i >= low and i <= high: + retval = "".join(["%%%2X" % o for o in c.encode("utf-8")]) + break + return retval + + +def iri2uri(uri): + """Convert an IRI to a URI. Note that IRIs must be + passed in a unicode strings. That is, do not utf-8 encode + the IRI before passing it into the function.""" + if isinstance(uri, str): + (scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri) + authority = authority.encode("idna").decode("utf-8") + # For each character in 'ucschar' or 'iprivate' + # 1. encode as utf-8 + # 2. then %-encode each octet of that utf-8 + uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment)) + uri = "".join([encode(c) for c in uri]) + return uri + + +if __name__ == "__main__": + import unittest + + class Test(unittest.TestCase): + def test_uris(self): + """Test that URIs are invariant under the transformation.""" + invariant = [ + "ftp://ftp.is.co.za/rfc/rfc1808.txt", + "http://www.ietf.org/rfc/rfc2396.txt", + "ldap://[2001:db8::7]/c=GB?objectClass?one", + "mailto:John.Doe@example.com", + "news:comp.infosystems.www.servers.unix", + "tel:+1-816-555-1212", + "telnet://192.0.2.16:80/", + "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", + ] + for uri in invariant: + self.assertEqual(uri, iri2uri(uri)) + + def test_iri(self): + """Test that the right type of escaping is done for each part of the URI.""" + self.assertEqual( + "http://xn--o3h.com/%E2%98%84", + iri2uri("http://\N{COMET}.com/\N{COMET}"), + ) + self.assertEqual( + "http://bitworking.org/?fred=%E2%98%84", + iri2uri("http://bitworking.org/?fred=\N{COMET}"), + ) + self.assertEqual( + "http://bitworking.org/#%E2%98%84", + iri2uri("http://bitworking.org/#\N{COMET}"), + ) + self.assertEqual("#%E2%98%84", iri2uri("#\N{COMET}")) + self.assertEqual( + "/fred?bar=%E2%98%9A#%E2%98%84", + iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"), + ) + self.assertEqual( + "/fred?bar=%E2%98%9A#%E2%98%84", + iri2uri(iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")), + ) + self.assertNotEqual( + "/fred?bar=%E2%98%9A#%E2%98%84", + iri2uri( + "/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode("utf-8") + ), + ) + + unittest.main() diff --git a/python_embeded/Lib/site-packages/httplib2/socks.py b/python_embeded/Lib/site-packages/httplib2/socks.py new file mode 100644 index 0000000000000000000000000000000000000000..cc68e634c7def34dbf2dd0be8b0cca17970a73f9 --- /dev/null +++ b/python_embeded/Lib/site-packages/httplib2/socks.py @@ -0,0 +1,518 @@ +"""SocksiPy - Python SOCKS module. + +Version 1.00 + +Copyright 2006 Dan-Haim. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. Neither the name of Dan Haim nor the names of his contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. + +This module provides a standard socket-like interface for Python +for tunneling connections through SOCKS proxies. + +Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for +use in PyLoris (http://pyloris.sourceforge.net/). + +Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) +mainly to merge bug fixes found in Sourceforge. +""" + +import base64 +import socket +import struct +import sys + +if getattr(socket, "socket", None) is None: + raise ImportError("socket.socket missing, proxy support unusable") + +PROXY_TYPE_SOCKS4 = 1 +PROXY_TYPE_SOCKS5 = 2 +PROXY_TYPE_HTTP = 3 +PROXY_TYPE_HTTP_NO_TUNNEL = 4 + +_defaultproxy = None +_orgsocket = socket.socket + + +class ProxyError(Exception): + pass + + +class GeneralProxyError(ProxyError): + pass + + +class Socks5AuthError(ProxyError): + pass + + +class Socks5Error(ProxyError): + pass + + +class Socks4Error(ProxyError): + pass + + +class HTTPError(ProxyError): + pass + + +_generalerrors = ( + "success", + "invalid data", + "not connected", + "not available", + "bad proxy type", + "bad input", +) + +_socks5errors = ( + "succeeded", + "general SOCKS server failure", + "connection not allowed by ruleset", + "Network unreachable", + "Host unreachable", + "Connection refused", + "TTL expired", + "Command not supported", + "Address type not supported", + "Unknown error", +) + +_socks5autherrors = ( + "succeeded", + "authentication is required", + "all offered authentication methods were rejected", + "unknown username or invalid password", + "unknown error", +) + +_socks4errors = ( + "request granted", + "request rejected or failed", + "request rejected because SOCKS server cannot connect to identd on the client", + "request rejected because the client program and identd report different " + "user-ids", + "unknown error", +) + + +def setdefaultproxy( + proxytype=None, addr=None, port=None, rdns=True, username=None, password=None +): + """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) + Sets a default proxy which all further socksocket objects will use, + unless explicitly changed. + """ + global _defaultproxy + _defaultproxy = (proxytype, addr, port, rdns, username, password) + + +def wrapmodule(module): + """wrapmodule(module) + + Attempts to replace a module's socket library with a SOCKS socket. Must set + a default proxy using setdefaultproxy(...) first. + This will only work on modules that import socket directly into the + namespace; + most of the Python Standard Library falls into this category. + """ + if _defaultproxy != None: + module.socket.socket = socksocket + else: + raise GeneralProxyError((4, "no proxy specified")) + + +class socksocket(socket.socket): + """socksocket([family[, type[, proto]]]) -> socket object + Open a SOCKS enabled socket. The parameters are the same as + those of the standard socket init. In order for SOCKS to work, + you must specify family=AF_INET, type=SOCK_STREAM and proto=0. + """ + + def __init__( + self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None + ): + _orgsocket.__init__(self, family, type, proto, _sock) + if _defaultproxy != None: + self.__proxy = _defaultproxy + else: + self.__proxy = (None, None, None, None, None, None) + self.__proxysockname = None + self.__proxypeername = None + self.__httptunnel = True + + def __recvall(self, count): + """__recvall(count) -> data + Receive EXACTLY the number of bytes requested from the socket. + Blocks until the required number of bytes have been received. + """ + data = self.recv(count) + while len(data) < count: + d = self.recv(count - len(data)) + if not d: + raise GeneralProxyError((0, "connection closed unexpectedly")) + data = data + d + return data + + def sendall(self, content, *args): + """ override socket.socket.sendall method to rewrite the header + for non-tunneling proxies if needed + """ + if not self.__httptunnel: + content = self.__rewriteproxy(content) + return super(socksocket, self).sendall(content, *args) + + def __rewriteproxy(self, header): + """ rewrite HTTP request headers to support non-tunneling proxies + (i.e. those which do not support the CONNECT method). + This only works for HTTP (not HTTPS) since HTTPS requires tunneling. + """ + host, endpt = None, None + hdrs = header.split("\r\n") + for hdr in hdrs: + if hdr.lower().startswith("host:"): + host = hdr + elif hdr.lower().startswith("get") or hdr.lower().startswith("post"): + endpt = hdr + if host and endpt: + hdrs.remove(host) + hdrs.remove(endpt) + host = host.split(" ")[1] + endpt = endpt.split(" ") + if self.__proxy[4] != None and self.__proxy[5] != None: + hdrs.insert(0, self.__getauthheader()) + hdrs.insert(0, "Host: %s" % host) + hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2])) + return "\r\n".join(hdrs) + + def __getauthheader(self): + auth = self.__proxy[4] + b":" + self.__proxy[5] + return "Proxy-Authorization: Basic " + base64.b64encode(auth).decode() + + def setproxy( + self, + proxytype=None, + addr=None, + port=None, + rdns=True, + username=None, + password=None, + headers=None, + ): + """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) + + Sets the proxy to be used. + proxytype - The type of the proxy to be used. Three types + are supported: PROXY_TYPE_SOCKS4 (including socks4a), + PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP + addr - The address of the server (IP or DNS). + port - The port of the server. Defaults to 1080 for SOCKS + servers and 8080 for HTTP proxy servers. + rdns - Should DNS queries be preformed on the remote side + (rather than the local side). The default is True. + Note: This has no effect with SOCKS4 servers. + username - Username to authenticate with to the server. + The default is no authentication. + password - Password to authenticate with to the server. + Only relevant when username is also provided. + headers - Additional or modified headers for the proxy connect + request. + """ + self.__proxy = ( + proxytype, + addr, + port, + rdns, + username.encode() if username else None, + password.encode() if password else None, + headers, + ) + + def __negotiatesocks5(self, destaddr, destport): + """__negotiatesocks5(self,destaddr,destport) + Negotiates a connection through a SOCKS5 server. + """ + # First we'll send the authentication packages we support. + if (self.__proxy[4] != None) and (self.__proxy[5] != None): + # The username/password details were supplied to the + # setproxy method so we support the USERNAME/PASSWORD + # authentication (in addition to the standard none). + self.sendall(struct.pack("BBBB", 0x05, 0x02, 0x00, 0x02)) + else: + # No username/password were entered, therefore we + # only support connections with no authentication. + self.sendall(struct.pack("BBB", 0x05, 0x01, 0x00)) + # We'll receive the server's response to determine which + # method was selected + chosenauth = self.__recvall(2) + if chosenauth[0:1] != chr(0x05).encode(): + self.close() + raise GeneralProxyError((1, _generalerrors[1])) + # Check the chosen authentication method + if chosenauth[1:2] == chr(0x00).encode(): + # No authentication is required + pass + elif chosenauth[1:2] == chr(0x02).encode(): + # Okay, we need to perform a basic username/password + # authentication. + packet = bytearray() + packet.append(0x01) + packet.append(len(self.__proxy[4])) + packet.extend(self.__proxy[4]) + packet.append(len(self.__proxy[5])) + packet.extend(self.__proxy[5]) + self.sendall(packet) + authstat = self.__recvall(2) + if authstat[0:1] != chr(0x01).encode(): + # Bad response + self.close() + raise GeneralProxyError((1, _generalerrors[1])) + if authstat[1:2] != chr(0x00).encode(): + # Authentication failed + self.close() + raise Socks5AuthError((3, _socks5autherrors[3])) + # Authentication succeeded + else: + # Reaching here is always bad + self.close() + if chosenauth[1] == chr(0xFF).encode(): + raise Socks5AuthError((2, _socks5autherrors[2])) + else: + raise GeneralProxyError((1, _generalerrors[1])) + # Now we can request the actual connection + req = struct.pack("BBB", 0x05, 0x01, 0x00) + # If the given destination address is an IP address, we'll + # use the IPv4 address request even if remote resolving was specified. + try: + ipaddr = socket.inet_aton(destaddr) + req = req + chr(0x01).encode() + ipaddr + except socket.error: + # Well it's not an IP number, so it's probably a DNS name. + if self.__proxy[3]: + # Resolve remotely + ipaddr = None + req = ( + req + + chr(0x03).encode() + + chr(len(destaddr)).encode() + + destaddr.encode() + ) + else: + # Resolve locally + ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) + req = req + chr(0x01).encode() + ipaddr + req = req + struct.pack(">H", destport) + self.sendall(req) + # Get the response + resp = self.__recvall(4) + if resp[0:1] != chr(0x05).encode(): + self.close() + raise GeneralProxyError((1, _generalerrors[1])) + elif resp[1:2] != chr(0x00).encode(): + # Connection failed + self.close() + if ord(resp[1:2]) <= 8: + raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) + else: + raise Socks5Error((9, _socks5errors[9])) + # Get the bound address/port + elif resp[3:4] == chr(0x01).encode(): + boundaddr = self.__recvall(4) + elif resp[3:4] == chr(0x03).encode(): + resp = resp + self.recv(1) + boundaddr = self.__recvall(ord(resp[4:5])) + else: + self.close() + raise GeneralProxyError((1, _generalerrors[1])) + boundport = struct.unpack(">H", self.__recvall(2))[0] + self.__proxysockname = (boundaddr, boundport) + if ipaddr != None: + self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) + else: + self.__proxypeername = (destaddr, destport) + + def getproxysockname(self): + """getsockname() -> address info + Returns the bound IP address and port number at the proxy. + """ + return self.__proxysockname + + def getproxypeername(self): + """getproxypeername() -> address info + Returns the IP and port number of the proxy. + """ + return _orgsocket.getpeername(self) + + def getpeername(self): + """getpeername() -> address info + Returns the IP address and port number of the destination + machine (note: getproxypeername returns the proxy) + """ + return self.__proxypeername + + def __negotiatesocks4(self, destaddr, destport): + """__negotiatesocks4(self,destaddr,destport) + Negotiates a connection through a SOCKS4 server. + """ + # Check if the destination address provided is an IP address + rmtrslv = False + try: + ipaddr = socket.inet_aton(destaddr) + except socket.error: + # It's a DNS name. Check where it should be resolved. + if self.__proxy[3]: + ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) + rmtrslv = True + else: + ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) + # Construct the request packet + req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr + # The username parameter is considered userid for SOCKS4 + if self.__proxy[4] != None: + req = req + self.__proxy[4] + req = req + chr(0x00).encode() + # DNS name if remote resolving is required + # NOTE: This is actually an extension to the SOCKS4 protocol + # called SOCKS4A and may not be supported in all cases. + if rmtrslv: + req = req + destaddr + chr(0x00).encode() + self.sendall(req) + # Get the response from the server + resp = self.__recvall(8) + if resp[0:1] != chr(0x00).encode(): + # Bad data + self.close() + raise GeneralProxyError((1, _generalerrors[1])) + if resp[1:2] != chr(0x5A).encode(): + # Server returned an error + self.close() + if ord(resp[1:2]) in (91, 92, 93): + self.close() + raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) + else: + raise Socks4Error((94, _socks4errors[4])) + # Get the bound address/port + self.__proxysockname = ( + socket.inet_ntoa(resp[4:]), + struct.unpack(">H", resp[2:4])[0], + ) + if rmtrslv != None: + self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) + else: + self.__proxypeername = (destaddr, destport) + + def __negotiatehttp(self, destaddr, destport): + """__negotiatehttp(self,destaddr,destport) + Negotiates a connection through an HTTP server. + """ + # If we need to resolve locally, we do this now + if not self.__proxy[3]: + addr = socket.gethostbyname(destaddr) + else: + addr = destaddr + headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"] + wrote_host_header = False + wrote_auth_header = False + if self.__proxy[6] != None: + for key, val in self.__proxy[6].iteritems(): + headers += [key, ": ", val, "\r\n"] + wrote_host_header = key.lower() == "host" + wrote_auth_header = key.lower() == "proxy-authorization" + if not wrote_host_header: + headers += ["Host: ", destaddr, "\r\n"] + if not wrote_auth_header: + if self.__proxy[4] != None and self.__proxy[5] != None: + headers += [self.__getauthheader(), "\r\n"] + headers.append("\r\n") + self.sendall("".join(headers).encode()) + # We read the response until we get the string "\r\n\r\n" + resp = self.recv(1) + while resp.find("\r\n\r\n".encode()) == -1: + resp = resp + self.recv(1) + # We just need the first line to check if the connection + # was successful + statusline = resp.splitlines()[0].split(" ".encode(), 2) + if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): + self.close() + raise GeneralProxyError((1, _generalerrors[1])) + try: + statuscode = int(statusline[1]) + except ValueError: + self.close() + raise GeneralProxyError((1, _generalerrors[1])) + if statuscode != 200: + self.close() + raise HTTPError((statuscode, statusline[2])) + self.__proxysockname = ("0.0.0.0", 0) + self.__proxypeername = (addr, destport) + + def connect(self, destpair): + """connect(self, despair) + Connects to the specified destination through a proxy. + destpar - A tuple of the IP/DNS address and the port number. + (identical to socket's connect). + To select the proxy server use setproxy(). + """ + # Do a minimal input check first + if ( + (not type(destpair) in (list, tuple)) + or (len(destpair) < 2) + or (not isinstance(destpair[0], (str, bytes))) + or (type(destpair[1]) != int) + ): + raise GeneralProxyError((5, _generalerrors[5])) + if self.__proxy[0] == PROXY_TYPE_SOCKS5: + if self.__proxy[2] != None: + portnum = self.__proxy[2] + else: + portnum = 1080 + _orgsocket.connect(self, (self.__proxy[1], portnum)) + self.__negotiatesocks5(destpair[0], destpair[1]) + elif self.__proxy[0] == PROXY_TYPE_SOCKS4: + if self.__proxy[2] != None: + portnum = self.__proxy[2] + else: + portnum = 1080 + _orgsocket.connect(self, (self.__proxy[1], portnum)) + self.__negotiatesocks4(destpair[0], destpair[1]) + elif self.__proxy[0] == PROXY_TYPE_HTTP: + if self.__proxy[2] != None: + portnum = self.__proxy[2] + else: + portnum = 8080 + _orgsocket.connect(self, (self.__proxy[1], portnum)) + self.__negotiatehttp(destpair[0], destpair[1]) + elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL: + if self.__proxy[2] != None: + portnum = self.__proxy[2] + else: + portnum = 8080 + _orgsocket.connect(self, (self.__proxy[1], portnum)) + if destpair[1] == 443: + self.__negotiatehttp(destpair[0], destpair[1]) + else: + self.__httptunnel = False + elif self.__proxy[0] == None: + _orgsocket.connect(self, (destpair[0], destpair[1])) + else: + raise GeneralProxyError((4, _generalerrors[4])) diff --git a/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/METADATA b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b0d2b196385e98259971519793447c1fd7a9a643 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/METADATA @@ -0,0 +1,203 @@ +Metadata-Version: 2.3 +Name: httpx +Version: 0.28.1 +Summary: The next generation HTTP client. +Project-URL: Changelog, https://github.com/encode/httpx/blob/master/CHANGELOG.md +Project-URL: Documentation, https://www.python-httpx.org +Project-URL: Homepage, https://github.com/encode/httpx +Project-URL: Source, https://github.com/encode/httpx +Author-email: Tom Christie +License: BSD-3-Clause +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: anyio +Requires-Dist: certifi +Requires-Dist: httpcore==1.* +Requires-Dist: idna +Provides-Extra: brotli +Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli' +Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli' +Provides-Extra: cli +Requires-Dist: click==8.*; extra == 'cli' +Requires-Dist: pygments==2.*; extra == 'cli' +Requires-Dist: rich<14,>=10; extra == 'cli' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: zstd +Requires-Dist: zstandard>=0.18.0; extra == 'zstd' +Description-Content-Type: text/markdown + +

+ HTTPX +

+ +

HTTPX - A next-generation HTTP client for Python.

+ +

+ + Test Suite + + + Package version + +

+ +HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**. + +--- + +Install HTTPX using pip: + +```shell +$ pip install httpx +``` + +Now, let's get started: + +```pycon +>>> import httpx +>>> r = httpx.get('https://www.example.org/') +>>> r + +>>> r.status_code +200 +>>> r.headers['content-type'] +'text/html; charset=UTF-8' +>>> r.text +'\n\n\nExample Domain...' +``` + +Or, using the command-line client. + +```shell +$ pip install 'httpx[cli]' # The command line client is an optional dependency. +``` + +Which now allows us to use HTTPX directly from the command-line... + +

+ httpx --help +

+ +Sending a request... + +

+ httpx http://httpbin.org/json +

+ +## Features + +HTTPX builds on the well-established usability of `requests`, and gives you: + +* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/). +* An integrated command-line client. +* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/). +* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/). +* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/transports/#wsgi-transport) or [ASGI applications](https://www.python-httpx.org/advanced/transports/#asgi-transport). +* Strict timeouts everywhere. +* Fully type annotated. +* 100% test coverage. + +Plus all the standard features of `requests`... + +* International Domains and URLs +* Keep-Alive & Connection Pooling +* Sessions with Cookie Persistence +* Browser-style SSL Verification +* Basic/Digest Authentication +* Elegant Key/Value Cookies +* Automatic Decompression +* Automatic Content Decoding +* Unicode Response Bodies +* Multipart File Uploads +* HTTP(S) Proxy Support +* Connection Timeouts +* Streaming Downloads +* .netrc Support +* Chunked Requests + +## Installation + +Install with pip: + +```shell +$ pip install httpx +``` + +Or, to include the optional HTTP/2 support, use: + +```shell +$ pip install httpx[http2] +``` + +HTTPX requires Python 3.8+. + +## Documentation + +Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/). + +For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/). + +For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section. + +The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference. + +To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/). + +## Contribute + +If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start. + +## Dependencies + +The HTTPX project relies on these excellent libraries: + +* `httpcore` - The underlying transport implementation for `httpx`. + * `h11` - HTTP/1.1 support. +* `certifi` - SSL certificates. +* `idna` - Internationalized domain name support. +* `sniffio` - Async library autodetection. + +As well as these optional installs: + +* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)* +* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)* +* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)* +* `click` - Command line client support. *(Optional, with `httpx[cli]`)* +* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)* +* `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)* + +A huge amount of credit is due to `requests` for the API layout that +much of this work follows, as well as to `urllib3` for plenty of design +inspiration around the lower-level networking details. + +--- + +

HTTPX is BSD licensed code.
Designed & crafted with care.

— 🦋 —

+ +## Release Information + +### Fixed + +* Reintroduced supposedly-private `URLTypes` shortcut. (#2673) + + +--- + +[Full changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md) diff --git a/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/RECORD b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..2beccd67476ff0f20af2197fb5b3fb470cc45f64 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/RECORD @@ -0,0 +1,54 @@ +../../Scripts/httpx.exe,sha256=27CAtpES_bPV1Fg8M4oXUgMIWkhmwbNl9YT7Vz7RLus,108406 +httpx-0.28.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpx-0.28.1.dist-info/METADATA,sha256=_rubD48-gNV8gZnDBPNcQzboWB0dGNeYPJJ2a4J5OyU,7052 +httpx-0.28.1.dist-info/RECORD,, +httpx-0.28.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87 +httpx-0.28.1.dist-info/entry_points.txt,sha256=2lVkdQmxLA1pNMgSN2eV89o90HCZezhmNwsy6ryKDSA,37 +httpx-0.28.1.dist-info/licenses/LICENSE.md,sha256=TsWdVE8StfU5o6cW_TIaxYzNgDC0ZSIfLIgCAM3yjY0,1508 +httpx/__init__.py,sha256=CsaZe6yZj0rHg6322AWKWHGTMVr9txgEfD5P3_Rrz60,2171 +httpx/__pycache__/__init__.cpython-312.pyc,, +httpx/__pycache__/__version__.cpython-312.pyc,, +httpx/__pycache__/_api.cpython-312.pyc,, +httpx/__pycache__/_auth.cpython-312.pyc,, +httpx/__pycache__/_client.cpython-312.pyc,, +httpx/__pycache__/_config.cpython-312.pyc,, +httpx/__pycache__/_content.cpython-312.pyc,, +httpx/__pycache__/_decoders.cpython-312.pyc,, +httpx/__pycache__/_exceptions.cpython-312.pyc,, +httpx/__pycache__/_main.cpython-312.pyc,, +httpx/__pycache__/_models.cpython-312.pyc,, +httpx/__pycache__/_multipart.cpython-312.pyc,, +httpx/__pycache__/_status_codes.cpython-312.pyc,, +httpx/__pycache__/_types.cpython-312.pyc,, +httpx/__pycache__/_urlparse.cpython-312.pyc,, +httpx/__pycache__/_urls.cpython-312.pyc,, +httpx/__pycache__/_utils.cpython-312.pyc,, +httpx/__version__.py,sha256=LoUyYeOXTieGzuP_64UL0wxdtxjuu_QbOvE7NOg-IqU,108 +httpx/_api.py,sha256=r_Zgs4jIpcPJLqK5dbbSayqo_iVMKFaxZCd-oOHxLEs,11743 +httpx/_auth.py,sha256=Yr3QwaUSK17rGYx-7j-FdicFIzz4Y9FFV-1F4-7RXX4,11891 +httpx/_client.py,sha256=xD-UG67-WMkeltAAOeGGj-cZ2RRTAm19sWRxlFY7_40,65714 +httpx/_config.py,sha256=pPp2U-wicfcKsF-KYRE1LYdt3e6ERGeIoXZ8Gjo3LWc,8547 +httpx/_content.py,sha256=LGGzrJTR3OvN4Mb1GVVNLXkXJH-6oKlwAttO9p5w_yg,8161 +httpx/_decoders.py,sha256=p0dX8I0NEHexs3UGp4SsZutiMhsXrrWl6-GnqVb0iKM,12041 +httpx/_exceptions.py,sha256=bxW7fxzgVMAdNTbwT0Vnq04gJDW1_gI_GFiQPuMyjL0,8527 +httpx/_main.py,sha256=Cg9GMabiTT_swaDfUgIRitSwxLRMSwUDOm7LdSGqlA4,15626 +httpx/_models.py,sha256=4__Guyv1gLxuZChwim8kfQNiIOcJ9acreFOSurvZfms,44700 +httpx/_multipart.py,sha256=KOHEZZl6oohg9mPaKyyu345qq1rJLg35TUG3YAzXB3Y,9843 +httpx/_status_codes.py,sha256=DYn-2ufBgMeXy5s8x3_TB7wjAuAAMewTakPrm5rXEsc,5639 +httpx/_transports/__init__.py,sha256=GbUoBSAOp7z-l-9j5YhMhR3DMIcn6FVLhj072O3Nnno,275 +httpx/_transports/__pycache__/__init__.cpython-312.pyc,, +httpx/_transports/__pycache__/asgi.cpython-312.pyc,, +httpx/_transports/__pycache__/base.cpython-312.pyc,, +httpx/_transports/__pycache__/default.cpython-312.pyc,, +httpx/_transports/__pycache__/mock.cpython-312.pyc,, +httpx/_transports/__pycache__/wsgi.cpython-312.pyc,, +httpx/_transports/asgi.py,sha256=HRfiDYMPt4wQH2gFgHZg4c-i3sblo6bL5GTqcET-xz8,5501 +httpx/_transports/base.py,sha256=kZS_VMbViYfF570pogUCJ1bulz-ybfL51Pqs9yktebU,2523 +httpx/_transports/default.py,sha256=AzeaRUyVwCccTyyNJexDf0n1dFfzzydpdIQgvw7PLnk,13983 +httpx/_transports/mock.py,sha256=PTo0d567RITXxGrki6kN7_67wwAxfwiMDcuXJiZCjEo,1232 +httpx/_transports/wsgi.py,sha256=NcPX3Xap_EwCFZWO_OaSyQNuInCYx1QMNbO8GAei6jY,4825 +httpx/_types.py,sha256=Jyh41GQq7AOev8IOWKDAg7zCbvHAfufmW5g_PiTtErY,2965 +httpx/_urlparse.py,sha256=ZAmH47ONfkxrrj-PPYhGeiHjb6AjKCS-ANWIN4OL_KY,18546 +httpx/_urls.py,sha256=dX99VR1DSOHpgo9Aq7PzYO4FKdxqKjwyNp8grf8dHN0,21550 +httpx/_utils.py,sha256=_TVeqAKvxJkKHdz7dFeb4s0LZqQXgeFkXSgfiHBK_1o,8285 +httpx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..21aaa72961a8af71c17d2cb3b76d5f7f567100e4 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.26.3 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ae96007f7d725813fd02dc1d06d3834ee1939e4 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +httpx = httpx:main diff --git a/python_embeded/Lib/site-packages/httpx/__init__.py b/python_embeded/Lib/site-packages/httpx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9addde071f81758baf350c4ab6bde2556340131 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/__init__.py @@ -0,0 +1,105 @@ +from .__version__ import __description__, __title__, __version__ +from ._api import * +from ._auth import * +from ._client import * +from ._config import * +from ._content import * +from ._exceptions import * +from ._models import * +from ._status_codes import * +from ._transports import * +from ._types import * +from ._urls import * + +try: + from ._main import main +except ImportError: # pragma: no cover + + def main() -> None: # type: ignore + import sys + + print( + "The httpx command line client could not run because the required " + "dependencies were not installed.\nMake sure you've installed " + "everything with: pip install 'httpx[cli]'" + ) + sys.exit(1) + + +__all__ = [ + "__description__", + "__title__", + "__version__", + "ASGITransport", + "AsyncBaseTransport", + "AsyncByteStream", + "AsyncClient", + "AsyncHTTPTransport", + "Auth", + "BaseTransport", + "BasicAuth", + "ByteStream", + "Client", + "CloseError", + "codes", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "Cookies", + "create_ssl_context", + "DecodingError", + "delete", + "DigestAuth", + "get", + "head", + "Headers", + "HTTPError", + "HTTPStatusError", + "HTTPTransport", + "InvalidURL", + "Limits", + "LocalProtocolError", + "main", + "MockTransport", + "NetRCAuth", + "NetworkError", + "options", + "patch", + "PoolTimeout", + "post", + "ProtocolError", + "Proxy", + "ProxyError", + "put", + "QueryParams", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "request", + "Request", + "RequestError", + "RequestNotRead", + "Response", + "ResponseNotRead", + "stream", + "StreamClosed", + "StreamConsumed", + "StreamError", + "SyncByteStream", + "Timeout", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "URL", + "USE_CLIENT_DEFAULT", + "WriteError", + "WriteTimeout", + "WSGITransport", +] + + +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + setattr(__locals[__name], "__module__", "httpx") # noqa diff --git a/python_embeded/Lib/site-packages/httpx/__version__.py b/python_embeded/Lib/site-packages/httpx/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..801bfacf671017cfbebf1ac26ec385daa02ed260 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/__version__.py @@ -0,0 +1,3 @@ +__title__ = "httpx" +__description__ = "A next generation HTTP client, for Python 3." +__version__ = "0.28.1" diff --git a/python_embeded/Lib/site-packages/httpx/_api.py b/python_embeded/Lib/site-packages/httpx/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cda1ecda8629edbdca2e3bc04bc51dba5e1430 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_api.py @@ -0,0 +1,438 @@ +from __future__ import annotations + +import typing +from contextlib import contextmanager + +from ._client import Client +from ._config import DEFAULT_TIMEOUT_CONFIG +from ._models import Response +from ._types import ( + AuthTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestFiles, + TimeoutTypes, +) +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + + +__all__ = [ + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "request", + "stream", +] + + +def request( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends an HTTP request. + + **Parameters:** + + * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`, + `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. + * **url** - URL for the new `Request` object. + * **params** - *(optional)* Query parameters to include in the URL, as a + string, dictionary, or sequence of two-tuples. + * **content** - *(optional)* Binary content to include in the body of the + request, as bytes or a byte iterator. + * **data** - *(optional)* Form data to include in the body of the request, + as a dictionary. + * **files** - *(optional)* A dictionary of upload files to include in the + body of the request. + * **json** - *(optional)* A JSON serializable object to include in the body + of the request. + * **headers** - *(optional)* Dictionary of HTTP headers to include in the + request. + * **cookies** - *(optional)* Dictionary of Cookie items to include in the + request. + * **auth** - *(optional)* An authentication class to use when sending the + request. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + the request. + * **follow_redirects** - *(optional)* Enables or disables HTTP redirects. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + + **Returns:** `Response` + + Usage: + + ``` + >>> import httpx + >>> response = httpx.request('GET', 'https://httpbin.org/get') + >>> response + + ``` + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + return client.request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) + + +@contextmanager +def stream( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + with client.stream( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) as response: + yield response + + +def get( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `GET` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `GET` requests should not include a request body. + """ + return request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def options( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `OPTIONS` requests should not include a request body. + """ + return request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def head( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `HEAD` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `HEAD` requests should not include a request body. + """ + return request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def post( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def put( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def patch( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def delete( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends a `DELETE` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `DELETE` requests should not include a request body. + """ + return request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) diff --git a/python_embeded/Lib/site-packages/httpx/_auth.py b/python_embeded/Lib/site-packages/httpx/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..b03971ab4b311d60790dc22ca24d9966426ec0a4 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_auth.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import hashlib +import os +import re +import time +import typing +from base64 import b64encode +from urllib.request import parse_http_list + +from ._exceptions import ProtocolError +from ._models import Cookies, Request, Response +from ._utils import to_bytes, to_str, unquote + +if typing.TYPE_CHECKING: # pragma: no cover + from hashlib import _Hash + + +__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"] + + +class Auth: + """ + Base class for all authentication schemes. + + To implement a custom authentication scheme, subclass `Auth` and override + the `.auth_flow()` method. + + If the authentication scheme does I/O such as disk access or network calls, or uses + synchronization primitives such as locks, you should override `.sync_auth_flow()` + and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized + implementations that will be used by `Client` and `AsyncClient` respectively. + """ + + requires_request_body = False + requires_response_body = False + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow. + + To dispatch a request, `yield` it: + + ``` + yield request + ``` + + The client will `.send()` the response back into the flow generator. You can + access it like so: + + ``` + response = yield request + ``` + + A `return` (or reaching the end of the generator) will result in the + client returning the last response obtained from the server. + + You can dispatch as many requests as is necessary. + """ + yield request + + def sync_auth_flow( + self, request: Request + ) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow synchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + request.read() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + response.read() + + try: + request = flow.send(response) + except StopIteration: + break + + async def async_auth_flow( + self, request: Request + ) -> typing.AsyncGenerator[Request, Response]: + """ + Execute the authentication flow asynchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + await request.aread() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + await response.aread() + + try: + request = flow.send(response) + except StopIteration: + break + + +class FunctionAuth(Auth): + """ + Allows the 'auth' argument to be passed as a simple callable function, + that takes the request, and returns a new, modified request. + """ + + def __init__(self, func: typing.Callable[[Request], Request]) -> None: + self._func = func + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + yield self._func(request) + + +class BasicAuth(Auth): + """ + Allows the 'auth' argument to be passed as a (username, password) pair, + and uses HTTP Basic authentication. + """ + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._auth_header = self._build_auth_header(username, password) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + request.headers["Authorization"] = self._auth_header + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class NetRCAuth(Auth): + """ + Use a 'netrc' file to lookup basic auth credentials based on the url host. + """ + + def __init__(self, file: str | None = None) -> None: + # Lazily import 'netrc'. + # There's no need for us to load this module unless 'NetRCAuth' is being used. + import netrc + + self._netrc_info = netrc.netrc(file) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + auth_info = self._netrc_info.authenticators(request.url.host) + if auth_info is None or not auth_info[2]: + # The netrc file did not have authentication credentials for this host. + yield request + else: + # Build a basic auth header with credentials from the netrc file. + request.headers["Authorization"] = self._build_auth_header( + username=auth_info[0], password=auth_info[2] + ) + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class DigestAuth(Auth): + _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = { + "MD5": hashlib.md5, + "MD5-SESS": hashlib.md5, + "SHA": hashlib.sha1, + "SHA-SESS": hashlib.sha1, + "SHA-256": hashlib.sha256, + "SHA-256-SESS": hashlib.sha256, + "SHA-512": hashlib.sha512, + "SHA-512-SESS": hashlib.sha512, + } + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._username = to_bytes(username) + self._password = to_bytes(password) + self._last_challenge: _DigestAuthChallenge | None = None + self._nonce_count = 1 + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + if self._last_challenge: + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + + response = yield request + + if response.status_code != 401 or "www-authenticate" not in response.headers: + # If the response is not a 401 then we don't + # need to build an authenticated request. + return + + for auth_header in response.headers.get_list("www-authenticate"): + if auth_header.lower().startswith("digest "): + break + else: + # If the response does not include a 'WWW-Authenticate: Digest ...' + # header, then we don't need to build an authenticated request. + return + + self._last_challenge = self._parse_challenge(request, response, auth_header) + self._nonce_count = 1 + + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + if response.cookies: + Cookies(response.cookies).set_cookie_header(request=request) + yield request + + def _parse_challenge( + self, request: Request, response: Response, auth_header: str + ) -> _DigestAuthChallenge: + """ + Returns a challenge from a Digest WWW-Authenticate header. + These take the form of: + `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"` + """ + scheme, _, fields = auth_header.partition(" ") + + # This method should only ever have been called with a Digest auth header. + assert scheme.lower() == "digest" + + header_dict: dict[str, str] = {} + for field in parse_http_list(fields): + key, value = field.strip().split("=", 1) + header_dict[key] = unquote(value) + + try: + realm = header_dict["realm"].encode() + nonce = header_dict["nonce"].encode() + algorithm = header_dict.get("algorithm", "MD5") + opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None + qop = header_dict["qop"].encode() if "qop" in header_dict else None + return _DigestAuthChallenge( + realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop + ) + except KeyError as exc: + message = "Malformed Digest WWW-Authenticate header" + raise ProtocolError(message, request=request) from exc + + def _build_auth_header( + self, request: Request, challenge: _DigestAuthChallenge + ) -> str: + hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()] + + def digest(data: bytes) -> bytes: + return hash_func(data).hexdigest().encode() + + A1 = b":".join((self._username, challenge.realm, self._password)) + + path = request.url.raw_path + A2 = b":".join((request.method.encode(), path)) + # TODO: implement auth-int + HA2 = digest(A2) + + nc_value = b"%08x" % self._nonce_count + cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce) + self._nonce_count += 1 + + HA1 = digest(A1) + if challenge.algorithm.lower().endswith("-sess"): + HA1 = digest(b":".join((HA1, challenge.nonce, cnonce))) + + qop = self._resolve_qop(challenge.qop, request=request) + if qop is None: + # Following RFC 2069 + digest_data = [HA1, challenge.nonce, HA2] + else: + # Following RFC 2617/7616 + digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2] + + format_args = { + "username": self._username, + "realm": challenge.realm, + "nonce": challenge.nonce, + "uri": path, + "response": digest(b":".join(digest_data)), + "algorithm": challenge.algorithm.encode(), + } + if challenge.opaque: + format_args["opaque"] = challenge.opaque + if qop: + format_args["qop"] = b"auth" + format_args["nc"] = nc_value + format_args["cnonce"] = cnonce + + return "Digest " + self._get_header_value(format_args) + + def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes: + s = str(nonce_count).encode() + s += nonce + s += time.ctime().encode() + s += os.urandom(8) + + return hashlib.sha1(s).hexdigest()[:16].encode() + + def _get_header_value(self, header_fields: dict[str, bytes]) -> str: + NON_QUOTED_FIELDS = ("algorithm", "qop", "nc") + QUOTED_TEMPLATE = '{}="{}"' + NON_QUOTED_TEMPLATE = "{}={}" + + header_value = "" + for i, (field, value) in enumerate(header_fields.items()): + if i > 0: + header_value += ", " + template = ( + QUOTED_TEMPLATE + if field not in NON_QUOTED_FIELDS + else NON_QUOTED_TEMPLATE + ) + header_value += template.format(field, to_str(value)) + + return header_value + + def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None: + if qop is None: + return None + qops = re.split(b", ?", qop) + if b"auth" in qops: + return b"auth" + + if qops == [b"auth-int"]: + raise NotImplementedError("Digest auth-int support is not yet implemented") + + message = f'Unexpected qop value "{qop!r}" in digest auth' + raise ProtocolError(message, request=request) + + +class _DigestAuthChallenge(typing.NamedTuple): + realm: bytes + nonce: bytes + algorithm: str + opaque: bytes | None + qop: bytes | None diff --git a/python_embeded/Lib/site-packages/httpx/_client.py b/python_embeded/Lib/site-packages/httpx/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2249231f8c3b912c731ff160344d3672e2f11738 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_client.py @@ -0,0 +1,2019 @@ +from __future__ import annotations + +import datetime +import enum +import logging +import time +import typing +import warnings +from contextlib import asynccontextmanager, contextmanager +from types import TracebackType + +from .__version__ import __version__ +from ._auth import Auth, BasicAuth, FunctionAuth +from ._config import ( + DEFAULT_LIMITS, + DEFAULT_MAX_REDIRECTS, + DEFAULT_TIMEOUT_CONFIG, + Limits, + Proxy, + Timeout, +) +from ._decoders import SUPPORTED_DECODERS +from ._exceptions import ( + InvalidURL, + RemoteProtocolError, + TooManyRedirects, + request_context, +) +from ._models import Cookies, Headers, Request, Response +from ._status_codes import codes +from ._transports.base import AsyncBaseTransport, BaseTransport +from ._transports.default import AsyncHTTPTransport, HTTPTransport +from ._types import ( + AsyncByteStream, + AuthTypes, + CertTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + SyncByteStream, + TimeoutTypes, +) +from ._urls import URL, QueryParams +from ._utils import URLPattern, get_environment_proxies + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"] + +# The type annotation for @classmethod and context managers here follows PEP 484 +# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods +T = typing.TypeVar("T", bound="Client") +U = typing.TypeVar("U", bound="AsyncClient") + + +def _is_https_redirect(url: URL, location: URL) -> bool: + """ + Return 'True' if 'location' is a HTTPS upgrade of 'url' + """ + if url.host != location.host: + return False + + return ( + url.scheme == "http" + and _port_or_default(url) == 80 + and location.scheme == "https" + and _port_or_default(location) == 443 + ) + + +def _port_or_default(url: URL) -> int | None: + if url.port is not None: + return url.port + return {"http": 80, "https": 443}.get(url.scheme) + + +def _same_origin(url: URL, other: URL) -> bool: + """ + Return 'True' if the given URLs share the same origin. + """ + return ( + url.scheme == other.scheme + and url.host == other.host + and _port_or_default(url) == _port_or_default(other) + ) + + +class UseClientDefault: + """ + For some parameters such as `auth=...` and `timeout=...` we need to be able + to indicate the default "unset" state, in a way that is distinctly different + to using `None`. + + The default "unset" state indicates that whatever default is set on the + client should be used. This is different to setting `None`, which + explicitly disables the parameter, possibly overriding a client default. + + For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature. + Omitting the `timeout` parameter will send a request using whatever default + timeout has been configured on the client. Including `timeout=None` will + ensure no timeout is used. + + Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant, + but it is used internally when a parameter is not included. + """ + + +USE_CLIENT_DEFAULT = UseClientDefault() + + +logger = logging.getLogger("httpx") + +USER_AGENT = f"python-httpx/{__version__}" +ACCEPT_ENCODING = ", ".join( + [key for key in SUPPORTED_DECODERS.keys() if key != "identity"] +) + + +class ClientState(enum.Enum): + # UNOPENED: + # The client has been instantiated, but has not been used to send a request, + # or been opened by entering the context of a `with` block. + UNOPENED = 1 + # OPENED: + # The client has either sent a request, or is within a `with` block. + OPENED = 2 + # CLOSED: + # The client has either exited the `with` block, or `close()` has + # been called explicitly. + CLOSED = 3 + + +class BoundSyncStream(SyncByteStream): + """ + A byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: SyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self._stream: + yield chunk + + def close(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + self._stream.close() + + +class BoundAsyncStream(AsyncByteStream): + """ + An async byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: AsyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + async for chunk in self._stream: + yield chunk + + async def aclose(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + await self._stream.aclose() + + +EventHook = typing.Callable[..., typing.Any] + + +class BaseClient: + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + event_hooks = {} if event_hooks is None else event_hooks + + self._base_url = self._enforce_trailing_slash(URL(base_url)) + + self._auth = self._build_auth(auth) + self._params = QueryParams(params) + self.headers = Headers(headers) + self._cookies = Cookies(cookies) + self._timeout = Timeout(timeout) + self.follow_redirects = follow_redirects + self.max_redirects = max_redirects + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + self._trust_env = trust_env + self._default_encoding = default_encoding + self._state = ClientState.UNOPENED + + @property + def is_closed(self) -> bool: + """ + Check if the client being closed + """ + return self._state == ClientState.CLOSED + + @property + def trust_env(self) -> bool: + return self._trust_env + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _get_proxy_map( + self, proxy: ProxyTypes | None, allow_env_proxies: bool + ) -> dict[str, Proxy | None]: + if proxy is None: + if allow_env_proxies: + return { + key: None if url is None else Proxy(url=url) + for key, url in get_environment_proxies().items() + } + return {} + else: + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + return {"all://": proxy} + + @property + def timeout(self) -> Timeout: + return self._timeout + + @timeout.setter + def timeout(self, timeout: TimeoutTypes) -> None: + self._timeout = Timeout(timeout) + + @property + def event_hooks(self) -> dict[str, list[EventHook]]: + return self._event_hooks + + @event_hooks.setter + def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None: + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + + @property + def auth(self) -> Auth | None: + """ + Authentication class used when none is passed at the request-level. + + See also [Authentication][0]. + + [0]: /quickstart/#authentication + """ + return self._auth + + @auth.setter + def auth(self, auth: AuthTypes) -> None: + self._auth = self._build_auth(auth) + + @property + def base_url(self) -> URL: + """ + Base URL to use when sending requests with relative URLs. + """ + return self._base_url + + @base_url.setter + def base_url(self, url: URL | str) -> None: + self._base_url = self._enforce_trailing_slash(URL(url)) + + @property + def headers(self) -> Headers: + """ + HTTP headers to include when sending requests. + """ + return self._headers + + @headers.setter + def headers(self, headers: HeaderTypes) -> None: + client_headers = Headers( + { + b"Accept": b"*/*", + b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"), + b"Connection": b"keep-alive", + b"User-Agent": USER_AGENT.encode("ascii"), + } + ) + client_headers.update(headers) + self._headers = client_headers + + @property + def cookies(self) -> Cookies: + """ + Cookie values to include when sending requests. + """ + return self._cookies + + @cookies.setter + def cookies(self, cookies: CookieTypes) -> None: + self._cookies = Cookies(cookies) + + @property + def params(self) -> QueryParams: + """ + Query parameters to include in the URL when sending requests. + """ + return self._params + + @params.setter + def params(self, params: QueryParamTypes) -> None: + self._params = QueryParams(params) + + def build_request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Request: + """ + Build and return a request instance. + + * The `params`, `headers` and `cookies` arguments + are merged with any values set on the client. + * The `url` argument is merged with any `base_url` set on the client. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + url = self._merge_url(url) + headers = self._merge_headers(headers) + cookies = self._merge_cookies(cookies) + params = self._merge_queryparams(params) + extensions = {} if extensions is None else extensions + if "timeout" not in extensions: + timeout = ( + self.timeout + if isinstance(timeout, UseClientDefault) + else Timeout(timeout) + ) + extensions = dict(**extensions, timeout=timeout.as_dict()) + return Request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + extensions=extensions, + ) + + def _merge_url(self, url: URL | str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + merge_url = URL(url) + if merge_url.is_relative_url: + # To merge URLs we always append to the base URL. To get this + # behaviour correct we always ensure the base URL ends in a '/' + # separator, and strip any leading '/' from the merge URL. + # + # So, eg... + # + # >>> client = Client(base_url="https://www.example.com/subpath") + # >>> client.base_url + # URL('https://www.example.com/subpath/') + # >>> client.build_request("GET", "/path").url + # URL('https://www.example.com/subpath/path') + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + return merge_url + + def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None: + """ + Merge a cookies argument together with any cookies on the client, + to create the cookies used for the outgoing request. + """ + if cookies or self.cookies: + merged_cookies = Cookies(self.cookies) + merged_cookies.update(cookies) + return merged_cookies + return cookies + + def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None: + """ + Merge a headers argument together with any headers on the client, + to create the headers used for the outgoing request. + """ + merged_headers = Headers(self.headers) + merged_headers.update(headers) + return merged_headers + + def _merge_queryparams( + self, params: QueryParamTypes | None = None + ) -> QueryParamTypes | None: + """ + Merge a queryparams argument together with any queryparams on the client, + to create the queryparams used for the outgoing request. + """ + if params or self.params: + merged_queryparams = QueryParams(self.params) + return merged_queryparams.merge(params) + return params + + def _build_auth(self, auth: AuthTypes | None) -> Auth | None: + if auth is None: + return None + elif isinstance(auth, tuple): + return BasicAuth(username=auth[0], password=auth[1]) + elif isinstance(auth, Auth): + return auth + elif callable(auth): + return FunctionAuth(func=auth) + else: + raise TypeError(f'Invalid "auth" argument: {auth!r}') + + def _build_request_auth( + self, + request: Request, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + ) -> Auth: + auth = ( + self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth) + ) + + if auth is not None: + return auth + + username, password = request.url.username, request.url.password + if username or password: + return BasicAuth(username=username, password=password) + + return Auth() + + def _build_redirect_request(self, request: Request, response: Response) -> Request: + """ + Given a request and a redirect response, return a new request that + should be used to effect the redirect. + """ + method = self._redirect_method(request, response) + url = self._redirect_url(request, response) + headers = self._redirect_headers(request, url, method) + stream = self._redirect_stream(request, method) + cookies = Cookies(self.cookies) + return Request( + method=method, + url=url, + headers=headers, + cookies=cookies, + stream=stream, + extensions=request.extensions, + ) + + def _redirect_method(self, request: Request, response: Response) -> str: + """ + When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.SEE_OTHER and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # Turn 302s into GETs. + if response.status_code == codes.FOUND and method != "HEAD": + method = "GET" + + # If a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in 'requests' issue 1704. + if response.status_code == codes.MOVED_PERMANENTLY and method == "POST": + method = "GET" + + return method + + def _redirect_url(self, request: Request, response: Response) -> URL: + """ + Return the URL for the redirect to follow. + """ + location = response.headers["Location"] + + try: + url = URL(location) + except InvalidURL as exc: + raise RemoteProtocolError( + f"Invalid URL in location header: {exc}.", request=request + ) from None + + # Handle malformed 'Location' headers that are "absolute" form, have no host. + # See: https://github.com/encode/httpx/issues/771 + if url.scheme and not url.host: + url = url.copy_with(host=request.url.host) + + # Facilitate relative 'Location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + if url.is_relative_url: + url = request.url.join(url) + + # Attach previous fragment if needed (RFC 7231 7.1.2) + if request.url.fragment and not url.fragment: + url = url.copy_with(fragment=request.url.fragment) + + return url + + def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers: + """ + Return the headers that should be used for the redirect request. + """ + headers = Headers(request.headers) + + if not _same_origin(url, request.url): + if not _is_https_redirect(request.url, url): + # Strip Authorization headers when responses are redirected + # away from the origin. (Except for direct HTTP to HTTPS redirects.) + headers.pop("Authorization", None) + + # Update the Host header. + headers["Host"] = url.netloc.decode("ascii") + + if method != request.method and method == "GET": + # If we've switch to a 'GET' request, then strip any headers which + # are only relevant to the request body. + headers.pop("Content-Length", None) + headers.pop("Transfer-Encoding", None) + + # We should use the client cookie store to determine any cookie header, + # rather than whatever was on the original outgoing request. + headers.pop("Cookie", None) + + return headers + + def _redirect_stream( + self, request: Request, method: str + ) -> SyncByteStream | AsyncByteStream | None: + """ + Return the body that should be used for the redirect request. + """ + if method != request.method and method == "GET": + return None + + return request.stream + + def _set_timeout(self, request: Request) -> None: + if "timeout" not in request.extensions: + timeout = ( + self.timeout + if isinstance(self.timeout, UseClientDefault) + else Timeout(self.timeout) + ) + request.extensions = dict(**request.extensions, timeout=timeout.as_dict()) + + +class Client(BaseClient): + """ + An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. + + It can be shared between threads. + + Usage: + + ```python + >>> client = httpx.Client() + >>> response = client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, BaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: BaseTransport | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + self._mounts: dict[URLPattern, BaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: BaseTransport | None = None, + ) -> BaseTransport: + if transport is not None: + return transport + + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> BaseTransport: + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> BaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = client.send(request, ...) + ``` + + See `Client.build_request()`, `Client.send()` and + [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + if cookies is not None: + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return self.send(request, auth=auth, follow_redirects=follow_redirects) + + @contextmanager + def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + response.close() + + def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `Client.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + response.read() + + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.sync_auth_flow(request) + try: + request = next(auth_flow) + + while True: + response = self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = auth_flow.send(response) + except StopIteration: + return response + + response.history = list(history) + response.read() + request = next_request + history.append(response) + + except BaseException as exc: + response.close() + raise exc + finally: + auth_flow.close() + + def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + hook(request) + + response = self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + hook(response) + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + response.read() + else: + response.next_request = request + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, SyncByteStream): + raise RuntimeError( + "Attempted to send an async request with a sync Client instance." + ) + + with request_context(request=request): + response = transport.handle_request(request) + + assert isinstance(response.stream, SyncByteStream) + + response.request = request + response.stream = BoundSyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def close(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + self._transport.close() + for transport in self._mounts.values(): + if transport is not None: + transport.close() + + def __enter__(self: T) -> T: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + self._transport.__enter__() + for transport in self._mounts.values(): + if transport is not None: + transport.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + self._transport.__exit__(exc_type, exc_value, traceback) + for transport in self._mounts.values(): + if transport is not None: + transport.__exit__(exc_type, exc_value, traceback) + + +class AsyncClient(BaseClient): + """ + An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, + cookie persistence, etc. + + It can be shared between tasks. + + Usage: + + ```python + >>> async with httpx.AsyncClient() as client: + >>> response = await client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: AsyncBaseTransport | None = None, + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + + self._mounts: dict[URLPattern, AsyncBaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: AsyncBaseTransport | None = None, + ) -> AsyncBaseTransport: + if transport is not None: + return transport + + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> AsyncBaseTransport: + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> AsyncBaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + async def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = await client.send(request, ...) + ``` + + See `AsyncClient.build_request()`, `AsyncClient.send()` + and [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + + if cookies is not None: # pragma: no cover + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return await self.send(request, auth=auth, follow_redirects=follow_redirects) + + @asynccontextmanager + async def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.AsyncIterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = await self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + await response.aclose() + + async def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `AsyncClient.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = await self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + await response.aread() + + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.async_auth_flow(request) + try: + request = await auth_flow.__anext__() + + while True: + response = await self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = await auth_flow.asend(response) + except StopAsyncIteration: + return response + + response.history = list(history) + await response.aread() + request = next_request + history.append(response) + + except BaseException as exc: + await response.aclose() + raise exc + finally: + await auth_flow.aclose() + + async def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + await hook(request) + + response = await self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + await hook(response) + + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + await response.aread() + else: + response.next_request = request + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, AsyncByteStream): + raise RuntimeError( + "Attempted to send an sync request with an AsyncClient instance." + ) + + with request_context(request=request): + response = await transport.handle_async_request(request) + + assert isinstance(response.stream, AsyncByteStream) + response.request = request + response.stream = BoundAsyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + async def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def aclose(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + await self._transport.aclose() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.aclose() + + async def __aenter__(self: U) -> U: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + await self._transport.__aenter__() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + await self._transport.__aexit__(exc_type, exc_value, traceback) + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aexit__(exc_type, exc_value, traceback) diff --git a/python_embeded/Lib/site-packages/httpx/_config.py b/python_embeded/Lib/site-packages/httpx/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..467a6c90ae269babe3af7963d9d7c78b9f012268 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_config.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +import os +import typing + +from ._models import Headers +from ._types import CertTypes, HeaderTypes, TimeoutTypes +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"] + + +class UnsetType: + pass # pragma: no cover + + +UNSET = UnsetType() + + +def create_ssl_context( + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, +) -> ssl.SSLContext: + import ssl + import warnings + + import certifi + + if verify is True: + if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover + ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"]) + elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover + ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"]) + else: + # Default case... + ctx = ssl.create_default_context(cafile=certifi.where()) + elif verify is False: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + elif isinstance(verify, str): # pragma: nocover + message = ( + "`verify=` is deprecated. " + "Use `verify=ssl.create_default_context(cafile=...)` " + "or `verify=ssl.create_default_context(capath=...)` instead." + ) + warnings.warn(message, DeprecationWarning) + if os.path.isdir(verify): + return ssl.create_default_context(capath=verify) + return ssl.create_default_context(cafile=verify) + else: + ctx = verify + + if cert: # pragma: nocover + message = ( + "`cert=...` is deprecated. Use `verify=` instead," + "with `.load_cert_chain()` to configure the certificate chain." + ) + warnings.warn(message, DeprecationWarning) + if isinstance(cert, str): + ctx.load_cert_chain(cert) + else: + ctx.load_cert_chain(*cert) + + return ctx + + +class Timeout: + """ + Timeout configuration. + + **Usage**: + + Timeout(None) # No timeouts. + Timeout(5.0) # 5s timeout on all operations. + Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. + Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. + Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. + # 5s timeout elsewhere. + """ + + def __init__( + self, + timeout: TimeoutTypes | UnsetType = UNSET, + *, + connect: None | float | UnsetType = UNSET, + read: None | float | UnsetType = UNSET, + write: None | float | UnsetType = UNSET, + pool: None | float | UnsetType = UNSET, + ) -> None: + if isinstance(timeout, Timeout): + # Passed as a single explicit Timeout. + assert connect is UNSET + assert read is UNSET + assert write is UNSET + assert pool is UNSET + self.connect = timeout.connect # type: typing.Optional[float] + self.read = timeout.read # type: typing.Optional[float] + self.write = timeout.write # type: typing.Optional[float] + self.pool = timeout.pool # type: typing.Optional[float] + elif isinstance(timeout, tuple): + # Passed as a tuple. + self.connect = timeout[0] + self.read = timeout[1] + self.write = None if len(timeout) < 3 else timeout[2] + self.pool = None if len(timeout) < 4 else timeout[3] + elif not ( + isinstance(connect, UnsetType) + or isinstance(read, UnsetType) + or isinstance(write, UnsetType) + or isinstance(pool, UnsetType) + ): + self.connect = connect + self.read = read + self.write = write + self.pool = pool + else: + if isinstance(timeout, UnsetType): + raise ValueError( + "httpx.Timeout must either include a default, or set all " + "four parameters explicitly." + ) + self.connect = timeout if isinstance(connect, UnsetType) else connect + self.read = timeout if isinstance(read, UnsetType) else read + self.write = timeout if isinstance(write, UnsetType) else write + self.pool = timeout if isinstance(pool, UnsetType) else pool + + def as_dict(self) -> dict[str, float | None]: + return { + "connect": self.connect, + "read": self.read, + "write": self.write, + "pool": self.pool, + } + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.connect == other.connect + and self.read == other.read + and self.write == other.write + and self.pool == other.pool + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + if len({self.connect, self.read, self.write, self.pool}) == 1: + return f"{class_name}(timeout={self.connect})" + return ( + f"{class_name}(connect={self.connect}, " + f"read={self.read}, write={self.write}, pool={self.pool})" + ) + + +class Limits: + """ + Configuration for limits to various client behaviors. + + **Parameters:** + + * **max_connections** - The maximum number of concurrent connections that may be + established. + * **max_keepalive_connections** - Allow the connection pool to maintain + keep-alive connections below this point. Should be less than or equal + to `max_connections`. + * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds. + """ + + def __init__( + self, + *, + max_connections: int | None = None, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = 5.0, + ) -> None: + self.max_connections = max_connections + self.max_keepalive_connections = max_keepalive_connections + self.keepalive_expiry = keepalive_expiry + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.max_connections == other.max_connections + and self.max_keepalive_connections == other.max_keepalive_connections + and self.keepalive_expiry == other.keepalive_expiry + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return ( + f"{class_name}(max_connections={self.max_connections}, " + f"max_keepalive_connections={self.max_keepalive_connections}, " + f"keepalive_expiry={self.keepalive_expiry})" + ) + + +class Proxy: + def __init__( + self, + url: URL | str, + *, + ssl_context: ssl.SSLContext | None = None, + auth: tuple[str, str] | None = None, + headers: HeaderTypes | None = None, + ) -> None: + url = URL(url) + headers = Headers(headers) + + if url.scheme not in ("http", "https", "socks5", "socks5h"): + raise ValueError(f"Unknown scheme for proxy URL {url!r}") + + if url.username or url.password: + # Remove any auth credentials from the URL. + auth = (url.username, url.password) + url = url.copy_with(username=None, password=None) + + self.url = url + self.auth = auth + self.headers = headers + self.ssl_context = ssl_context + + @property + def raw_auth(self) -> tuple[bytes, bytes] | None: + # The proxy authentication as raw bytes. + return ( + None + if self.auth is None + else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8")) + ) + + def __repr__(self) -> str: + # The authentication is represented with the password component masked. + auth = (self.auth[0], "********") if self.auth else None + + # Build a nice concise representation. + url_str = f"{str(self.url)!r}" + auth_str = f", auth={auth!r}" if auth else "" + headers_str = f", headers={dict(self.headers)!r}" if self.headers else "" + return f"Proxy({url_str}{auth_str}{headers_str})" + + +DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0) +DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20) +DEFAULT_MAX_REDIRECTS = 20 diff --git a/python_embeded/Lib/site-packages/httpx/_content.py b/python_embeded/Lib/site-packages/httpx/_content.py new file mode 100644 index 0000000000000000000000000000000000000000..6f479a0885f723b7395843d41164a87041820776 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_content.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +import inspect +import warnings +from json import dumps as json_dumps +from typing import ( + Any, + AsyncIterable, + AsyncIterator, + Iterable, + Iterator, + Mapping, +) +from urllib.parse import urlencode + +from ._exceptions import StreamClosed, StreamConsumed +from ._multipart import MultipartStream +from ._types import ( + AsyncByteStream, + RequestContent, + RequestData, + RequestFiles, + ResponseContent, + SyncByteStream, +) +from ._utils import peek_filelike_length, primitive_value_to_str + +__all__ = ["ByteStream"] + + +class ByteStream(AsyncByteStream, SyncByteStream): + def __init__(self, stream: bytes) -> None: + self._stream = stream + + def __iter__(self) -> Iterator[bytes]: + yield self._stream + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield self._stream + + +class IteratorByteStream(SyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: Iterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isgenerator(stream) + + def __iter__(self) -> Iterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "read"): + # File-like interfaces should use 'read' directly. + chunk = self._stream.read(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = self._stream.read(self.CHUNK_SIZE) + else: + # Otherwise iterate. + for part in self._stream: + yield part + + +class AsyncIteratorByteStream(AsyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: AsyncIterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isasyncgen(stream) + + async def __aiter__(self) -> AsyncIterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "aread"): + # File-like interfaces should use 'aread' directly. + chunk = await self._stream.aread(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = await self._stream.aread(self.CHUNK_SIZE) + else: + # Otherwise iterate. + async for part in self._stream: + yield part + + +class UnattachedStream(AsyncByteStream, SyncByteStream): + """ + If a request or response is serialized using pickle, then it is no longer + attached to a stream for I/O purposes. Any stream operations should result + in `httpx.StreamClosed`. + """ + + def __iter__(self) -> Iterator[bytes]: + raise StreamClosed() + + async def __aiter__(self) -> AsyncIterator[bytes]: + raise StreamClosed() + yield b"" # pragma: no cover + + +def encode_content( + content: str | bytes | Iterable[bytes] | AsyncIterable[bytes], +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + if isinstance(content, (bytes, str)): + body = content.encode("utf-8") if isinstance(content, str) else content + content_length = len(body) + headers = {"Content-Length": str(content_length)} if body else {} + return headers, ByteStream(body) + + elif isinstance(content, Iterable) and not isinstance(content, dict): + # `not isinstance(content, dict)` is a bit oddly specific, but it + # catches a case that's easy for users to make in error, and would + # otherwise pass through here, like any other bytes-iterable, + # because `dict` happens to be iterable. See issue #2491. + content_length_or_none = peek_filelike_length(content) + + if content_length_or_none is None: + headers = {"Transfer-Encoding": "chunked"} + else: + headers = {"Content-Length": str(content_length_or_none)} + return headers, IteratorByteStream(content) # type: ignore + + elif isinstance(content, AsyncIterable): + headers = {"Transfer-Encoding": "chunked"} + return headers, AsyncIteratorByteStream(content) + + raise TypeError(f"Unexpected type for 'content', {type(content)!r}") + + +def encode_urlencoded_data( + data: RequestData, +) -> tuple[dict[str, str], ByteStream]: + plain_data = [] + for key, value in data.items(): + if isinstance(value, (list, tuple)): + plain_data.extend([(key, primitive_value_to_str(item)) for item in value]) + else: + plain_data.append((key, primitive_value_to_str(value))) + body = urlencode(plain_data, doseq=True).encode("utf-8") + content_length = str(len(body)) + content_type = "application/x-www-form-urlencoded" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_multipart_data( + data: RequestData, files: RequestFiles, boundary: bytes | None +) -> tuple[dict[str, str], MultipartStream]: + multipart = MultipartStream(data=data, files=files, boundary=boundary) + headers = multipart.get_headers() + return headers, multipart + + +def encode_text(text: str) -> tuple[dict[str, str], ByteStream]: + body = text.encode("utf-8") + content_length = str(len(body)) + content_type = "text/plain; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_html(html: str) -> tuple[dict[str, str], ByteStream]: + body = html.encode("utf-8") + content_length = str(len(body)) + content_type = "text/html; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]: + body = json_dumps( + json, ensure_ascii=False, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + content_length = str(len(body)) + content_type = "application/json" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_request( + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: Any | None = None, + boundary: bytes | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, `data`, `files`, and `json`, + returning a two-tuple of (, ). + """ + if data is not None and not isinstance(data, Mapping): + # We prefer to separate `content=` + # for raw request content, and `data=
` for url encoded or + # multipart form content. + # + # However for compat with requests, we *do* still support + # `data=` usages. We deal with that case here, treating it + # as if `content=<...>` had been supplied instead. + message = "Use 'content=<...>' to upload raw bytes/text content." + warnings.warn(message, DeprecationWarning, stacklevel=2) + return encode_content(data) + + if content is not None: + return encode_content(content) + elif files: + return encode_multipart_data(data or {}, files, boundary) + elif data: + return encode_urlencoded_data(data) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") + + +def encode_response( + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: Any | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, returning a two-tuple of + (, ). + """ + if content is not None: + return encode_content(content) + elif text is not None: + return encode_text(text) + elif html is not None: + return encode_html(html) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") diff --git a/python_embeded/Lib/site-packages/httpx/_decoders.py b/python_embeded/Lib/site-packages/httpx/_decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..899dfada878e1181fca6d3c75a79526a076abb9e --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_decoders.py @@ -0,0 +1,393 @@ +""" +Handlers for Content-Encoding. + +See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding +""" + +from __future__ import annotations + +import codecs +import io +import typing +import zlib + +from ._exceptions import DecodingError + +# Brotli support is optional +try: + # The C bindings in `brotli` are recommended for CPython. + import brotli +except ImportError: # pragma: no cover + try: + # The CFFI bindings in `brotlicffi` are recommended for PyPy + # and other environments. + import brotlicffi as brotli + except ImportError: + brotli = None + + +# Zstandard support is optional +try: + import zstandard +except ImportError: # pragma: no cover + zstandard = None # type: ignore + + +class ContentDecoder: + def decode(self, data: bytes) -> bytes: + raise NotImplementedError() # pragma: no cover + + def flush(self) -> bytes: + raise NotImplementedError() # pragma: no cover + + +class IdentityDecoder(ContentDecoder): + """ + Handle unencoded data. + """ + + def decode(self, data: bytes) -> bytes: + return data + + def flush(self) -> bytes: + return b"" + + +class DeflateDecoder(ContentDecoder): + """ + Handle 'deflate' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.first_attempt = True + self.decompressor = zlib.decompressobj() + + def decode(self, data: bytes) -> bytes: + was_first_attempt = self.first_attempt + self.first_attempt = False + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + if was_first_attempt: + self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) + return self.decode(data) + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class GZipDecoder(ContentDecoder): + """ + Handle 'gzip' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16) + + def decode(self, data: bytes) -> bytes: + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class BrotliDecoder(ContentDecoder): + """ + Handle 'brotli' decoding. + + Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/ + or `pip install brotli`. See https://github.com/google/brotli + Supports both 'brotlipy' and 'Brotli' packages since they share an import + name. The top branches are for 'brotlipy' and bottom branches for 'Brotli' + """ + + def __init__(self) -> None: + if brotli is None: # pragma: no cover + raise ImportError( + "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' " + "packages have been installed. " + "Make sure to install httpx using `pip install httpx[brotli]`." + ) from None + + self.decompressor = brotli.Decompressor() + self.seen_data = False + self._decompress: typing.Callable[[bytes], bytes] + if hasattr(self.decompressor, "decompress"): + # The 'brotlicffi' package. + self._decompress = self.decompressor.decompress # pragma: no cover + else: + # The 'brotli' package. + self._decompress = self.decompressor.process # pragma: no cover + + def decode(self, data: bytes) -> bytes: + if not data: + return b"" + self.seen_data = True + try: + return self._decompress(data) + except brotli.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + try: + if hasattr(self.decompressor, "finish"): + # Only available in the 'brotlicffi' package. + + # As the decompressor decompresses eagerly, this + # will never actually emit any data. However, it will potentially throw + # errors if a truncated or damaged data stream has been used. + self.decompressor.finish() # pragma: no cover + return b"" + except brotli.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class ZStandardDecoder(ContentDecoder): + """ + Handle 'zstd' RFC 8878 decoding. + + Requires `pip install zstandard`. + Can be installed as a dependency of httpx using `pip install httpx[zstd]`. + """ + + # inspired by the ZstdDecoder implementation in urllib3 + def __init__(self) -> None: + if zstandard is None: # pragma: no cover + raise ImportError( + "Using 'ZStandardDecoder', ..." + "Make sure to install httpx using `pip install httpx[zstd]`." + ) from None + + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + self.seen_data = False + + def decode(self, data: bytes) -> bytes: + assert zstandard is not None + self.seen_data = True + output = io.BytesIO() + try: + output.write(self.decompressor.decompress(data)) + while self.decompressor.eof and self.decompressor.unused_data: + unused_data = self.decompressor.unused_data + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + output.write(self.decompressor.decompress(unused_data)) + except zstandard.ZstdError as exc: + raise DecodingError(str(exc)) from exc + return output.getvalue() + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + ret = self.decompressor.flush() # note: this is a no-op + if not self.decompressor.eof: + raise DecodingError("Zstandard data is incomplete") # pragma: no cover + return bytes(ret) + + +class MultiDecoder(ContentDecoder): + """ + Handle the case where multiple encodings have been applied. + """ + + def __init__(self, children: typing.Sequence[ContentDecoder]) -> None: + """ + 'children' should be a sequence of decoders in the order in which + each was applied. + """ + # Note that we reverse the order for decoding. + self.children = list(reversed(children)) + + def decode(self, data: bytes) -> bytes: + for child in self.children: + data = child.decode(data) + return data + + def flush(self) -> bytes: + data = b"" + for child in self.children: + data = child.decode(data) + child.flush() + return data + + +class ByteChunker: + """ + Handles returning byte content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.BytesIO() + self._chunk_size = chunk_size + + def decode(self, content: bytes) -> list[bytes]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[bytes]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextChunker: + """ + Handles returning text content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.StringIO() + self._chunk_size = chunk_size + + def decode(self, content: str) -> list[str]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[str]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextDecoder: + """ + Handles incrementally decoding bytes into text + """ + + def __init__(self, encoding: str = "utf-8") -> None: + self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace") + + def decode(self, data: bytes) -> str: + return self.decoder.decode(data) + + def flush(self) -> str: + return self.decoder.decode(b"", True) + + +class LineDecoder: + """ + Handles incrementally reading lines from text. + + Has the same behaviour as the stdllib splitlines, + but handling the input iteratively. + """ + + def __init__(self) -> None: + self.buffer: list[str] = [] + self.trailing_cr: bool = False + + def decode(self, text: str) -> list[str]: + # See https://docs.python.org/3/library/stdtypes.html#str.splitlines + NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029" + + # We always push a trailing `\r` into the next decode iteration. + if self.trailing_cr: + text = "\r" + text + self.trailing_cr = False + if text.endswith("\r"): + self.trailing_cr = True + text = text[:-1] + + if not text: + # NOTE: the edge case input of empty text doesn't occur in practice, + # because other httpx internals filter out this value + return [] # pragma: no cover + + trailing_newline = text[-1] in NEWLINE_CHARS + lines = text.splitlines() + + if len(lines) == 1 and not trailing_newline: + # No new lines, buffer the input and continue. + self.buffer.append(lines[0]) + return [] + + if self.buffer: + # Include any existing buffer in the first portion of the + # splitlines result. + lines = ["".join(self.buffer) + lines[0]] + lines[1:] + self.buffer = [] + + if not trailing_newline: + # If the last segment of splitlines is not newline terminated, + # then drop it from our output and start a new buffer. + self.buffer = [lines.pop()] + + return lines + + def flush(self) -> list[str]: + if not self.buffer and not self.trailing_cr: + return [] + + lines = ["".join(self.buffer)] + self.buffer = [] + self.trailing_cr = False + return lines + + +SUPPORTED_DECODERS = { + "identity": IdentityDecoder, + "gzip": GZipDecoder, + "deflate": DeflateDecoder, + "br": BrotliDecoder, + "zstd": ZStandardDecoder, +} + + +if brotli is None: + SUPPORTED_DECODERS.pop("br") # pragma: no cover +if zstandard is None: + SUPPORTED_DECODERS.pop("zstd") # pragma: no cover diff --git a/python_embeded/Lib/site-packages/httpx/_exceptions.py b/python_embeded/Lib/site-packages/httpx/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..77f45a6d3986d15626fc8a5fd459d6a3e0fbe466 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_exceptions.py @@ -0,0 +1,379 @@ +""" +Our exception hierarchy: + +* HTTPError + x RequestError + + TransportError + - TimeoutException + · ConnectTimeout + · ReadTimeout + · WriteTimeout + · PoolTimeout + - NetworkError + · ConnectError + · ReadError + · WriteError + · CloseError + - ProtocolError + · LocalProtocolError + · RemoteProtocolError + - ProxyError + - UnsupportedProtocol + + DecodingError + + TooManyRedirects + x HTTPStatusError +* InvalidURL +* CookieConflict +* StreamError + x StreamConsumed + x StreamClosed + x ResponseNotRead + x RequestNotRead +""" + +from __future__ import annotations + +import contextlib +import typing + +if typing.TYPE_CHECKING: + from ._models import Request, Response # pragma: no cover + +__all__ = [ + "CloseError", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "DecodingError", + "HTTPError", + "HTTPStatusError", + "InvalidURL", + "LocalProtocolError", + "NetworkError", + "PoolTimeout", + "ProtocolError", + "ProxyError", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "RequestError", + "RequestNotRead", + "ResponseNotRead", + "StreamClosed", + "StreamConsumed", + "StreamError", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "WriteError", + "WriteTimeout", +] + + +class HTTPError(Exception): + """ + Base class for `RequestError` and `HTTPStatusError`. + + Useful for `try...except` blocks when issuing a request, + and then calling `.raise_for_status()`. + + For example: + + ``` + try: + response = httpx.get("https://www.example.com") + response.raise_for_status() + except httpx.HTTPError as exc: + print(f"HTTP Exception for {exc.request.url} - {exc}") + ``` + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + self._request: Request | None = None + + @property + def request(self) -> Request: + if self._request is None: + raise RuntimeError("The .request property has not been set.") + return self._request + + @request.setter + def request(self, request: Request) -> None: + self._request = request + + +class RequestError(HTTPError): + """ + Base class for all exceptions that may occur when issuing a `.request()`. + """ + + def __init__(self, message: str, *, request: Request | None = None) -> None: + super().__init__(message) + # At the point an exception is raised we won't typically have a request + # instance to associate it with. + # + # The 'request_context' context manager is used within the Client and + # Response methods in order to ensure that any raised exceptions + # have a `.request` property set on them. + self._request = request + + +class TransportError(RequestError): + """ + Base class for all exceptions that occur at the level of the Transport API. + """ + + +# Timeout exceptions... + + +class TimeoutException(TransportError): + """ + The base class for timeout errors. + + An operation has timed out. + """ + + +class ConnectTimeout(TimeoutException): + """ + Timed out while connecting to the host. + """ + + +class ReadTimeout(TimeoutException): + """ + Timed out while receiving data from the host. + """ + + +class WriteTimeout(TimeoutException): + """ + Timed out while sending data to the host. + """ + + +class PoolTimeout(TimeoutException): + """ + Timed out waiting to acquire a connection from the pool. + """ + + +# Core networking exceptions... + + +class NetworkError(TransportError): + """ + The base class for network-related errors. + + An error occurred while interacting with the network. + """ + + +class ReadError(NetworkError): + """ + Failed to receive data from the network. + """ + + +class WriteError(NetworkError): + """ + Failed to send data through the network. + """ + + +class ConnectError(NetworkError): + """ + Failed to establish a connection. + """ + + +class CloseError(NetworkError): + """ + Failed to close a connection. + """ + + +# Other transport exceptions... + + +class ProxyError(TransportError): + """ + An error occurred while establishing a proxy connection. + """ + + +class UnsupportedProtocol(TransportError): + """ + Attempted to make a request to an unsupported protocol. + + For example issuing a request to `ftp://www.example.com`. + """ + + +class ProtocolError(TransportError): + """ + The protocol was violated. + """ + + +class LocalProtocolError(ProtocolError): + """ + A protocol was violated by the client. + + For example if the user instantiated a `Request` instance explicitly, + failed to include the mandatory `Host:` header, and then issued it directly + using `client.send()`. + """ + + +class RemoteProtocolError(ProtocolError): + """ + The protocol was violated by the server. + + For example, returning malformed HTTP. + """ + + +# Other request exceptions... + + +class DecodingError(RequestError): + """ + Decoding of the response failed, due to a malformed encoding. + """ + + +class TooManyRedirects(RequestError): + """ + Too many redirects. + """ + + +# Client errors + + +class HTTPStatusError(HTTPError): + """ + The response had an error HTTP status of 4xx or 5xx. + + May be raised when calling `response.raise_for_status()` + """ + + def __init__(self, message: str, *, request: Request, response: Response) -> None: + super().__init__(message) + self.request = request + self.response = response + + +class InvalidURL(Exception): + """ + URL is improperly formed or cannot be parsed. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class CookieConflict(Exception): + """ + Attempted to lookup a cookie by name, but multiple cookies existed. + + Can occur when calling `response.cookies.get(...)`. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +# Stream exceptions... + +# These may occur as the result of a programming error, by accessing +# the request/response stream in an invalid manner. + + +class StreamError(RuntimeError): + """ + The base class for stream exceptions. + + The developer made an error in accessing the request stream in + an invalid way. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class StreamConsumed(StreamError): + """ + Attempted to read or stream content, but the content has already + been streamed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. For requests, this could be due to passing " + "a generator as request content, and then receiving a redirect " + "response or a secondary request as part of an authentication flow." + "For responses, this could be due to attempting to stream the response " + "content more than once." + ) + super().__init__(message) + + +class StreamClosed(StreamError): + """ + Attempted to read or stream response content, but the request has been + closed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream content, but the stream has " "been closed." + ) + super().__init__(message) + + +class ResponseNotRead(StreamError): + """ + Attempted to access streaming response content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming response content," + " without having called `read()`." + ) + super().__init__(message) + + +class RequestNotRead(StreamError): + """ + Attempted to access streaming request content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming request content," + " without having called `read()`." + ) + super().__init__(message) + + +@contextlib.contextmanager +def request_context( + request: Request | None = None, +) -> typing.Iterator[None]: + """ + A context manager that can be used to attach the given request context + to any `RequestError` exceptions that are raised within the block. + """ + try: + yield + except RequestError as exc: + if request is not None: + exc.request = request + raise exc diff --git a/python_embeded/Lib/site-packages/httpx/_main.py b/python_embeded/Lib/site-packages/httpx/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..cffa4bb7db0f930f4db56653a061c4d7400ba4e6 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_main.py @@ -0,0 +1,506 @@ +from __future__ import annotations + +import functools +import json +import sys +import typing + +import click +import pygments.lexers +import pygments.util +import rich.console +import rich.markup +import rich.progress +import rich.syntax +import rich.table + +from ._client import Client +from ._exceptions import RequestError +from ._models import Response +from ._status_codes import codes + +if typing.TYPE_CHECKING: + import httpcore # pragma: no cover + + +def print_help() -> None: + console = rich.console.Console() + + console.print("[bold]HTTPX :butterfly:", justify="center") + console.print() + console.print("A next generation HTTP client.", justify="center") + console.print() + console.print( + "Usage: [bold]httpx[/bold] [cyan] [OPTIONS][/cyan] ", justify="left" + ) + console.print() + + table = rich.table.Table.grid(padding=1, pad_edge=True) + table.add_column("Parameter", no_wrap=True, justify="left", style="bold") + table.add_column("Description") + table.add_row( + "-m, --method [cyan]METHOD", + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n" + "[Default: GET, or POST if a request body is included]", + ) + table.add_row( + "-p, --params [cyan] ...", + "Query parameters to include in the request URL.", + ) + table.add_row( + "-c, --content [cyan]TEXT", "Byte content to include in the request body." + ) + table.add_row( + "-d, --data [cyan] ...", "Form data to include in the request body." + ) + table.add_row( + "-f, --files [cyan] ...", + "Form files to include in the request body.", + ) + table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.") + table.add_row( + "-h, --headers [cyan] ...", + "Include additional HTTP headers in the request.", + ) + table.add_row( + "--cookies [cyan] ...", "Cookies to include in the request." + ) + table.add_row( + "--auth [cyan]", + "Username and password to include in the request. Specify '-' for the password" + " to use a password prompt. Note that using --verbose/-v will expose" + " the Authorization header, including the password encoding" + " in a trivially reversible format.", + ) + + table.add_row( + "--proxy [cyan]URL", + "Send the request via a proxy. Should be the URL giving the proxy address.", + ) + + table.add_row( + "--timeout [cyan]FLOAT", + "Timeout value to use for network operations, such as establishing the" + " connection, reading some data, etc... [Default: 5.0]", + ) + + table.add_row("--follow-redirects", "Automatically follow redirects.") + table.add_row("--no-verify", "Disable SSL verification.") + table.add_row( + "--http2", "Send the request using HTTP/2, if the remote server supports it." + ) + + table.add_row( + "--download [cyan]FILE", + "Save the response content as a file, rather than displaying it.", + ) + + table.add_row("-v, --verbose", "Verbose output. Show request as well as response.") + table.add_row("--help", "Show this message and exit.") + console.print(table) + + +def get_lexer_for_response(response: Response) -> str: + content_type = response.headers.get("Content-Type") + if content_type is not None: + mime_type, _, _ = content_type.partition(";") + try: + return typing.cast( + str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name + ) + except pygments.util.ClassNotFound: # pragma: no cover + pass + return "" # pragma: no cover + + +def format_request_headers(request: httpcore.Request, http2: bool = False) -> str: + version = "HTTP/2" if http2 else "HTTP/1.1" + headers = [ + (name.lower() if http2 else name, value) for name, value in request.headers + ] + method = request.method.decode("ascii") + target = request.url.target.decode("ascii") + lines = [f"{method} {target} {version}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def format_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> str: + version = http_version.decode("ascii") + reason = ( + codes.get_reason_phrase(status) + if reason_phrase is None + else reason_phrase.decode("ascii") + ) + lines = [f"{version} {status} {reason}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def print_request_headers(request: httpcore.Request, http2: bool = False) -> None: + console = rich.console.Console() + http_text = format_request_headers(request, http2=http2) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> None: + console = rich.console.Console() + http_text = format_response_headers(http_version, status, reason_phrase, headers) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response(response: Response) -> None: + console = rich.console.Console() + lexer_name = get_lexer_for_response(response) + if lexer_name: + if lexer_name.lower() == "json": + try: + data = response.json() + text = json.dumps(data, indent=4) + except ValueError: # pragma: no cover + text = response.text + else: + text = response.text + + syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True) + console.print(syntax) + else: + console.print(f"<{len(response.content)} bytes of binary data>") + + +_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...] +_PCTRTTT = typing.Tuple[_PCTRTT, ...] +_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]] + + +def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover + lines = [] + for key, value in cert.items(): + if isinstance(value, (list, tuple)): + lines.append(f"* {key}:") + for item in value: + if key in ("subject", "issuer"): + for sub_item in item: + lines.append(f"* {sub_item[0]}: {sub_item[1]!r}") + elif isinstance(item, tuple) and len(item) == 2: + lines.append(f"* {item[0]}: {item[1]!r}") + else: + lines.append(f"* {item!r}") + else: + lines.append(f"* {key}: {value!r}") + return "\n".join(lines) + + +def trace( + name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False +) -> None: + console = rich.console.Console() + if name == "connection.connect_tcp.started" and verbose: + host = info["host"] + console.print(f"* Connecting to {host!r}") + elif name == "connection.connect_tcp.complete" and verbose: + stream = info["return_value"] + server_addr = stream.get_extra_info("server_addr") + console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}") + elif name == "connection.start_tls.complete" and verbose: # pragma: no cover + stream = info["return_value"] + ssl_object = stream.get_extra_info("ssl_object") + version = ssl_object.version() + cipher = ssl_object.cipher() + server_cert = ssl_object.getpeercert() + alpn = ssl_object.selected_alpn_protocol() + console.print(f"* SSL established using {version!r} / {cipher[0]!r}") + console.print(f"* Selected ALPN protocol: {alpn!r}") + if server_cert: + console.print("* Server certificate:") + console.print(format_certificate(server_cert)) + elif name == "http11.send_request_headers.started" and verbose: + request = info["request"] + print_request_headers(request, http2=False) + elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover + request = info["request"] + print_request_headers(request, http2=True) + elif name == "http11.receive_response_headers.complete": + http_version, status, reason_phrase, headers = info["return_value"] + print_response_headers(http_version, status, reason_phrase, headers) + elif name == "http2.receive_response_headers.complete": # pragma: no cover + status, headers = info["return_value"] + http_version = b"HTTP/2" + reason_phrase = None + print_response_headers(http_version, status, reason_phrase, headers) + + +def download_response(response: Response, download: typing.BinaryIO) -> None: + console = rich.console.Console() + console.print() + content_length = response.headers.get("Content-Length") + with rich.progress.Progress( + "[progress.description]{task.description}", + "[progress.percentage]{task.percentage:>3.0f}%", + rich.progress.BarColumn(bar_width=None), + rich.progress.DownloadColumn(), + rich.progress.TransferSpeedColumn(), + ) as progress: + description = f"Downloading [bold]{rich.markup.escape(download.name)}" + download_task = progress.add_task( + description, + total=int(content_length or 0), + start=content_length is not None, + ) + for chunk in response.iter_bytes(): + download.write(chunk) + progress.update(download_task, completed=response.num_bytes_downloaded) + + +def validate_json( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value is None: + return None + + try: + return json.loads(value) + except json.JSONDecodeError: # pragma: no cover + raise click.BadParameter("Not valid JSON") + + +def validate_auth( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value == (None, None): + return None + + username, password = value + if password == "-": # pragma: no cover + password = click.prompt("Password", hide_input=True) + return (username, password) + + +def handle_help( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> None: + if not value or ctx.resilient_parsing: + return + + print_help() + ctx.exit() + + +@click.command(add_help_option=False) +@click.argument("url", type=str) +@click.option( + "--method", + "-m", + "method", + type=str, + help=( + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. " + "[Default: GET, or POST if a request body is included]" + ), +) +@click.option( + "--params", + "-p", + "params", + type=(str, str), + multiple=True, + help="Query parameters to include in the request URL.", +) +@click.option( + "--content", + "-c", + "content", + type=str, + help="Byte content to include in the request body.", +) +@click.option( + "--data", + "-d", + "data", + type=(str, str), + multiple=True, + help="Form data to include in the request body.", +) +@click.option( + "--files", + "-f", + "files", + type=(str, click.File(mode="rb")), + multiple=True, + help="Form files to include in the request body.", +) +@click.option( + "--json", + "-j", + "json", + type=str, + callback=validate_json, + help="JSON data to include in the request body.", +) +@click.option( + "--headers", + "-h", + "headers", + type=(str, str), + multiple=True, + help="Include additional HTTP headers in the request.", +) +@click.option( + "--cookies", + "cookies", + type=(str, str), + multiple=True, + help="Cookies to include in the request.", +) +@click.option( + "--auth", + "auth", + type=(str, str), + default=(None, None), + callback=validate_auth, + help=( + "Username and password to include in the request. " + "Specify '-' for the password to use a password prompt. " + "Note that using --verbose/-v will expose the Authorization header, " + "including the password encoding in a trivially reversible format." + ), +) +@click.option( + "--proxy", + "proxy", + type=str, + default=None, + help="Send the request via a proxy. Should be the URL giving the proxy address.", +) +@click.option( + "--timeout", + "timeout", + type=float, + default=5.0, + help=( + "Timeout value to use for network operations, such as establishing the " + "connection, reading some data, etc... [Default: 5.0]" + ), +) +@click.option( + "--follow-redirects", + "follow_redirects", + is_flag=True, + default=False, + help="Automatically follow redirects.", +) +@click.option( + "--no-verify", + "verify", + is_flag=True, + default=True, + help="Disable SSL verification.", +) +@click.option( + "--http2", + "http2", + type=bool, + is_flag=True, + default=False, + help="Send the request using HTTP/2, if the remote server supports it.", +) +@click.option( + "--download", + type=click.File("wb"), + help="Save the response content as a file, rather than displaying it.", +) +@click.option( + "--verbose", + "-v", + type=bool, + is_flag=True, + default=False, + help="Verbose. Show request as well as response.", +) +@click.option( + "--help", + is_flag=True, + is_eager=True, + expose_value=False, + callback=handle_help, + help="Show this message and exit.", +) +def main( + url: str, + method: str, + params: list[tuple[str, str]], + content: str, + data: list[tuple[str, str]], + files: list[tuple[str, click.File]], + json: str, + headers: list[tuple[str, str]], + cookies: list[tuple[str, str]], + auth: tuple[str, str] | None, + proxy: str, + timeout: float, + follow_redirects: bool, + verify: bool, + http2: bool, + download: typing.BinaryIO | None, + verbose: bool, +) -> None: + """ + An HTTP command line client. + Sends a request and displays the response. + """ + if not method: + method = "POST" if content or data or files or json else "GET" + + try: + with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client: + with client.stream( + method, + url, + params=list(params), + content=content, + data=dict(data), + files=files, # type: ignore + json=json, + headers=headers, + cookies=dict(cookies), + auth=auth, + follow_redirects=follow_redirects, + extensions={"trace": functools.partial(trace, verbose=verbose)}, + ) as response: + if download is not None: + download_response(response, download) + else: + response.read() + if response.content: + print_response(response) + + except RequestError as exc: + console = rich.console.Console() + console.print(f"[red]{type(exc).__name__}[/red]: {exc}") + sys.exit(1) + + sys.exit(0 if response.is_success else 1) diff --git a/python_embeded/Lib/site-packages/httpx/_models.py b/python_embeded/Lib/site-packages/httpx/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..67d74bf86bfc80e22d9a4a3153572845accd9039 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_models.py @@ -0,0 +1,1277 @@ +from __future__ import annotations + +import codecs +import datetime +import email.message +import json as jsonlib +import re +import typing +import urllib.request +from collections.abc import Mapping +from http.cookiejar import Cookie, CookieJar + +from ._content import ByteStream, UnattachedStream, encode_request, encode_response +from ._decoders import ( + SUPPORTED_DECODERS, + ByteChunker, + ContentDecoder, + IdentityDecoder, + LineDecoder, + MultiDecoder, + TextChunker, + TextDecoder, +) +from ._exceptions import ( + CookieConflict, + HTTPStatusError, + RequestNotRead, + ResponseNotRead, + StreamClosed, + StreamConsumed, + request_context, +) +from ._multipart import get_multipart_boundary_from_content_type +from ._status_codes import codes +from ._types import ( + AsyncByteStream, + CookieTypes, + HeaderTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + ResponseContent, + ResponseExtensions, + SyncByteStream, +) +from ._urls import URL +from ._utils import to_bytes_or_str, to_str + +__all__ = ["Cookies", "Headers", "Request", "Response"] + +SENSITIVE_HEADERS = {"authorization", "proxy-authorization"} + + +def _is_known_encoding(encoding: str) -> bool: + """ + Return `True` if `encoding` is a known codec. + """ + try: + codecs.lookup(encoding) + except LookupError: + return False + return True + + +def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header key. + """ + return key if isinstance(key, bytes) else key.encode(encoding or "ascii") + + +def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header value. + """ + if isinstance(value, bytes): + return value + if not isinstance(value, str): + raise TypeError(f"Header value must be str or bytes, not {type(value)}") + return value.encode(encoding or "ascii") + + +def _parse_content_type_charset(content_type: str) -> str | None: + # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery. + # See: https://peps.python.org/pep-0594/#cgi + msg = email.message.Message() + msg["content-type"] = content_type + return msg.get_content_charset(failobj=None) + + +def _parse_header_links(value: str) -> list[dict[str, str]]: + """ + Returns a list of parsed link headers, for more info see: + https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link + The generic syntax of those is: + Link: < uri-reference >; param1=value1; param2="value2" + So for instance: + Link; '; type="image/jpeg",;' + would return + [ + {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, + {"url": "http://.../back.jpeg"}, + ] + :param value: HTTP Link entity-header field + :return: list of parsed link headers + """ + links: list[dict[str, str]] = [] + replace_chars = " '\"" + value = value.strip(replace_chars) + if not value: + return links + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + link = {"url": url.strip("<> '\"")} + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + link[key.strip(replace_chars)] = value.strip(replace_chars) + links.append(link) + return links + + +def _obfuscate_sensitive_headers( + items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]], +) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]: + for k, v in items: + if to_str(k.lower()) in SENSITIVE_HEADERS: + v = to_bytes_or_str("[secure]", match_type_of=v) + yield k, v + + +class Headers(typing.MutableMapping[str, str]): + """ + HTTP headers, as a case-insensitive multi-dict. + """ + + def __init__( + self, + headers: HeaderTypes | None = None, + encoding: str | None = None, + ) -> None: + self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]] + + if isinstance(headers, Headers): + self._list = list(headers._list) + elif isinstance(headers, Mapping): + for k, v in headers.items(): + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + elif headers is not None: + for k, v in headers: + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + + self._encoding = encoding + + @property + def encoding(self) -> str: + """ + Header encoding is mandated as ascii, but we allow fallbacks to utf-8 + or iso-8859-1. + """ + if self._encoding is None: + for encoding in ["ascii", "utf-8"]: + for key, value in self.raw: + try: + key.decode(encoding) + value.decode(encoding) + except UnicodeDecodeError: + break + else: + # The else block runs if 'break' did not occur, meaning + # all values fitted the encoding. + self._encoding = encoding + break + else: + # The ISO-8859-1 encoding covers all 256 code points in a byte, + # so will never raise decode errors. + self._encoding = "iso-8859-1" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + self._encoding = value + + @property + def raw(self) -> list[tuple[bytes, bytes]]: + """ + Returns a list of the raw header items, as byte pairs. + """ + return [(raw_key, value) for raw_key, _, value in self._list] + + def keys(self) -> typing.KeysView[str]: + return {key.decode(self.encoding): None for _, key, value in self._list}.keys() + + def values(self) -> typing.ValuesView[str]: + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return `(key, value)` items of headers. Concatenate headers + into a single comma separated value when a key occurs multiple times. + """ + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return a list of `(key, value)` pairs of headers. Allow multiple + occurrences of the same key without concatenating into a single + comma separated value. + """ + return [ + (key.decode(self.encoding), value.decode(self.encoding)) + for _, key, value in self._list + ] + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Return a header value. If multiple occurrences of the header occur + then concatenate them together with commas. + """ + try: + return self[key] + except KeyError: + return default + + def get_list(self, key: str, split_commas: bool = False) -> list[str]: + """ + Return a list of all header values for a given key. + If `split_commas=True` is passed, then any comma separated header + values are split into multiple return strings. + """ + get_header_key = key.lower().encode(self.encoding) + + values = [ + item_value.decode(self.encoding) + for _, item_key, item_value in self._list + if item_key.lower() == get_header_key + ] + + if not split_commas: + return values + + split_values = [] + for value in values: + split_values.extend([item.strip() for item in value.split(",")]) + return split_values + + def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore + headers = Headers(headers) + for key in headers.keys(): + if key in self: + self.pop(key) + self._list.extend(headers._list) + + def copy(self) -> Headers: + return Headers(self, encoding=self.encoding) + + def __getitem__(self, key: str) -> str: + """ + Return a single header value. + + If there are multiple headers with the same key, then we concatenate + them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2 + """ + normalized_key = key.lower().encode(self.encoding) + + items = [ + header_value.decode(self.encoding) + for _, header_key, header_value in self._list + if header_key == normalized_key + ] + + if items: + return ", ".join(items) + + raise KeyError(key) + + def __setitem__(self, key: str, value: str) -> None: + """ + Set the header `key` to `value`, removing any duplicate entries. + Retains insertion order. + """ + set_key = key.encode(self._encoding or "utf-8") + set_value = value.encode(self._encoding or "utf-8") + lookup_key = set_key.lower() + + found_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key == lookup_key + ] + + for idx in reversed(found_indexes[1:]): + del self._list[idx] + + if found_indexes: + idx = found_indexes[0] + self._list[idx] = (set_key, lookup_key, set_value) + else: + self._list.append((set_key, lookup_key, set_value)) + + def __delitem__(self, key: str) -> None: + """ + Remove the header `key`. + """ + del_key = key.lower().encode(self.encoding) + + pop_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key.lower() == del_key + ] + + if not pop_indexes: + raise KeyError(key) + + for idx in reversed(pop_indexes): + del self._list[idx] + + def __contains__(self, key: typing.Any) -> bool: + header_key = key.lower().encode(self.encoding) + return header_key in [key for _, key, _ in self._list] + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._list) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_headers = Headers(other) + except ValueError: + return False + + self_list = [(key, value) for _, key, value in self._list] + other_list = [(key, value) for _, key, value in other_headers._list] + return sorted(self_list) == sorted(other_list) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + + encoding_str = "" + if self.encoding != "ascii": + encoding_str = f", encoding={self.encoding!r}" + + as_list = list(_obfuscate_sensitive_headers(self.multi_items())) + as_dict = dict(as_list) + + no_duplicate_keys = len(as_dict) == len(as_list) + if no_duplicate_keys: + return f"{class_name}({as_dict!r}{encoding_str})" + return f"{class_name}({as_list!r}{encoding_str})" + + +class Request: + def __init__( + self, + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + stream: SyncByteStream | AsyncByteStream | None = None, + extensions: RequestExtensions | None = None, + ) -> None: + self.method = method.upper() + self.url = URL(url) if params is None else URL(url, params=params) + self.headers = Headers(headers) + self.extensions = {} if extensions is None else dict(extensions) + + if cookies: + Cookies(cookies).set_cookie_header(self) + + if stream is None: + content_type: str | None = self.headers.get("content-type") + headers, stream = encode_request( + content=content, + data=data, + files=files, + json=json, + boundary=get_multipart_boundary_from_content_type( + content_type=content_type.encode(self.headers.encoding) + if content_type + else None + ), + ) + self._prepare(headers) + self.stream = stream + # Load the request body, except for streaming content. + if isinstance(stream, ByteStream): + self.read() + else: + # There's an important distinction between `Request(content=...)`, + # and `Request(stream=...)`. + # + # Using `content=...` implies automatically populated `Host` and content + # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include *any* + # auto-populated headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when: + # + # * Preserving the request stream when copying requests, eg for redirects. + # * Creating request instances on the *server-side* of the transport API. + self.stream = stream + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "Content-Length" in self.headers: + continue + self.headers.setdefault(key, value) + + auto_headers: list[tuple[bytes, bytes]] = [] + + has_host = "Host" in self.headers + has_content_length = ( + "Content-Length" in self.headers or "Transfer-Encoding" in self.headers + ) + + if not has_host and self.url.host: + auto_headers.append((b"Host", self.url.netloc)) + if not has_content_length and self.method in ("POST", "PUT", "PATCH"): + auto_headers.append((b"Content-Length", b"0")) + + self.headers = Headers(auto_headers + self.headers.raw) + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise RequestNotRead() + return self._content + + def read(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.Iterable) + self._content = b"".join(self.stream) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + async def aread(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.AsyncIterable) + self._content = b"".join([part async for part in self.stream]) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + url = str(self.url) + return f"<{class_name}({self.method!r}, {url!r})>" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.extensions = {} + self.stream = UnattachedStream() + + +class Response: + def __init__( + self, + status_code: int, + *, + headers: HeaderTypes | None = None, + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: typing.Any = None, + stream: SyncByteStream | AsyncByteStream | None = None, + request: Request | None = None, + extensions: ResponseExtensions | None = None, + history: list[Response] | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + self.status_code = status_code + self.headers = Headers(headers) + + self._request: Request | None = request + + # When follow_redirects=False and a redirect is received, + # the client will set `response.next_request`. + self.next_request: Request | None = None + + self.extensions = {} if extensions is None else dict(extensions) + self.history = [] if history is None else list(history) + + self.is_closed = False + self.is_stream_consumed = False + + self.default_encoding = default_encoding + + if stream is None: + headers, stream = encode_response(content, text, html, json) + self._prepare(headers) + self.stream = stream + if isinstance(stream, ByteStream): + # Load the response body, except for streaming content. + self.read() + else: + # There's an important distinction between `Response(content=...)`, + # and `Response(stream=...)`. + # + # Using `content=...` implies automatically populated content headers, + # of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include any content headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when creating response instances having received a stream + # from the transport API. + self.stream = stream + + self._num_bytes_downloaded = 0 + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "content-length" in self.headers: + continue + self.headers.setdefault(key, value) + + @property + def elapsed(self) -> datetime.timedelta: + """ + Returns the time taken for the complete request/response + cycle to complete. + """ + if not hasattr(self, "_elapsed"): + raise RuntimeError( + "'.elapsed' may only be accessed after the response " + "has been read or closed." + ) + return self._elapsed + + @elapsed.setter + def elapsed(self, elapsed: datetime.timedelta) -> None: + self._elapsed = elapsed + + @property + def request(self) -> Request: + """ + Returns the request instance associated to the current response. + """ + if self._request is None: + raise RuntimeError( + "The request instance has not been set on this response." + ) + return self._request + + @request.setter + def request(self, value: Request) -> None: + self._request = value + + @property + def http_version(self) -> str: + try: + http_version: bytes = self.extensions["http_version"] + except KeyError: + return "HTTP/1.1" + else: + return http_version.decode("ascii", errors="ignore") + + @property + def reason_phrase(self) -> str: + try: + reason_phrase: bytes = self.extensions["reason_phrase"] + except KeyError: + return codes.get_reason_phrase(self.status_code) + else: + return reason_phrase.decode("ascii", errors="ignore") + + @property + def url(self) -> URL: + """ + Returns the URL for which the request was made. + """ + return self.request.url + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise ResponseNotRead() + return self._content + + @property + def text(self) -> str: + if not hasattr(self, "_text"): + content = self.content + if not content: + self._text = "" + else: + decoder = TextDecoder(encoding=self.encoding or "utf-8") + self._text = "".join([decoder.decode(self.content), decoder.flush()]) + return self._text + + @property + def encoding(self) -> str | None: + """ + Return an encoding to use for decoding the byte content into text. + The priority for determining this is given by... + + * `.encoding = <>` has been set explicitly. + * The encoding as specified by the charset parameter in the Content-Type header. + * The encoding as determined by `default_encoding`, which may either be + a string like "utf-8" indicating the encoding to use, or may be a callable + which enables charset autodetection. + """ + if not hasattr(self, "_encoding"): + encoding = self.charset_encoding + if encoding is None or not _is_known_encoding(encoding): + if isinstance(self.default_encoding, str): + encoding = self.default_encoding + elif hasattr(self, "_content"): + encoding = self.default_encoding(self._content) + self._encoding = encoding or "utf-8" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + """ + Set the encoding to use for decoding the byte content into text. + + If the `text` attribute has been accessed, attempting to set the + encoding will throw a ValueError. + """ + if hasattr(self, "_text"): + raise ValueError( + "Setting encoding after `text` has been accessed is not allowed." + ) + self._encoding = value + + @property + def charset_encoding(self) -> str | None: + """ + Return the encoding, as specified by the Content-Type header. + """ + content_type = self.headers.get("Content-Type") + if content_type is None: + return None + + return _parse_content_type_charset(content_type) + + def _get_content_decoder(self) -> ContentDecoder: + """ + Returns a decoder instance which can be used to decode the raw byte + content, depending on the Content-Encoding used in the response. + """ + if not hasattr(self, "_decoder"): + decoders: list[ContentDecoder] = [] + values = self.headers.get_list("content-encoding", split_commas=True) + for value in values: + value = value.strip().lower() + try: + decoder_cls = SUPPORTED_DECODERS[value] + decoders.append(decoder_cls()) + except KeyError: + continue + + if len(decoders) == 1: + self._decoder = decoders[0] + elif len(decoders) > 1: + self._decoder = MultiDecoder(children=decoders) + else: + self._decoder = IdentityDecoder() + + return self._decoder + + @property + def is_informational(self) -> bool: + """ + A property which is `True` for 1xx status codes, `False` otherwise. + """ + return codes.is_informational(self.status_code) + + @property + def is_success(self) -> bool: + """ + A property which is `True` for 2xx status codes, `False` otherwise. + """ + return codes.is_success(self.status_code) + + @property + def is_redirect(self) -> bool: + """ + A property which is `True` for 3xx status codes, `False` otherwise. + + Note that not all responses with a 3xx status code indicate a URL redirect. + + Use `response.has_redirect_location` to determine responses with a properly + formed URL redirection. + """ + return codes.is_redirect(self.status_code) + + @property + def is_client_error(self) -> bool: + """ + A property which is `True` for 4xx status codes, `False` otherwise. + """ + return codes.is_client_error(self.status_code) + + @property + def is_server_error(self) -> bool: + """ + A property which is `True` for 5xx status codes, `False` otherwise. + """ + return codes.is_server_error(self.status_code) + + @property + def is_error(self) -> bool: + """ + A property which is `True` for 4xx and 5xx status codes, `False` otherwise. + """ + return codes.is_error(self.status_code) + + @property + def has_redirect_location(self) -> bool: + """ + Returns True for 3xx responses with a properly formed URL redirection, + `False` otherwise. + """ + return ( + self.status_code + in ( + # 301 (Cacheable redirect. Method may change to GET.) + codes.MOVED_PERMANENTLY, + # 302 (Uncacheable redirect. Method may change to GET.) + codes.FOUND, + # 303 (Client should make a GET or HEAD request.) + codes.SEE_OTHER, + # 307 (Equiv. 302, but retain method) + codes.TEMPORARY_REDIRECT, + # 308 (Equiv. 301, but retain method) + codes.PERMANENT_REDIRECT, + ) + and "Location" in self.headers + ) + + def raise_for_status(self) -> Response: + """ + Raise the `HTTPStatusError` if one occurred. + """ + request = self._request + if request is None: + raise RuntimeError( + "Cannot call `raise_for_status` as the request " + "instance has not been set on this response." + ) + + if self.is_success: + return self + + if self.has_redirect_location: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "Redirect location: '{0.headers[location]}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + else: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + + status_class = self.status_code // 100 + error_types = { + 1: "Informational response", + 3: "Redirect response", + 4: "Client error", + 5: "Server error", + } + error_type = error_types.get(status_class, "Invalid status code") + message = message.format(self, error_type=error_type) + raise HTTPStatusError(message, request=request, response=self) + + def json(self, **kwargs: typing.Any) -> typing.Any: + return jsonlib.loads(self.content, **kwargs) + + @property + def cookies(self) -> Cookies: + if not hasattr(self, "_cookies"): + self._cookies = Cookies() + self._cookies.extract_cookies(self) + return self._cookies + + @property + def links(self) -> dict[str | None, dict[str, str]]: + """ + Returns the parsed header links of the response, if any + """ + header = self.headers.get("link") + if header is None: + return {} + + return { + (link.get("rel") or link.get("url")): link + for link in _parse_header_links(header) + } + + @property + def num_bytes_downloaded(self) -> int: + return self._num_bytes_downloaded + + def __repr__(self) -> str: + return f"" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream", "is_closed", "_decoder"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.is_closed = True + self.extensions = {} + self.stream = UnattachedStream() + + def read(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join(self.iter_bytes()) + return self._content + + def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for raw_bytes in self.iter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for byte_content in self.iter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_lines(self) -> typing.Iterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + for text in self.iter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call a sync iterator on an async stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call an sync close on an async stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + self.stream.close() + + async def aread(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_bytes()]) + return self._content + + async def aiter_bytes( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for raw_bytes in self.aiter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_text( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for byte_content in self.aiter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_lines(self) -> typing.AsyncIterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + async for text in self.aiter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + async def aiter_raw( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async iterator on an sync stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + async for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + await self.aclose() + + async def aclose(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async close on an sync stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + await self.stream.aclose() + + +class Cookies(typing.MutableMapping[str, str]): + """ + HTTP Cookies, as a mutable mapping. + """ + + def __init__(self, cookies: CookieTypes | None = None) -> None: + if cookies is None or isinstance(cookies, dict): + self.jar = CookieJar() + if isinstance(cookies, dict): + for key, value in cookies.items(): + self.set(key, value) + elif isinstance(cookies, list): + self.jar = CookieJar() + for key, value in cookies: + self.set(key, value) + elif isinstance(cookies, Cookies): + self.jar = CookieJar() + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + else: + self.jar = cookies + + def extract_cookies(self, response: Response) -> None: + """ + Loads any cookies based on the response `Set-Cookie` headers. + """ + urllib_response = self._CookieCompatResponse(response) + urllib_request = self._CookieCompatRequest(response.request) + + self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore + + def set_cookie_header(self, request: Request) -> None: + """ + Sets an appropriate 'Cookie:' HTTP header on the `Request`. + """ + urllib_request = self._CookieCompatRequest(request) + self.jar.add_cookie_header(urllib_request) + + def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None: + """ + Set a cookie value by name. May optionally include domain and path. + """ + kwargs = { + "version": 0, + "name": name, + "value": value, + "port": None, + "port_specified": False, + "domain": domain, + "domain_specified": bool(domain), + "domain_initial_dot": domain.startswith("."), + "path": path, + "path_specified": bool(path), + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + cookie = Cookie(**kwargs) # type: ignore + self.jar.set_cookie(cookie) + + def get( # type: ignore + self, + name: str, + default: str | None = None, + domain: str | None = None, + path: str | None = None, + ) -> str | None: + """ + Get a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to retrieve. + """ + value = None + for cookie in self.jar: + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if value is not None: + message = f"Multiple cookies exist with name={name}" + raise CookieConflict(message) + value = cookie.value + + if value is None: + return default + return value + + def delete( + self, + name: str, + domain: str | None = None, + path: str | None = None, + ) -> None: + """ + Delete a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to delete. + """ + if domain is not None and path is not None: + return self.jar.clear(domain, path, name) + + remove = [ + cookie + for cookie in self.jar + if cookie.name == name + and (domain is None or cookie.domain == domain) + and (path is None or cookie.path == path) + ] + + for cookie in remove: + self.jar.clear(cookie.domain, cookie.path, cookie.name) + + def clear(self, domain: str | None = None, path: str | None = None) -> None: + """ + Delete all cookies. Optionally include a domain and path in + order to only delete a subset of all the cookies. + """ + args = [] + if domain is not None: + args.append(domain) + if path is not None: + assert domain is not None + args.append(path) + self.jar.clear(*args) + + def update(self, cookies: CookieTypes | None = None) -> None: # type: ignore + cookies = Cookies(cookies) + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + + def __setitem__(self, name: str, value: str) -> None: + return self.set(name, value) + + def __getitem__(self, name: str) -> str: + value = self.get(name) + if value is None: + raise KeyError(name) + return value + + def __delitem__(self, name: str) -> None: + return self.delete(name) + + def __len__(self) -> int: + return len(self.jar) + + def __iter__(self) -> typing.Iterator[str]: + return (cookie.name for cookie in self.jar) + + def __bool__(self) -> bool: + for _ in self.jar: + return True + return False + + def __repr__(self) -> str: + cookies_repr = ", ".join( + [ + f"" + for cookie in self.jar + ] + ) + + return f"" + + class _CookieCompatRequest(urllib.request.Request): + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, request: Request) -> None: + super().__init__( + url=str(request.url), + headers=dict(request.headers), + method=request.method, + ) + self.request = request + + def add_unredirected_header(self, key: str, value: str) -> None: + super().add_unredirected_header(key, value) + self.request.headers[key] = value + + class _CookieCompatResponse: + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, response: Response) -> None: + self.response = response + + def info(self) -> email.message.Message: + info = email.message.Message() + for key, value in self.response.headers.multi_items(): + # Note that setting `info[key]` here is an "append" operation, + # not a "replace" operation. + # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__ + info[key] = value + return info diff --git a/python_embeded/Lib/site-packages/httpx/_multipart.py b/python_embeded/Lib/site-packages/httpx/_multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..b4761af9b2cf384de5189269927d781a700dbe46 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_multipart.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +import io +import mimetypes +import os +import re +import typing +from pathlib import Path + +from ._types import ( + AsyncByteStream, + FileContent, + FileTypes, + RequestData, + RequestFiles, + SyncByteStream, +) +from ._utils import ( + peek_filelike_length, + primitive_value_to_str, + to_bytes, +) + +_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"} +_HTML5_FORM_ENCODING_REPLACEMENTS.update( + {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B} +) +_HTML5_FORM_ENCODING_RE = re.compile( + r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]) +) + + +def _format_form_param(name: str, value: str) -> bytes: + """ + Encode a name/value pair within a multipart form. + """ + + def replacer(match: typing.Match[str]) -> str: + return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)] + + value = _HTML5_FORM_ENCODING_RE.sub(replacer, value) + return f'{name}="{value}"'.encode() + + +def _guess_content_type(filename: str | None) -> str | None: + """ + Guesses the mimetype based on a filename. Defaults to `application/octet-stream`. + + Returns `None` if `filename` is `None` or empty. + """ + if filename: + return mimetypes.guess_type(filename)[0] or "application/octet-stream" + return None + + +def get_multipart_boundary_from_content_type( + content_type: bytes | None, +) -> bytes | None: + if not content_type or not content_type.startswith(b"multipart/form-data"): + return None + # parse boundary according to + # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1 + if b";" in content_type: + for section in content_type.split(b";"): + if section.strip().lower().startswith(b"boundary="): + return section.strip()[len(b"boundary=") :].strip(b'"') + return None + + +class DataField: + """ + A single form field item, within a multipart form field. + """ + + def __init__(self, name: str, value: str | bytes | int | float | None) -> None: + if not isinstance(name, str): + raise TypeError( + f"Invalid type for name. Expected str, got {type(name)}: {name!r}" + ) + if value is not None and not isinstance(value, (str, bytes, int, float)): + raise TypeError( + "Invalid type for value. Expected primitive type," + f" got {type(value)}: {value!r}" + ) + self.name = name + self.value: str | bytes = ( + value if isinstance(value, bytes) else primitive_value_to_str(value) + ) + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + name = _format_form_param("name", self.name) + self._headers = b"".join( + [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"] + ) + + return self._headers + + def render_data(self) -> bytes: + if not hasattr(self, "_data"): + self._data = to_bytes(self.value) + + return self._data + + def get_length(self) -> int: + headers = self.render_headers() + data = self.render_data() + return len(headers) + len(data) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield self.render_data() + + +class FileField: + """ + A single file field item, within a multipart form field. + """ + + CHUNK_SIZE = 64 * 1024 + + def __init__(self, name: str, value: FileTypes) -> None: + self.name = name + + fileobj: FileContent + + headers: dict[str, str] = {} + content_type: str | None = None + + # This large tuple based API largely mirror's requests' API + # It would be good to think of better APIs for this that we could + # include in httpx 2.0 since variable length tuples(especially of 4 elements) + # are quite unwieldly + if isinstance(value, tuple): + if len(value) == 2: + # neither the 3rd parameter (content_type) nor the 4th (headers) + # was included + filename, fileobj = value + elif len(value) == 3: + filename, fileobj, content_type = value + else: + # all 4 parameters included + filename, fileobj, content_type, headers = value # type: ignore + else: + filename = Path(str(getattr(value, "name", "upload"))).name + fileobj = value + + if content_type is None: + content_type = _guess_content_type(filename) + + has_content_type_header = any("content-type" in key.lower() for key in headers) + if content_type is not None and not has_content_type_header: + # note that unlike requests, we ignore the content_type provided in the 3rd + # tuple element if it is also included in the headers requests does + # the opposite (it overwrites the headerwith the 3rd tuple element) + headers["Content-Type"] = content_type + + if isinstance(fileobj, io.StringIO): + raise TypeError( + "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'." + ) + if isinstance(fileobj, io.TextIOBase): + raise TypeError( + "Multipart file uploads must be opened in binary mode, not text mode." + ) + + self.filename = filename + self.file = fileobj + self.headers = headers + + def get_length(self) -> int | None: + headers = self.render_headers() + + if isinstance(self.file, (str, bytes)): + return len(headers) + len(to_bytes(self.file)) + + file_length = peek_filelike_length(self.file) + + # If we can't determine the filesize without reading it into memory, + # then return `None` here, to indicate an unknown file length. + if file_length is None: + return None + + return len(headers) + file_length + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + parts = [ + b"Content-Disposition: form-data; ", + _format_form_param("name", self.name), + ] + if self.filename: + filename = _format_form_param("filename", self.filename) + parts.extend([b"; ", filename]) + for header_name, header_value in self.headers.items(): + key, val = f"\r\n{header_name}: ".encode(), header_value.encode() + parts.extend([key, val]) + parts.append(b"\r\n\r\n") + self._headers = b"".join(parts) + + return self._headers + + def render_data(self) -> typing.Iterator[bytes]: + if isinstance(self.file, (str, bytes)): + yield to_bytes(self.file) + return + + if hasattr(self.file, "seek"): + try: + self.file.seek(0) + except io.UnsupportedOperation: + pass + + chunk = self.file.read(self.CHUNK_SIZE) + while chunk: + yield to_bytes(chunk) + chunk = self.file.read(self.CHUNK_SIZE) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield from self.render_data() + + +class MultipartStream(SyncByteStream, AsyncByteStream): + """ + Request content as streaming multipart encoded form data. + """ + + def __init__( + self, + data: RequestData, + files: RequestFiles, + boundary: bytes | None = None, + ) -> None: + if boundary is None: + boundary = os.urandom(16).hex().encode("ascii") + + self.boundary = boundary + self.content_type = "multipart/form-data; boundary=%s" % boundary.decode( + "ascii" + ) + self.fields = list(self._iter_fields(data, files)) + + def _iter_fields( + self, data: RequestData, files: RequestFiles + ) -> typing.Iterator[FileField | DataField]: + for name, value in data.items(): + if isinstance(value, (tuple, list)): + for item in value: + yield DataField(name=name, value=item) + else: + yield DataField(name=name, value=value) + + file_items = files.items() if isinstance(files, typing.Mapping) else files + for name, value in file_items: + yield FileField(name=name, value=value) + + def iter_chunks(self) -> typing.Iterator[bytes]: + for field in self.fields: + yield b"--%s\r\n" % self.boundary + yield from field.render() + yield b"\r\n" + yield b"--%s--\r\n" % self.boundary + + def get_content_length(self) -> int | None: + """ + Return the length of the multipart encoded content, or `None` if + any of the files have a length that cannot be determined upfront. + """ + boundary_length = len(self.boundary) + length = 0 + + for field in self.fields: + field_length = field.get_length() + if field_length is None: + return None + + length += 2 + boundary_length + 2 # b"--{boundary}\r\n" + length += field_length + length += 2 # b"\r\n" + + length += 2 + boundary_length + 4 # b"--{boundary}--\r\n" + return length + + # Content stream interface. + + def get_headers(self) -> dict[str, str]: + content_length = self.get_content_length() + content_type = self.content_type + if content_length is None: + return {"Transfer-Encoding": "chunked", "Content-Type": content_type} + return {"Content-Length": str(content_length), "Content-Type": content_type} + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk diff --git a/python_embeded/Lib/site-packages/httpx/_status_codes.py b/python_embeded/Lib/site-packages/httpx/_status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..133a6231a5b53fd2f073799ca1bd07c50abe40ae --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_status_codes.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from enum import IntEnum + +__all__ = ["codes"] + + +class codes(IntEnum): + """HTTP status codes and reason phrases + + Status codes from the following RFCs are all observed: + + * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 + * RFC 6585: Additional HTTP Status Codes + * RFC 3229: Delta encoding in HTTP + * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 + * RFC 5842: Binding Extensions to WebDAV + * RFC 7238: Permanent Redirect + * RFC 2295: Transparent Content Negotiation in HTTP + * RFC 2774: An HTTP Extension Framework + * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) + * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) + * RFC 7725: An HTTP Status Code to Report Legal Obstacles + * RFC 8297: An HTTP Status Code for Indicating Hints + * RFC 8470: Using Early Data in HTTP + """ + + def __new__(cls, value: int, phrase: str = "") -> codes: + obj = int.__new__(cls, value) + obj._value_ = value + + obj.phrase = phrase # type: ignore[attr-defined] + return obj + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def get_reason_phrase(cls, value: int) -> str: + try: + return codes(value).phrase # type: ignore + except ValueError: + return "" + + @classmethod + def is_informational(cls, value: int) -> bool: + """ + Returns `True` for 1xx status codes, `False` otherwise. + """ + return 100 <= value <= 199 + + @classmethod + def is_success(cls, value: int) -> bool: + """ + Returns `True` for 2xx status codes, `False` otherwise. + """ + return 200 <= value <= 299 + + @classmethod + def is_redirect(cls, value: int) -> bool: + """ + Returns `True` for 3xx status codes, `False` otherwise. + """ + return 300 <= value <= 399 + + @classmethod + def is_client_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx status codes, `False` otherwise. + """ + return 400 <= value <= 499 + + @classmethod + def is_server_error(cls, value: int) -> bool: + """ + Returns `True` for 5xx status codes, `False` otherwise. + """ + return 500 <= value <= 599 + + @classmethod + def is_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx or 5xx status codes, `False` otherwise. + """ + return 400 <= value <= 599 + + # informational + CONTINUE = 100, "Continue" + SWITCHING_PROTOCOLS = 101, "Switching Protocols" + PROCESSING = 102, "Processing" + EARLY_HINTS = 103, "Early Hints" + + # success + OK = 200, "OK" + CREATED = 201, "Created" + ACCEPTED = 202, "Accepted" + NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information" + NO_CONTENT = 204, "No Content" + RESET_CONTENT = 205, "Reset Content" + PARTIAL_CONTENT = 206, "Partial Content" + MULTI_STATUS = 207, "Multi-Status" + ALREADY_REPORTED = 208, "Already Reported" + IM_USED = 226, "IM Used" + + # redirection + MULTIPLE_CHOICES = 300, "Multiple Choices" + MOVED_PERMANENTLY = 301, "Moved Permanently" + FOUND = 302, "Found" + SEE_OTHER = 303, "See Other" + NOT_MODIFIED = 304, "Not Modified" + USE_PROXY = 305, "Use Proxy" + TEMPORARY_REDIRECT = 307, "Temporary Redirect" + PERMANENT_REDIRECT = 308, "Permanent Redirect" + + # client error + BAD_REQUEST = 400, "Bad Request" + UNAUTHORIZED = 401, "Unauthorized" + PAYMENT_REQUIRED = 402, "Payment Required" + FORBIDDEN = 403, "Forbidden" + NOT_FOUND = 404, "Not Found" + METHOD_NOT_ALLOWED = 405, "Method Not Allowed" + NOT_ACCEPTABLE = 406, "Not Acceptable" + PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required" + REQUEST_TIMEOUT = 408, "Request Timeout" + CONFLICT = 409, "Conflict" + GONE = 410, "Gone" + LENGTH_REQUIRED = 411, "Length Required" + PRECONDITION_FAILED = 412, "Precondition Failed" + REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large" + REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long" + UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type" + REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable" + EXPECTATION_FAILED = 417, "Expectation Failed" + IM_A_TEAPOT = 418, "I'm a teapot" + MISDIRECTED_REQUEST = 421, "Misdirected Request" + UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity" + LOCKED = 423, "Locked" + FAILED_DEPENDENCY = 424, "Failed Dependency" + TOO_EARLY = 425, "Too Early" + UPGRADE_REQUIRED = 426, "Upgrade Required" + PRECONDITION_REQUIRED = 428, "Precondition Required" + TOO_MANY_REQUESTS = 429, "Too Many Requests" + REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large" + UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons" + + # server errors + INTERNAL_SERVER_ERROR = 500, "Internal Server Error" + NOT_IMPLEMENTED = 501, "Not Implemented" + BAD_GATEWAY = 502, "Bad Gateway" + SERVICE_UNAVAILABLE = 503, "Service Unavailable" + GATEWAY_TIMEOUT = 504, "Gateway Timeout" + HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported" + VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates" + INSUFFICIENT_STORAGE = 507, "Insufficient Storage" + LOOP_DETECTED = 508, "Loop Detected" + NOT_EXTENDED = 510, "Not Extended" + NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required" + + +# Include lower-case styles for `requests` compatibility. +for code in codes: + setattr(codes, code._name_.lower(), int(code)) diff --git a/python_embeded/Lib/site-packages/httpx/_types.py b/python_embeded/Lib/site-packages/httpx/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..704dfdffc8ba61eb913fa918072381e410b23c00 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_types.py @@ -0,0 +1,114 @@ +""" +Type definitions for type checking purposes. +""" + +from http.cookiejar import CookieJar +from typing import ( + IO, + TYPE_CHECKING, + Any, + AsyncIterable, + AsyncIterator, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +if TYPE_CHECKING: # pragma: no cover + from ._auth import Auth # noqa: F401 + from ._config import Proxy, Timeout # noqa: F401 + from ._models import Cookies, Headers, Request # noqa: F401 + from ._urls import URL, QueryParams # noqa: F401 + + +PrimitiveData = Optional[Union[str, int, float, bool]] + +URLTypes = Union["URL", str] + +QueryParamTypes = Union[ + "QueryParams", + Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]], + List[Tuple[str, PrimitiveData]], + Tuple[Tuple[str, PrimitiveData], ...], + str, + bytes, +] + +HeaderTypes = Union[ + "Headers", + Mapping[str, str], + Mapping[bytes, bytes], + Sequence[Tuple[str, str]], + Sequence[Tuple[bytes, bytes]], +] + +CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]] + +TimeoutTypes = Union[ + Optional[float], + Tuple[Optional[float], Optional[float], Optional[float], Optional[float]], + "Timeout", +] +ProxyTypes = Union["URL", str, "Proxy"] +CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]] + +AuthTypes = Union[ + Tuple[Union[str, bytes], Union[str, bytes]], + Callable[["Request"], "Request"], + "Auth", +] + +RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseExtensions = Mapping[str, Any] + +RequestData = Mapping[str, Any] + +FileContent = Union[IO[bytes], bytes, str] +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +RequestExtensions = Mapping[str, Any] + +__all__ = ["AsyncByteStream", "SyncByteStream"] + + +class SyncByteStream: + def __iter__(self) -> Iterator[bytes]: + raise NotImplementedError( + "The '__iter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + def close(self) -> None: + """ + Subclasses can override this method to release any network resources + after a request/response cycle is complete. + """ + + +class AsyncByteStream: + async def __aiter__(self) -> AsyncIterator[bytes]: + raise NotImplementedError( + "The '__aiter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + async def aclose(self) -> None: + pass diff --git a/python_embeded/Lib/site-packages/httpx/_urlparse.py b/python_embeded/Lib/site-packages/httpx/_urlparse.py new file mode 100644 index 0000000000000000000000000000000000000000..bf190fd560ee4fc8a11af371a15fc5f1dc284d34 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_urlparse.py @@ -0,0 +1,527 @@ +""" +An implementation of `urlparse` that provides URL validation and normalization +as described by RFC3986. + +We rely on this implementation rather than the one in Python's stdlib, because: + +* It provides more complete URL validation. +* It properly differentiates between an empty querystring and an absent querystring, + to distinguish URLs with a trailing '?'. +* It handles scheme, hostname, port, and path normalization. +* It supports IDNA hostnames, normalizing them to their encoded form. +* The API supports passing individual components, as well as the complete URL string. + +Previously we relied on the excellent `rfc3986` package to handle URL parsing and +validation, but this module provides a simpler alternative, with less indirection +required. +""" + +from __future__ import annotations + +import ipaddress +import re +import typing + +import idna + +from ._exceptions import InvalidURL + +MAX_URL_LENGTH = 65536 + +# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3 +UNRESERVED_CHARACTERS = ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" +) +SUB_DELIMS = "!$&'()*+,;=" + +PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}") + +# https://url.spec.whatwg.org/#percent-encoded-bytes + +# The fragment percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`). +FRAG_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)] +) + +# The query percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>). +QUERY_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)] +) + +# The path percent-encode set is the query percent-encode set +# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}). +PATH_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) + ] +) + +# The userinfo percent-encode set is the path percent-encode set +# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@), +# U+005B ([) to U+005E (^), inclusive, and U+007C (|). +USERNAME_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +PASSWORD_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +# Note... The terminology 'userinfo' percent-encode set in the WHATWG document +# is used for the username and password quoting. For the joint userinfo component +# we remove U+003A (:) from the safe set. +USERINFO_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) + + +# {scheme}: (optional) +# //{authority} (optional) +# {path} +# ?{query} (optional) +# #{fragment} (optional) +URL_REGEX = re.compile( + ( + r"(?:(?P{scheme}):)?" + r"(?://(?P{authority}))?" + r"(?P{path})" + r"(?:\?(?P{query}))?" + r"(?:#(?P{fragment}))?" + ).format( + scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?", + authority="[^/?#]*", + path="[^?#]*", + query="[^#]*", + fragment=".*", + ) +) + +# {userinfo}@ (optional) +# {host} +# :{port} (optional) +AUTHORITY_REGEX = re.compile( + ( + r"(?:(?P{userinfo})@)?" r"(?P{host})" r":?(?P{port})?" + ).format( + userinfo=".*", # Any character sequence. + host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@', + # or an IPv6 address enclosed within square brackets. + port=".*", # Any character sequence. + ) +) + + +# If we call urlparse with an individual component, then we need to regex +# validate that component individually. +# Note that we're duplicating the same strings as above. Shock! Horror!! +COMPONENT_REGEX = { + "scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"), + "authority": re.compile("[^/?#]*"), + "path": re.compile("[^?#]*"), + "query": re.compile("[^#]*"), + "fragment": re.compile(".*"), + "userinfo": re.compile("[^@]*"), + "host": re.compile("(\\[.*\\]|[^:]*)"), + "port": re.compile(".*"), +} + + +# We use these simple regexs as a first pass before handing off to +# the stdlib 'ipaddress' module for IP address validation. +IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$") +IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$") + + +class ParseResult(typing.NamedTuple): + scheme: str + userinfo: str + host: str + port: int | None + path: str + query: str | None + fragment: str | None + + @property + def authority(self) -> str: + return "".join( + [ + f"{self.userinfo}@" if self.userinfo else "", + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + @property + def netloc(self) -> str: + return "".join( + [ + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + def copy_with(self, **kwargs: str | None) -> ParseResult: + if not kwargs: + return self + + defaults = { + "scheme": self.scheme, + "authority": self.authority, + "path": self.path, + "query": self.query, + "fragment": self.fragment, + } + defaults.update(kwargs) + return urlparse("", **defaults) + + def __str__(self) -> str: + authority = self.authority + return "".join( + [ + f"{self.scheme}:" if self.scheme else "", + f"//{authority}" if authority else "", + self.path, + f"?{self.query}" if self.query is not None else "", + f"#{self.fragment}" if self.fragment is not None else "", + ] + ) + + +def urlparse(url: str = "", **kwargs: str | None) -> ParseResult: + # Initial basic checks on allowable URLs. + # --------------------------------------- + + # Hard limit the maximum allowable URL length. + if len(url) > MAX_URL_LENGTH: + raise InvalidURL("URL too long") + + # If a URL includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in url): + char = next(char for char in url if char.isascii() and not char.isprintable()) + idx = url.find(char) + error = ( + f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Some keyword arguments require special handling. + # ------------------------------------------------ + + # Coerce "port" to a string, if it is provided as an integer. + if "port" in kwargs: + port = kwargs["port"] + kwargs["port"] = str(port) if isinstance(port, int) else port + + # Replace "netloc" with "host and "port". + if "netloc" in kwargs: + netloc = kwargs.pop("netloc") or "" + kwargs["host"], _, kwargs["port"] = netloc.partition(":") + + # Replace "username" and/or "password" with "userinfo". + if "username" in kwargs or "password" in kwargs: + username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE) + password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE) + kwargs["userinfo"] = f"{username}:{password}" if password else username + + # Replace "raw_path" with "path" and "query". + if "raw_path" in kwargs: + raw_path = kwargs.pop("raw_path") or "" + kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?") + if not seperator: + kwargs["query"] = None + + # Ensure that IPv6 "host" addresses are always escaped with "[...]". + if "host" in kwargs: + host = kwargs.get("host") or "" + if ":" in host and not (host.startswith("[") and host.endswith("]")): + kwargs["host"] = f"[{host}]" + + # If any keyword arguments are provided, ensure they are valid. + # ------------------------------------------------------------- + + for key, value in kwargs.items(): + if value is not None: + if len(value) > MAX_URL_LENGTH: + raise InvalidURL(f"URL component '{key}' too long") + + # If a component includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in value): + char = next( + char for char in value if char.isascii() and not char.isprintable() + ) + idx = value.find(char) + error = ( + f"Invalid non-printable ASCII character in URL {key} component, " + f"{char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Ensure that keyword arguments match as a valid regex. + if not COMPONENT_REGEX[key].fullmatch(value): + raise InvalidURL(f"Invalid URL component '{key}'") + + # The URL_REGEX will always match, but may have empty components. + url_match = URL_REGEX.match(url) + assert url_match is not None + url_dict = url_match.groupdict() + + # * 'scheme', 'authority', and 'path' may be empty strings. + # * 'query' may be 'None', indicating no trailing "?" portion. + # Any string including the empty string, indicates a trailing "?". + # * 'fragment' may be 'None', indicating no trailing "#" portion. + # Any string including the empty string, indicates a trailing "#". + scheme = kwargs.get("scheme", url_dict["scheme"]) or "" + authority = kwargs.get("authority", url_dict["authority"]) or "" + path = kwargs.get("path", url_dict["path"]) or "" + query = kwargs.get("query", url_dict["query"]) + frag = kwargs.get("fragment", url_dict["fragment"]) + + # The AUTHORITY_REGEX will always match, but may have empty components. + authority_match = AUTHORITY_REGEX.match(authority) + assert authority_match is not None + authority_dict = authority_match.groupdict() + + # * 'userinfo' and 'host' may be empty strings. + # * 'port' may be 'None'. + userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or "" + host = kwargs.get("host", authority_dict["host"]) or "" + port = kwargs.get("port", authority_dict["port"]) + + # Normalize and validate each component. + # We end up with a parsed representation of the URL, + # with components that are plain ASCII bytestrings. + parsed_scheme: str = scheme.lower() + parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE) + parsed_host: str = encode_host(host) + parsed_port: int | None = normalize_port(port, scheme) + + has_scheme = parsed_scheme != "" + has_authority = ( + parsed_userinfo != "" or parsed_host != "" or parsed_port is not None + ) + validate_path(path, has_scheme=has_scheme, has_authority=has_authority) + if has_scheme or has_authority: + path = normalize_path(path) + + parsed_path: str = quote(path, safe=PATH_SAFE) + parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE) + parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE) + + # The parsed ASCII bytestrings are our canonical form. + # All properties of the URL are derived from these. + return ParseResult( + parsed_scheme, + parsed_userinfo, + parsed_host, + parsed_port, + parsed_path, + parsed_query, + parsed_frag, + ) + + +def encode_host(host: str) -> str: + if not host: + return "" + + elif IPv4_STYLE_HOSTNAME.match(host): + # Validate IPv4 hostnames like #.#.#.# + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + try: + ipaddress.IPv4Address(host) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv4 address: {host!r}") + return host + + elif IPv6_STYLE_HOSTNAME.match(host): + # Validate IPv6 hostnames like [...] + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # "A host identified by an Internet Protocol literal address, version 6 + # [RFC3513] or later, is distinguished by enclosing the IP literal + # within square brackets ("[" and "]"). This is the only place where + # square bracket characters are allowed in the URI syntax." + try: + ipaddress.IPv6Address(host[1:-1]) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv6 address: {host!r}") + return host[1:-1] + + elif host.isascii(): + # Regular ASCII hostnames + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # reg-name = *( unreserved / pct-encoded / sub-delims ) + WHATWG_SAFE = '"`{}%|\\' + return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE) + + # IDNA hostnames + try: + return idna.encode(host.lower()).decode("ascii") + except idna.IDNAError: + raise InvalidURL(f"Invalid IDNA hostname: {host!r}") + + +def normalize_port(port: str | int | None, scheme: str) -> int | None: + # From https://tools.ietf.org/html/rfc3986#section-3.2.3 + # + # "A scheme may define a default port. For example, the "http" scheme + # defines a default port of "80", corresponding to its reserved TCP + # port number. The type of port designated by the port number (e.g., + # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and + # normalizers should omit the port component and its ":" delimiter if + # port is empty or if its value would be the same as that of the + # scheme's default." + if port is None or port == "": + return None + + try: + port_as_int = int(port) + except ValueError: + raise InvalidURL(f"Invalid port: {port!r}") + + # See https://url.spec.whatwg.org/#url-miscellaneous + default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get( + scheme + ) + if port_as_int == default_port: + return None + return port_as_int + + +def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None: + """ + Path validation rules that depend on if the URL contains + a scheme or authority component. + + See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3 + """ + if has_authority: + # If a URI contains an authority component, then the path component + # must either be empty or begin with a slash ("/") character." + if path and not path.startswith("/"): + raise InvalidURL("For absolute URLs, path must be empty or begin with '/'") + + if not has_scheme and not has_authority: + # If a URI does not contain an authority component, then the path cannot begin + # with two slash characters ("//"). + if path.startswith("//"): + raise InvalidURL("Relative URLs cannot have a path starting with '//'") + + # In addition, a URI reference (Section 4.1) may be a relative-path reference, + # in which case the first path segment cannot contain a colon (":") character. + if path.startswith(":"): + raise InvalidURL("Relative URLs cannot have a path starting with ':'") + + +def normalize_path(path: str) -> str: + """ + Drop "." and ".." segments from a URL path. + + For example: + + normalize_path("/path/./to/somewhere/..") == "/path/to" + """ + # Fast return when no '.' characters in the path. + if "." not in path: + return path + + components = path.split("/") + + # Fast return when no '.' or '..' components in the path. + if "." not in components and ".." not in components: + return path + + # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + output: list[str] = [] + for component in components: + if component == ".": + pass + elif component == "..": + if output and output != [""]: + output.pop() + else: + output.append(component) + return "/".join(output) + + +def PERCENT(string: str) -> str: + return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")]) + + +def percent_encoded(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string. + """ + NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe + + # Fast path for strings that don't need escaping. + if not string.rstrip(NON_ESCAPED_CHARS): + return string + + return "".join( + [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string] + ) + + +def quote(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string, omitting existing '%xx' escape sequences. + + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 + + * `string`: The string to be percent-escaped. + * `safe`: A string containing characters that may be treated as safe, and do not + need to be escaped. Unreserved characters are always treated as safe. + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3 + """ + parts = [] + current_position = 0 + for match in re.finditer(PERCENT_ENCODED_REGEX, string): + start_position, end_position = match.start(), match.end() + matched_text = match.group(0) + # Add any text up to the '%xx' escape sequence. + if start_position != current_position: + leading_text = string[current_position:start_position] + parts.append(percent_encoded(leading_text, safe=safe)) + + # Add the '%xx' escape sequence. + parts.append(matched_text) + current_position = end_position + + # Add any text after the final '%xx' escape sequence. + if current_position != len(string): + trailing_text = string[current_position:] + parts.append(percent_encoded(trailing_text, safe=safe)) + + return "".join(parts) diff --git a/python_embeded/Lib/site-packages/httpx/_urls.py b/python_embeded/Lib/site-packages/httpx/_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..147a8fa333acaf31618d37ba2896e3a5bf5e4d02 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_urls.py @@ -0,0 +1,641 @@ +from __future__ import annotations + +import typing +from urllib.parse import parse_qs, unquote, urlencode + +import idna + +from ._types import QueryParamTypes +from ._urlparse import urlparse +from ._utils import primitive_value_to_str + +__all__ = ["URL", "QueryParams"] + + +class URL: + """ + url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink") + + assert url.scheme == "https" + assert url.username == "jo@email.com" + assert url.password == "a secret" + assert url.userinfo == b"jo%40email.com:a%20secret" + assert url.host == "müller.de" + assert url.raw_host == b"xn--mller-kva.de" + assert url.port == 1234 + assert url.netloc == b"xn--mller-kva.de:1234" + assert url.path == "/pa th" + assert url.query == b"?search=ab" + assert url.raw_path == b"/pa%20th?search=ab" + assert url.fragment == "anchorlink" + + The components of a URL are broken down like this: + + https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink + [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment] + [ userinfo ] [ netloc ][ raw_path ] + + Note that: + + * `url.scheme` is normalized to always be lowercased. + + * `url.host` is normalized to always be lowercased. Internationalized domain + names are represented in unicode, without IDNA encoding applied. For instance: + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded. + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + * `url.port` is either None or an integer. URLs that include the default port for + "http", "https", "ws", "wss", and "ftp" schemes have their port + normalized to `None`. + + assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80") + assert httpx.URL("http://example.com").port is None + assert httpx.URL("http://example.com:80").port is None + + * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work + with `url.username` and `url.password` instead, which handle the URL escaping. + + * `url.raw_path` is raw bytes of both the path and query, without URL escaping. + This portion is used as the target when constructing HTTP requests. Usually you'll + want to work with `url.path` instead. + + * `url.query` is raw bytes, without URL escaping. A URL query string portion can + only be properly URL escaped when decoding the parameter names and values + themselves. + """ + + def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None: + if kwargs: + allowed = { + "scheme": str, + "username": str, + "password": str, + "userinfo": bytes, + "host": str, + "port": int, + "netloc": bytes, + "path": str, + "query": bytes, + "raw_path": bytes, + "fragment": str, + "params": object, + } + + # Perform type checking for all supported keyword arguments. + for key, value in kwargs.items(): + if key not in allowed: + message = f"{key!r} is an invalid keyword argument for URL()" + raise TypeError(message) + if value is not None and not isinstance(value, allowed[key]): + expected = allowed[key].__name__ + seen = type(value).__name__ + message = f"Argument {key!r} must be {expected} but got {seen}" + raise TypeError(message) + if isinstance(value, bytes): + kwargs[key] = value.decode("ascii") + + if "params" in kwargs: + # Replace any "params" keyword with the raw "query" instead. + # + # Ensure that empty params use `kwargs["query"] = None` rather + # than `kwargs["query"] = ""`, so that generated URLs do not + # include an empty trailing "?". + params = kwargs.pop("params") + kwargs["query"] = None if not params else str(QueryParams(params)) + + if isinstance(url, str): + self._uri_reference = urlparse(url, **kwargs) + elif isinstance(url, URL): + self._uri_reference = url._uri_reference.copy_with(**kwargs) + else: + raise TypeError( + "Invalid type for url. Expected str or httpx.URL," + f" got {type(url)}: {url!r}" + ) + + @property + def scheme(self) -> str: + """ + The URL scheme, such as "http", "https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme + + @property + def raw_scheme(self) -> bytes: + """ + The raw bytes representation of the URL scheme, such as b"http", b"https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme.encode("ascii") + + @property + def userinfo(self) -> bytes: + """ + The URL userinfo as a raw bytestring. + For example: b"jo%40email.com:a%20secret". + """ + return self._uri_reference.userinfo.encode("ascii") + + @property + def username(self) -> str: + """ + The URL username as a string, with URL decoding applied. + For example: "jo@email.com" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[0]) + + @property + def password(self) -> str: + """ + The URL password as a string, with URL decoding applied. + For example: "a secret" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[2]) + + @property + def host(self) -> str: + """ + The URL host as a string. + Always normalized to lowercase, with IDNA hosts decoded into unicode. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.host == "www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.host == "::ffff:192.168.0.1" + """ + host: str = self._uri_reference.host + + if host.startswith("xn--"): + host = idna.decode(host) + + return host + + @property + def raw_host(self) -> bytes: + """ + The raw bytes representation of the URL host. + Always normalized to lowercase, and IDNA encoded. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.raw_host == b"www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.raw_host == b"::ffff:192.168.0.1" + """ + return self._uri_reference.host.encode("ascii") + + @property + def port(self) -> int | None: + """ + The URL port as an integer. + + Note that the URL class performs port normalization as per the WHATWG spec. + Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always + treated as `None`. + + For example: + + assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80") + assert httpx.URL("http://www.example.com:80").port is None + """ + return self._uri_reference.port + + @property + def netloc(self) -> bytes: + """ + Either `` or `:` as bytes. + Always normalized to lowercase, and IDNA encoded. + + This property may be used for generating the value of a request + "Host" header. + """ + return self._uri_reference.netloc.encode("ascii") + + @property + def path(self) -> str: + """ + The URL path as a string. Excluding the query string, and URL decoded. + + For example: + + url = httpx.URL("https://example.com/pa%20th") + assert url.path == "/pa th" + """ + path = self._uri_reference.path or "/" + return unquote(path) + + @property + def query(self) -> bytes: + """ + The URL query string, as raw bytes, excluding the leading b"?". + + This is necessarily a bytewise interface, because we cannot + perform URL decoding of this representation until we've parsed + the keys and values into a QueryParams instance. + + For example: + + url = httpx.URL("https://example.com/?filter=some%20search%20terms") + assert url.query == b"filter=some%20search%20terms" + """ + query = self._uri_reference.query or "" + return query.encode("ascii") + + @property + def params(self) -> QueryParams: + """ + The URL query parameters, neatly parsed and packaged into an immutable + multidict representation. + """ + return QueryParams(self._uri_reference.query) + + @property + def raw_path(self) -> bytes: + """ + The complete URL path and query string as raw bytes. + Used as the target when constructing HTTP requests. + + For example: + + GET /users?search=some%20text HTTP/1.1 + Host: www.example.org + Connection: close + """ + path = self._uri_reference.path or "/" + if self._uri_reference.query is not None: + path += "?" + self._uri_reference.query + return path.encode("ascii") + + @property + def fragment(self) -> str: + """ + The URL fragments, as used in HTML anchors. + As a string, without the leading '#'. + """ + return unquote(self._uri_reference.fragment or "") + + @property + def is_absolute_url(self) -> bool: + """ + Return `True` for absolute URLs such as 'http://example.com/path', + and `False` for relative URLs such as '/path'. + """ + # We don't use `.is_absolute` from `rfc3986` because it treats + # URLs with a fragment portion as not absolute. + # What we actually care about is if the URL provides + # a scheme and hostname to which connections should be made. + return bool(self._uri_reference.scheme and self._uri_reference.host) + + @property + def is_relative_url(self) -> bool: + """ + Return `False` for absolute URLs such as 'http://example.com/path', + and `True` for relative URLs such as '/path'. + """ + return not self.is_absolute_url + + def copy_with(self, **kwargs: typing.Any) -> URL: + """ + Copy this URL, returning a new URL with some components altered. + Accepts the same set of parameters as the components that are made + available via properties on the `URL` class. + + For example: + + url = httpx.URL("https://www.example.com").copy_with( + username="jo@gmail.com", password="a secret" + ) + assert url == "https://jo%40email.com:a%20secret@www.example.com" + """ + return URL(self, **kwargs) + + def copy_set_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.set(key, value)) + + def copy_add_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.add(key, value)) + + def copy_remove_param(self, key: str) -> URL: + return self.copy_with(params=self.params.remove(key)) + + def copy_merge_params(self, params: QueryParamTypes) -> URL: + return self.copy_with(params=self.params.merge(params)) + + def join(self, url: URL | str) -> URL: + """ + Return an absolute URL, using this URL as the base. + + Eg. + + url = httpx.URL("https://www.example.com/test") + url = url.join("/new/path") + assert url == "https://www.example.com/new/path" + """ + from urllib.parse import urljoin + + return URL(urljoin(str(self), str(URL(url)))) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, (URL, str)) and str(self) == str(URL(other)) + + def __str__(self) -> str: + return str(self._uri_reference) + + def __repr__(self) -> str: + scheme, userinfo, host, port, path, query, fragment = self._uri_reference + + if ":" in userinfo: + # Mask any password component. + userinfo = f'{userinfo.split(":")[0]}:[secure]' + + authority = "".join( + [ + f"{userinfo}@" if userinfo else "", + f"[{host}]" if ":" in host else host, + f":{port}" if port is not None else "", + ] + ) + url = "".join( + [ + f"{self.scheme}:" if scheme else "", + f"//{authority}" if authority else "", + path, + f"?{query}" if query is not None else "", + f"#{fragment}" if fragment is not None else "", + ] + ) + + return f"{self.__class__.__name__}({url!r})" + + @property + def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover + import collections + import warnings + + warnings.warn("URL.raw is deprecated.") + RawURL = collections.namedtuple( + "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"] + ) + return RawURL( + raw_scheme=self.raw_scheme, + raw_host=self.raw_host, + port=self.port, + raw_path=self.raw_path, + ) + + +class QueryParams(typing.Mapping[str, str]): + """ + URL query parameters, as a multi-dict. + """ + + def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None: + assert len(args) < 2, "Too many arguments." + assert not (args and kwargs), "Cannot mix named and unnamed arguments." + + value = args[0] if args else kwargs + + if value is None or isinstance(value, (str, bytes)): + value = value.decode("ascii") if isinstance(value, bytes) else value + self._dict = parse_qs(value, keep_blank_values=True) + elif isinstance(value, QueryParams): + self._dict = {k: list(v) for k, v in value._dict.items()} + else: + dict_value: dict[typing.Any, list[typing.Any]] = {} + if isinstance(value, (list, tuple)): + # Convert list inputs like: + # [("a", "123"), ("a", "456"), ("b", "789")] + # To a dict representation, like: + # {"a": ["123", "456"], "b": ["789"]} + for item in value: + dict_value.setdefault(item[0], []).append(item[1]) + else: + # Convert dict inputs like: + # {"a": "123", "b": ["456", "789"]} + # To dict inputs where values are always lists, like: + # {"a": ["123"], "b": ["456", "789"]} + dict_value = { + k: list(v) if isinstance(v, (list, tuple)) else [v] + for k, v in value.items() + } + + # Ensure that keys and values are neatly coerced to strings. + # We coerce values `True` and `False` to JSON-like "true" and "false" + # representations, and coerce `None` values to the empty string. + self._dict = { + str(k): [primitive_value_to_str(item) for item in v] + for k, v in dict_value.items() + } + + def keys(self) -> typing.KeysView[str]: + """ + Return all the keys in the query params. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.keys()) == ["a", "b"] + """ + return self._dict.keys() + + def values(self) -> typing.ValuesView[str]: + """ + Return all the values in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.values()) == ["123", "789"] + """ + return {k: v[0] for k, v in self._dict.items()}.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return all items in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.items()) == [("a", "123"), ("b", "789")] + """ + return {k: v[0] for k, v in self._dict.items()}.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return all items in the query params. Allow duplicate keys to occur. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")] + """ + multi_items: list[tuple[str, str]] = [] + for k, v in self._dict.items(): + multi_items.extend([(k, i) for i in v]) + return multi_items + + def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any: + """ + Get a value from the query param for a given key. If the key occurs + more than once, then only the first value is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get("a") == "123" + """ + if key in self._dict: + return self._dict[str(key)][0] + return default + + def get_list(self, key: str) -> list[str]: + """ + Get all values from the query param for a given key. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get_list("a") == ["123", "456"] + """ + return list(self._dict.get(str(key), [])) + + def set(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.set("a", "456") + assert q == httpx.QueryParams("a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = [primitive_value_to_str(value)] + return q + + def add(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting or appending the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.add("a", "456") + assert q == httpx.QueryParams("a=123&a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)] + return q + + def remove(self, key: str) -> QueryParams: + """ + Return a new QueryParams instance, removing the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.remove("a") + assert q == httpx.QueryParams("") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict.pop(str(key), None) + return q + + def merge(self, params: QueryParamTypes | None = None) -> QueryParams: + """ + Return a new QueryParams instance, updated with. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.merge({"b": "456"}) + assert q == httpx.QueryParams("a=123&b=456") + + q = httpx.QueryParams("a=123") + q = q.merge({"a": "456", "b": "789"}) + assert q == httpx.QueryParams("a=456&b=789") + """ + q = QueryParams(params) + q._dict = {**self._dict, **q._dict} + return q + + def __getitem__(self, key: typing.Any) -> str: + return self._dict[key][0] + + def __contains__(self, key: typing.Any) -> bool: + return key in self._dict + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._dict) + + def __bool__(self) -> bool: + return bool(self._dict) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + if not isinstance(other, self.__class__): + return False + return sorted(self.multi_items()) == sorted(other.multi_items()) + + def __str__(self) -> str: + return urlencode(self.multi_items()) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + query_string = str(self) + return f"{class_name}({query_string!r})" + + def update(self, params: QueryParamTypes | None = None) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.merge(...)` to create an updated copy." + ) + + def __setitem__(self, key: str, value: str) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.set(key, value)` to create an updated copy." + ) diff --git a/python_embeded/Lib/site-packages/httpx/_utils.py b/python_embeded/Lib/site-packages/httpx/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe827da4d071b32ea6da44328629699d6fc88ce --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx/_utils.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +import ipaddress +import os +import re +import typing +from urllib.request import getproxies + +from ._types import PrimitiveData + +if typing.TYPE_CHECKING: # pragma: no cover + from ._urls import URL + + +def primitive_value_to_str(value: PrimitiveData) -> str: + """ + Coerce a primitive data type into a string value. + + Note that we prefer JSON-style 'true'/'false' for boolean values here. + """ + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +def get_environment_proxies() -> dict[str, str | None]: + """Gets proxy information from the environment""" + + # urllib.request.getproxies() falls back on System + # Registry and Config for proxies on Windows and macOS. + # We don't want to propagate non-HTTP proxies into + # our configuration such as 'TRAVIS_APT_PROXY'. + proxy_info = getproxies() + mounts: dict[str, str | None] = {} + + for scheme in ("http", "https", "all"): + if proxy_info.get(scheme): + hostname = proxy_info[scheme] + mounts[f"{scheme}://"] = ( + hostname if "://" in hostname else f"http://{hostname}" + ) + + no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")] + for hostname in no_proxy_hosts: + # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details + # on how names in `NO_PROXY` are handled. + if hostname == "*": + # If NO_PROXY=* is used or if "*" occurs as any one of the comma + # separated hostnames, then we should just bypass any information + # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore + # proxies. + return {} + elif hostname: + # NO_PROXY=.google.com is marked as "all://*.google.com, + # which disables "www.google.com" but not "google.com" + # NO_PROXY=google.com is marked as "all://*google.com, + # which disables "www.google.com" and "google.com". + # (But not "wwwgoogle.com") + # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost" + # NO_PROXY=example.com,::1,localhost,192.168.0.0/16 + if "://" in hostname: + mounts[hostname] = None + elif is_ipv4_hostname(hostname): + mounts[f"all://{hostname}"] = None + elif is_ipv6_hostname(hostname): + mounts[f"all://[{hostname}]"] = None + elif hostname.lower() == "localhost": + mounts[f"all://{hostname}"] = None + else: + mounts[f"all://*{hostname}"] = None + + return mounts + + +def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes: + return value.encode(encoding) if isinstance(value, str) else value + + +def to_str(value: str | bytes, encoding: str = "utf-8") -> str: + return value if isinstance(value, str) else value.decode(encoding) + + +def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr: + return value if isinstance(match_type_of, str) else value.encode() + + +def unquote(value: str) -> str: + return value[1:-1] if value[0] == value[-1] == '"' else value + + +def peek_filelike_length(stream: typing.Any) -> int | None: + """ + Given a file-like stream object, return its length in number of bytes + without reading it into memory. + """ + try: + # Is it an actual file? + fd = stream.fileno() + # Yup, seems to be an actual file. + length = os.fstat(fd).st_size + except (AttributeError, OSError): + # No... Maybe it's something that supports random access, like `io.BytesIO`? + try: + # Assuming so, go to end of stream to figure out its length, + # then put it back in place. + offset = stream.tell() + length = stream.seek(0, os.SEEK_END) + stream.seek(offset) + except (AttributeError, OSError): + # Not even that? Sorry, we're doomed... + return None + + return length + + +class URLPattern: + """ + A utility class currently used for making lookups against proxy keys... + + # Wildcard matching... + >>> pattern = URLPattern("all://") + >>> pattern.matches(httpx.URL("http://example.com")) + True + + # Witch scheme matching... + >>> pattern = URLPattern("https://") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + + # With domain matching... + >>> pattern = URLPattern("https://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # Wildcard scheme, with domain matching... + >>> pattern = URLPattern("all://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + True + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # With port matching... + >>> pattern = URLPattern("https://example.com:1234") + >>> pattern.matches(httpx.URL("https://example.com:1234")) + True + >>> pattern.matches(httpx.URL("https://example.com")) + False + """ + + def __init__(self, pattern: str) -> None: + from ._urls import URL + + if pattern and ":" not in pattern: + raise ValueError( + f"Proxy keys should use proper URL forms rather " + f"than plain scheme strings. " + f'Instead of "{pattern}", use "{pattern}://"' + ) + + url = URL(pattern) + self.pattern = pattern + self.scheme = "" if url.scheme == "all" else url.scheme + self.host = "" if url.host == "*" else url.host + self.port = url.port + if not url.host or url.host == "*": + self.host_regex: typing.Pattern[str] | None = None + elif url.host.startswith("*."): + # *.example.com should match "www.example.com", but not "example.com" + domain = re.escape(url.host[2:]) + self.host_regex = re.compile(f"^.+\\.{domain}$") + elif url.host.startswith("*"): + # *example.com should match "www.example.com" and "example.com" + domain = re.escape(url.host[1:]) + self.host_regex = re.compile(f"^(.+\\.)?{domain}$") + else: + # example.com should match "example.com" but not "www.example.com" + domain = re.escape(url.host) + self.host_regex = re.compile(f"^{domain}$") + + def matches(self, other: URL) -> bool: + if self.scheme and self.scheme != other.scheme: + return False + if ( + self.host + and self.host_regex is not None + and not self.host_regex.match(other.host) + ): + return False + if self.port is not None and self.port != other.port: + return False + return True + + @property + def priority(self) -> tuple[int, int, int]: + """ + The priority allows URLPattern instances to be sortable, so that + we can match from most specific to least specific. + """ + # URLs with a port should take priority over URLs without a port. + port_priority = 0 if self.port is not None else 1 + # Longer hostnames should match first. + host_priority = -len(self.host) + # Longer schemes should match first. + scheme_priority = -len(self.scheme) + return (port_priority, host_priority, scheme_priority) + + def __hash__(self) -> int: + return hash(self.pattern) + + def __lt__(self, other: URLPattern) -> bool: + return self.priority < other.priority + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, URLPattern) and self.pattern == other.pattern + + +def is_ipv4_hostname(hostname: str) -> bool: + try: + ipaddress.IPv4Address(hostname.split("/")[0]) + except Exception: + return False + return True + + +def is_ipv6_hostname(hostname: str) -> bool: + try: + ipaddress.IPv6Address(hostname.split("/")[0]) + except Exception: + return False + return True diff --git a/python_embeded/Lib/site-packages/httpx/py.typed b/python_embeded/Lib/site-packages/httpx/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/INSTALLER b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/METADATA b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8ba5aa4ad27cac2ce4274779ff97a1e9805c8c0e --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/METADATA @@ -0,0 +1,339 @@ +Metadata-Version: 2.4 +Name: httpx-sse +Version: 0.4.1 +Summary: Consume Server-Sent Event (SSE) messages with HTTPX. +Author-email: Florimond Manca +License: MIT +Project-URL: Homepage, https://github.com/florimondmanca/httpx-sse +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Dynamic: license-file + +# httpx-sse + +[![Build Status](https://dev.azure.com/florimondmanca/public/_apis/build/status/florimondmanca.httpx-sse?branchName=master)](https://dev.azure.com/florimondmanca/public/_build?definitionId=19) +[![Coverage](https://codecov.io/gh/florimondmanca/httpx-sse/branch/master/graph/badge.svg)](https://codecov.io/gh/florimondmanca/httpx-sse) +[![Package version](https://badge.fury.io/py/httpx-sse.svg)](https://pypi.org/project/httpx-sse) + +Consume [Server-Sent Event (SSE)](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) messages with [HTTPX](https://www.python-httpx.org). + +**Table of contents** + +- [Installation](#installation) +- [Quickstart](#quickstart) +- [How-To](#how-to) +- [API Reference](#api-reference) + +## Installation + +**NOTE**: This is beta software. Please be sure to pin your dependencies. + +```bash +pip install httpx-sse=="0.4.*" +``` + +## Quickstart + +`httpx-sse` provides the [`connect_sse`](#connect_sse) and [`aconnect_sse`](#aconnect_sse) helpers for connecting to an SSE endpoint. The resulting [`EventSource`](#eventsource) object exposes the [`.iter_sse()`](#iter_sse) and [`.aiter_sse()`](#aiter_sse) methods to iterate over the server-sent events. + +Example usage: + +```python +import httpx +from httpx_sse import connect_sse + +with httpx.Client() as client: + with connect_sse(client, "GET", "http://localhost:8000/sse") as event_source: + for sse in event_source.iter_sse(): + print(sse.event, sse.data, sse.id, sse.retry) +``` + +You can try this against this example Starlette server ([credit](https://sysid.github.io/sse/)): + +```python +# Requirements: pip install uvicorn starlette sse-starlette +import asyncio +import uvicorn +from starlette.applications import Starlette +from starlette.routing import Route +from sse_starlette.sse import EventSourceResponse + +async def numbers(minimum, maximum): + for i in range(minimum, maximum + 1): + await asyncio.sleep(0.9) + yield {"data": i} + +async def sse(request): + generator = numbers(1, 5) + return EventSourceResponse(generator) + +routes = [ + Route("/sse", endpoint=sse) +] + +app = Starlette(routes=routes) + +if __name__ == "__main__": + uvicorn.run(app) +``` + +## How-To + +### Calling into Python web apps + +You can [call into Python web apps](https://www.python-httpx.org/async/#calling-into-python-web-apps) with HTTPX and `httpx-sse` to test SSE endpoints directly. + +Here's an example of calling into a Starlette ASGI app... + +```python +import asyncio + +import httpx +from httpx_sse import aconnect_sse +from sse_starlette.sse import EventSourceResponse +from starlette.applications import Starlette +from starlette.routing import Route + +async def auth_events(request): + async def events(): + yield { + "event": "login", + "data": '{"user_id": "4135"}', + } + + return EventSourceResponse(events()) + +app = Starlette(routes=[Route("/sse/auth/", endpoint=auth_events)]) + +async def main(): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app)) as client: + async with aconnect_sse( + client, "GET", "http://localhost:8000/sse/auth/" + ) as event_source: + events = [sse async for sse in event_source.aiter_sse()] + (sse,) = events + assert sse.event == "login" + assert sse.json() == {"user_id": "4135"} + +asyncio.run(main()) +``` + +### Handling reconnections + +_(Advanced)_ + +`SSETransport` and `AsyncSSETransport` don't have reconnection built-in. This is because how to perform retries is generally dependent on your use case. As a result, if the connection breaks while attempting to read from the server, you will get an `httpx.ReadError` from `iter_sse()` (or `aiter_sse()`). + +However, `httpx-sse` does allow implementing reconnection by using the `Last-Event-ID` and reconnection time (in milliseconds), exposed as `sse.id` and `sse.retry` respectively. + +Here's how you might achieve this using [`stamina`](https://github.com/hynek/stamina)... + +```python +import time +from typing import Iterator + +import httpx +from httpx_sse import connect_sse, ServerSentEvent +from stamina import retry + +def iter_sse_retrying(client, method, url): + last_event_id = "" + reconnection_delay = 0.0 + + # `stamina` will apply jitter and exponential backoff on top of + # the `retry` reconnection delay sent by the server. + @retry(on=httpx.ReadError) + def _iter_sse(): + nonlocal last_event_id, reconnection_delay + + time.sleep(reconnection_delay) + + headers = {"Accept": "text/event-stream"} + + if last_event_id: + headers["Last-Event-ID"] = last_event_id + + with connect_sse(client, method, url, headers=headers) as event_source: + for sse in event_source.iter_sse(): + last_event_id = sse.id + + if sse.retry is not None: + reconnection_delay = sse.retry / 1000 + + yield sse + + return _iter_sse() +``` + +Usage: + +```python +with httpx.Client() as client: + for sse in iter_sse_retrying(client, "GET", "http://localhost:8000/sse"): + print(sse.event, sse.data) +``` + +## API Reference + +### `connect_sse` + +```python +def connect_sse( + client: httpx.Client, + method: str, + url: Union[str, httpx.URL], + **kwargs, +) -> ContextManager[EventSource] +``` + +Connect to an SSE endpoint and return an [`EventSource`](#eventsource) context manager. + +This sets `Cache-Control: no-store` on the request, as per the SSE spec, as well as `Accept: text/event-stream`. + +If the response `Content-Type` is not `text/event-stream`, this will raise an [`SSEError`](#sseerror). + +### `aconnect_sse` + +```python +async def aconnect_sse( + client: httpx.AsyncClient, + method: str, + url: Union[str, httpx.URL], + **kwargs, +) -> AsyncContextManager[EventSource] +``` + +An async equivalent to [`connect_sse`](#connect_sse). + +### `EventSource` + +```python +def __init__(response: httpx.Response) +``` + +Helper for working with an SSE response. + +#### `response` + +The underlying [`httpx.Response`](https://www.python-httpx.org/api/#response). + +You may use this to perform more operations and checks on the response, such as checking for HTTP status errors: + +```python +with connect_sse(...) as event_source: + event_source.response.raise_for_status() + + for sse in event_source.iter_sse(): + ... +``` + +#### `iter_sse` + +```python +def iter_sse() -> Iterator[ServerSentEvent] +``` + +Decode the response content and yield corresponding [`ServerSentEvent`](#serversentevent). + +Example usage: + +```python +for sse in event_source.iter_sse(): + ... +``` + +#### `aiter_sse` + +```python +async def iter_sse() -> AsyncIterator[ServerSentEvent] +``` + +An async equivalent to `iter_sse`. + +### `ServerSentEvent` + +Represents a server-sent event. + +* `event: str` - Defaults to `"message"`. +* `data: str` - Defaults to `""`. +* `id: str` - Defaults to `""`. +* `retry: str | None` - Defaults to `None`. + +Methods: + +* `json() -> Any` - Returns `sse.data` decoded as JSON. + +### `SSEError` + +An error that occurred while making a request to an SSE endpoint. + +Parents: + +* `httpx.TransportError` + +## License + +MIT + +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## 0.4.1 - 2025-06-24 + +### Fixed + +* Always close the response async generator in `aiter_sse()`. (Pull #30) + +## 0.4.0 - 2023-12-22 + +### Removed + +* Dropped Python 3.7 support, as it has reached EOL. (Pull #21) + +### Added + +* Add official support for Python 3.12. (Pull #21) + +### Fixed + +* Allow `Content-Type` that contain but are not strictly `text/event-stream`. (Pull #22 by @dbuades) +* Improve error message when `Content-Type` is missing. (Pull #20 by @jamesbraza) + +## 0.3.1 - 2023-06-01 + +### Added + +* Add `__repr__()` for `ServerSentEvent` model, which may help with debugging and other tasks. (Pull #16) + +## 0.3.0 - 2023-04-27 + +### Changed + +* Raising an `SSEError` if the response content type is not `text/event-stream` is now performed as part of `iter_sse()` / `aiter_sse()`, instead of `connect_sse()` / `aconnect_sse()`. This allows inspecting the response before iterating on server-sent events, such as checking for error responses. (Pull #12) + +## 0.2.0 - 2023-03-27 + +### Changed + +* `connect_sse()` and `aconnect_sse()` now require a `method` argument: `connect_sse(client, "GET", "https://example.org")`. This provides support for SSE requests with HTTP verbs other than `GET`. (Pull #7) + +## 0.1.0 - 2023-02-05 + +_Initial release_ + +### Added + +* Add `connect_sse`, `aconnect_sse()`, `ServerSentEvent` and `SSEError`. diff --git a/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/RECORD b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d639755ce65c5156f641ea96a0c5d6a891f69eb0 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/RECORD @@ -0,0 +1,17 @@ +httpx_sse-0.4.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpx_sse-0.4.1.dist-info/METADATA,sha256=-9Zixuh3X-ko22mPKlQ2JM99arqsR56-y-bhpWr6L6E,9425 +httpx_sse-0.4.1.dist-info/RECORD,, +httpx_sse-0.4.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +httpx_sse-0.4.1.dist-info/licenses/LICENSE,sha256=vuxn5O6Dp68m8kK-2Zh6qGPW0t-3dhBqojYMQYfzGQE,1072 +httpx_sse-0.4.1.dist-info/top_level.txt,sha256=hbK3kwBH9d-rEZQvJ6yBawdDylIKfJ8fh0CM4EVNs04,10 +httpx_sse/__init__.py,sha256=z1ZzGzak69Y1zbftNSf4uK5PFbbYT059ZW-_eDYUx9c,282 +httpx_sse/__pycache__/__init__.cpython-312.pyc,, +httpx_sse/__pycache__/_api.cpython-312.pyc,, +httpx_sse/__pycache__/_decoders.cpython-312.pyc,, +httpx_sse/__pycache__/_exceptions.cpython-312.pyc,, +httpx_sse/__pycache__/_models.cpython-312.pyc,, +httpx_sse/_api.py,sha256=RqwZeUJMP92aeA7hCQne2Bqc0oGtLfl3FgY4bSy4kZU,2372 +httpx_sse/_decoders.py,sha256=4vOvJt_fFyKwmJeyJQLv_dt9ZQVNAskuMoQwT-65kcw,1748 +httpx_sse/_exceptions.py,sha256=sFZBUT1xIM1DvYQ6ckpzrhBG9d8VffFSZFMIEhv1N58,62 +httpx_sse/_models.py,sha256=4WwGeBEGMR2nbROTZ7PyVlu7chmWg7tbkJyXyd5DTx0,1221 +httpx_sse/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/WHEEL b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/top_level.txt b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a5e926f56e3d2574317cd01713fe078afad84fc2 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse-0.4.1.dist-info/top_level.txt @@ -0,0 +1 @@ +httpx_sse diff --git a/python_embeded/Lib/site-packages/httpx_sse/__init__.py b/python_embeded/Lib/site-packages/httpx_sse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a87150c6418bc2e1dd68e96c942300b66efbe145 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse/__init__.py @@ -0,0 +1,14 @@ +from ._api import EventSource, aconnect_sse, connect_sse +from ._exceptions import SSEError +from ._models import ServerSentEvent + +__version__ = "0.4.1" + +__all__ = [ + "__version__", + "EventSource", + "connect_sse", + "aconnect_sse", + "ServerSentEvent", + "SSEError", +] diff --git a/python_embeded/Lib/site-packages/httpx_sse/_api.py b/python_embeded/Lib/site-packages/httpx_sse/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..48114e0b0222bab751196492084bd3fe489b49e8 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse/_api.py @@ -0,0 +1,75 @@ +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager, contextmanager +from typing import Any, AsyncIterator, Iterator, cast + +import httpx + +from ._decoders import SSEDecoder +from ._exceptions import SSEError +from ._models import ServerSentEvent + + +class EventSource: + def __init__(self, response: httpx.Response) -> None: + self._response = response + + def _check_content_type(self) -> None: + content_type = self._response.headers.get("content-type", "").partition(";")[0] + if "text/event-stream" not in content_type: + raise SSEError( + "Expected response header Content-Type to contain 'text/event-stream', " + f"got {content_type!r}" + ) + + @property + def response(self) -> httpx.Response: + return self._response + + def iter_sse(self) -> Iterator[ServerSentEvent]: + self._check_content_type() + decoder = SSEDecoder() + for line in self._response.iter_lines(): + line = line.rstrip("\n") + sse = decoder.decode(line) + if sse is not None: + yield sse + + async def aiter_sse(self) -> AsyncGenerator[ServerSentEvent, None]: + self._check_content_type() + decoder = SSEDecoder() + lines = cast(AsyncGenerator[str, None], self._response.aiter_lines()) + try: + async for line in lines: + line = line.rstrip("\n") + sse = decoder.decode(line) + if sse is not None: + yield sse + finally: + await lines.aclose() + + +@contextmanager +def connect_sse( + client: httpx.Client, method: str, url: str, **kwargs: Any +) -> Iterator[EventSource]: + headers = kwargs.pop("headers", {}) + headers["Accept"] = "text/event-stream" + headers["Cache-Control"] = "no-store" + + with client.stream(method, url, headers=headers, **kwargs) as response: + yield EventSource(response) + + +@asynccontextmanager +async def aconnect_sse( + client: httpx.AsyncClient, + method: str, + url: str, + **kwargs: Any, +) -> AsyncIterator[EventSource]: + headers = kwargs.pop("headers", {}) + headers["Accept"] = "text/event-stream" + headers["Cache-Control"] = "no-store" + + async with client.stream(method, url, headers=headers, **kwargs) as response: + yield EventSource(response) diff --git a/python_embeded/Lib/site-packages/httpx_sse/_decoders.py b/python_embeded/Lib/site-packages/httpx_sse/_decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..256c4c0bf1164f53effab665c8866fadc9abfd21 --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse/_decoders.py @@ -0,0 +1,64 @@ +from typing import List, Optional + +from ._models import ServerSentEvent + + +class SSEDecoder: + def __init__(self) -> None: + self._event = "" + self._data: List[str] = [] + self._last_event_id = "" + self._retry: Optional[int] = None + + def decode(self, line: str) -> Optional[ServerSentEvent]: + # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501 + + if not line: + if ( + not self._event + and not self._data + and not self._last_event_id + and self._retry is None + ): + return None + + sse = ServerSentEvent( + event=self._event, + data="\n".join(self._data), + id=self._last_event_id, + retry=self._retry, + ) + + # NOTE: as per the SSE spec, do not reset last_event_id. + self._event = "" + self._data = [] + self._retry = None + + return sse + + if line.startswith(":"): + return None + + fieldname, _, value = line.partition(":") + + if value.startswith(" "): + value = value[1:] + + if fieldname == "event": + self._event = value + elif fieldname == "data": + self._data.append(value) + elif fieldname == "id": + if "\0" in value: + pass + else: + self._last_event_id = value + elif fieldname == "retry": + try: + self._retry = int(value) + except (TypeError, ValueError): + pass + else: + pass # Field is ignored. + + return None diff --git a/python_embeded/Lib/site-packages/httpx_sse/_models.py b/python_embeded/Lib/site-packages/httpx_sse/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..d4dc1190f7b02a8c97ab85e4f896787ca39dd9ec --- /dev/null +++ b/python_embeded/Lib/site-packages/httpx_sse/_models.py @@ -0,0 +1,54 @@ +import json +from typing import Any, Optional + + +class ServerSentEvent: + def __init__( + self, + event: Optional[str] = None, + data: Optional[str] = None, + id: Optional[str] = None, + retry: Optional[int] = None, + ) -> None: + if not event: + event = "message" + + if data is None: + data = "" + + if id is None: + id = "" + + self._event = event + self._data = data + self._id = id + self._retry = retry + + @property + def event(self) -> str: + return self._event + + @property + def data(self) -> str: + return self._data + + @property + def id(self) -> str: + return self._id + + @property + def retry(self) -> Optional[int]: + return self._retry + + def json(self) -> Any: + return json.loads(self.data) + + def __repr__(self) -> str: + pieces = [f"event={self.event!r}"] + if self.data != "": + pieces.append(f"data={self.data!r}") + if self.id != "": + pieces.append(f"id={self.id!r}") + if self.retry is not None: + pieces.append(f"retry={self.retry!r}") + return f"ServerSentEvent({', '.join(pieces)})" diff --git a/python_embeded/Lib/site-packages/httpx_sse/py.typed b/python_embeded/Lib/site-packages/httpx_sse/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/huggingface_hub/community.py b/python_embeded/Lib/site-packages/huggingface_hub/community.py new file mode 100644 index 0000000000000000000000000000000000000000..16f2f02428dd5c2ce6437534af0397801bda45c5 --- /dev/null +++ b/python_embeded/Lib/site-packages/huggingface_hub/community.py @@ -0,0 +1,355 @@ +""" +Data structures to interact with Discussions and Pull Requests on the Hub. + +See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions) +for more information on Pull Requests, Discussions, and the community tab. +""" + +from dataclasses import dataclass +from datetime import datetime +from typing import List, Literal, Optional, Union + +from . import constants +from .utils import parse_datetime + + +DiscussionStatus = Literal["open", "closed", "merged", "draft"] + + +@dataclass +class Discussion: + """ + A Discussion or Pull Request on the Hub. + + This dataclass is not intended to be instantiated directly. + + Attributes: + title (`str`): + The title of the Discussion / Pull Request + status (`str`): + The status of the Discussion / Pull Request. + It must be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + * `"draft"` (only for Pull Requests ) + num (`int`): + The number of the Discussion / Pull Request. + repo_id (`str`): + The id (`"{namespace}/{repo_name}"`) of the repo on which + the Discussion / Pull Request was open. + repo_type (`str`): + The type of the repo on which the Discussion / Pull Request was open. + Possible values are: `"model"`, `"dataset"`, `"space"`. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + is_pull_request (`bool`): + Whether or not this is a Pull Request. + created_at (`datetime`): + The `datetime` of creation of the Discussion / Pull Request. + endpoint (`str`): + Endpoint of the Hub. Default is https://huggingface.co. + git_reference (`str`, *optional*): + (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. + url (`str`): + (property) URL of the discussion on the Hub. + """ + + title: str + status: DiscussionStatus + num: int + repo_id: str + repo_type: str + author: str + is_pull_request: bool + created_at: datetime + endpoint: str + + @property + def git_reference(self) -> Optional[str]: + """ + If this is a Pull Request , returns the git reference to which changes can be pushed. + Returns `None` otherwise. + """ + if self.is_pull_request: + return f"refs/pr/{self.num}" + return None + + @property + def url(self) -> str: + """Returns the URL of the discussion on the Hub.""" + if self.repo_type is None or self.repo_type == constants.REPO_TYPE_MODEL: + return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}" + return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}" + + +@dataclass +class DiscussionWithDetails(Discussion): + """ + Subclass of [`Discussion`]. + + Attributes: + title (`str`): + The title of the Discussion / Pull Request + status (`str`): + The status of the Discussion / Pull Request. + It can be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + * `"draft"` (only for Pull Requests ) + num (`int`): + The number of the Discussion / Pull Request. + repo_id (`str`): + The id (`"{namespace}/{repo_name}"`) of the repo on which + the Discussion / Pull Request was open. + repo_type (`str`): + The type of the repo on which the Discussion / Pull Request was open. + Possible values are: `"model"`, `"dataset"`, `"space"`. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + is_pull_request (`bool`): + Whether or not this is a Pull Request. + created_at (`datetime`): + The `datetime` of creation of the Discussion / Pull Request. + events (`list` of [`DiscussionEvent`]) + The list of [`DiscussionEvents`] in this Discussion or Pull Request. + conflicting_files (`Union[List[str], bool, None]`, *optional*): + A list of conflicting files if this is a Pull Request. + `None` if `self.is_pull_request` is `False`. + `True` if there are conflicting files but the list can't be retrieved. + target_branch (`str`, *optional*): + The branch into which changes are to be merged if this is a + Pull Request . `None` if `self.is_pull_request` is `False`. + merge_commit_oid (`str`, *optional*): + If this is a merged Pull Request , this is set to the OID / SHA of + the merge commit, `None` otherwise. + diff (`str`, *optional*): + The git diff if this is a Pull Request , `None` otherwise. + endpoint (`str`): + Endpoint of the Hub. Default is https://huggingface.co. + git_reference (`str`, *optional*): + (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. + url (`str`): + (property) URL of the discussion on the Hub. + """ + + events: List["DiscussionEvent"] + conflicting_files: Union[List[str], bool, None] + target_branch: Optional[str] + merge_commit_oid: Optional[str] + diff: Optional[str] + + +@dataclass +class DiscussionEvent: + """ + An event in a Discussion or Pull Request. + + Use concrete classes: + * [`DiscussionComment`] + * [`DiscussionStatusChange`] + * [`DiscussionCommit`] + * [`DiscussionTitleChange`] + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + """ + + id: str + type: str + created_at: datetime + author: str + + _event: dict + """Stores the original event data, in case we need to access it later.""" + + +@dataclass +class DiscussionComment(DiscussionEvent): + """A comment in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + content (`str`): + The raw markdown content of the comment. Mentions, links and images are not rendered. + edited (`bool`): + Whether or not this comment has been edited. + hidden (`bool`): + Whether or not this comment has been hidden. + """ + + content: str + edited: bool + hidden: bool + + @property + def rendered(self) -> str: + """The rendered comment, as a HTML string""" + return self._event["data"]["latest"]["html"] + + @property + def last_edited_at(self) -> datetime: + """The last edit time, as a `datetime` object.""" + return parse_datetime(self._event["data"]["latest"]["updatedAt"]) + + @property + def last_edited_by(self) -> str: + """The last edit time, as a `datetime` object.""" + return self._event["data"]["latest"].get("author", {}).get("name", "deleted") + + @property + def edit_history(self) -> List[dict]: + """The edit history of the comment""" + return self._event["data"]["history"] + + @property + def number_of_edits(self) -> int: + return len(self.edit_history) + + +@dataclass +class DiscussionStatusChange(DiscussionEvent): + """A change of status in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + new_status (`str`): + The status of the Discussion / Pull Request after the change. + It can be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + """ + + new_status: str + + +@dataclass +class DiscussionCommit(DiscussionEvent): + """A commit in a Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + summary (`str`): + The summary of the commit. + oid (`str`): + The OID / SHA of the commit, as a hexadecimal string. + """ + + summary: str + oid: str + + +@dataclass +class DiscussionTitleChange(DiscussionEvent): + """A rename event in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + old_title (`str`): + The previous title for the Discussion / Pull Request. + new_title (`str`): + The new title. + """ + + old_title: str + new_title: str + + +def deserialize_event(event: dict) -> DiscussionEvent: + """Instantiates a [`DiscussionEvent`] from a dict""" + event_id: str = event["id"] + event_type: str = event["type"] + created_at = parse_datetime(event["createdAt"]) + + common_args = dict( + id=event_id, + type=event_type, + created_at=created_at, + author=event.get("author", {}).get("name", "deleted"), + _event=event, + ) + + if event_type == "comment": + return DiscussionComment( + **common_args, + edited=event["data"]["edited"], + hidden=event["data"]["hidden"], + content=event["data"]["latest"]["raw"], + ) + if event_type == "status-change": + return DiscussionStatusChange( + **common_args, + new_status=event["data"]["status"], + ) + if event_type == "commit": + return DiscussionCommit( + **common_args, + summary=event["data"]["subject"], + oid=event["data"]["oid"], + ) + if event_type == "title-change": + return DiscussionTitleChange( + **common_args, + old_title=event["data"]["from"], + new_title=event["data"]["to"], + ) + + return DiscussionEvent(**common_args) diff --git a/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/LICENSE.txt b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..96ece318ed5a5fa072e231c98495d746bacaeef9 --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2021 Peter Odding + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/METADATA b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c36fa4cafe53d55ba15ddc3c4045db067a165282 --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/METADATA @@ -0,0 +1,216 @@ +Metadata-Version: 2.1 +Name: humanfriendly +Version: 10.0 +Summary: Human friendly output for text interfaces using Python +Home-page: https://humanfriendly.readthedocs.io +Author: Peter Odding +Author-email: peter@peterodding.com +License: MIT +Platform: UNKNOWN +Classifier: Development Status :: 6 - Mature +Classifier: Environment :: Console +Classifier: Framework :: Sphinx :: Extension +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: System Administrators +Classifier: License :: OSI Approved :: MIT License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Communications +Classifier: Topic :: Scientific/Engineering :: Human Machine Interfaces +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: User Interfaces +Classifier: Topic :: System :: Shells +Classifier: Topic :: System :: System Shells +Classifier: Topic :: System :: Systems Administration +Classifier: Topic :: Terminals +Classifier: Topic :: Text Processing :: General +Classifier: Topic :: Text Processing :: Linguistic +Classifier: Topic :: Utilities +Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.* +Requires-Dist: monotonic ; python_version == "2.7" +Requires-Dist: pyreadline ; sys_platform == "win32" and python_version<"3.8" +Requires-Dist: pyreadline3 ; sys_platform == "win32" and python_version>="3.8" + +humanfriendly: Human friendly input/output in Python +==================================================== + +.. image:: https://github.com/xolox/python-humanfriendly/actions/workflows/test.yml/badge.svg?branch=master + :target: https://github.com/xolox/python-humanfriendly/actions + +.. image:: https://codecov.io/gh/xolox/python-humanfriendly/branch/master/graph/badge.svg?token=jYaj4T74TU + :target: https://codecov.io/gh/xolox/python-humanfriendly + +The functions and classes in the `humanfriendly` package can be used to make +text interfaces more user friendly. Some example features: + +- Parsing and formatting numbers, file sizes, pathnames and timespans in + simple, human friendly formats. + +- Easy to use timers for long running operations, with human friendly + formatting of the resulting timespans. + +- Prompting the user to select a choice from a list of options by typing the + option's number or a unique substring of the option. + +- Terminal interaction including text styling (`ANSI escape sequences`_), user + friendly rendering of usage messages and querying the terminal for its + size. + +The `humanfriendly` package is currently tested on Python 2.7, 3.5+ and PyPy +(2.7) on Linux and macOS. While the intention is to support Windows as well, +you may encounter some rough edges. + +.. contents:: + :local: + +Getting started +--------------- + +It's very simple to start using the `humanfriendly` package:: + + >>> from humanfriendly import format_size, parse_size + >>> from humanfriendly.prompts import prompt_for_input + >>> user_input = prompt_for_input("Enter a readable file size: ") + + Enter a readable file size: 16G + + >>> num_bytes = parse_size(user_input) + >>> print(num_bytes) + 16000000000 + >>> print("You entered:", format_size(num_bytes)) + You entered: 16 GB + >>> print("You entered:", format_size(num_bytes, binary=True)) + You entered: 14.9 GiB + +To get a demonstration of supported terminal text styles (based on +`ANSI escape sequences`_) you can run the following command:: + + $ humanfriendly --demo + +Command line +------------ + +.. A DRY solution to avoid duplication of the `humanfriendly --help' text: +.. +.. [[[cog +.. from humanfriendly.usage import inject_usage +.. inject_usage('humanfriendly.cli') +.. ]]] + +**Usage:** `humanfriendly [OPTIONS]` + +Human friendly input/output (text formatting) on the command +line based on the Python package with the same name. + +**Supported options:** + +.. csv-table:: + :header: Option, Description + :widths: 30, 70 + + + "``-c``, ``--run-command``","Execute an external command (given as the positional arguments) and render + a spinner and timer while the command is running. The exit status of the + command is propagated." + ``--format-table``,"Read tabular data from standard input (each line is a row and each + whitespace separated field is a column), format the data as a table and + print the resulting table to standard output. See also the ``--delimiter`` + option." + "``-d``, ``--delimiter=VALUE``","Change the delimiter used by ``--format-table`` to ``VALUE`` (a string). By default + all whitespace is treated as a delimiter." + "``-l``, ``--format-length=LENGTH``","Convert a length count (given as the integer or float ``LENGTH``) into a human + readable string and print that string to standard output." + "``-n``, ``--format-number=VALUE``","Format a number (given as the integer or floating point number ``VALUE``) with + thousands separators and two decimal places (if needed) and print the + formatted number to standard output." + "``-s``, ``--format-size=BYTES``","Convert a byte count (given as the integer ``BYTES``) into a human readable + string and print that string to standard output." + "``-b``, ``--binary``","Change the output of ``-s``, ``--format-size`` to use binary multiples of bytes + (base-2) instead of the default decimal multiples of bytes (base-10)." + "``-t``, ``--format-timespan=SECONDS``","Convert a number of seconds (given as the floating point number ``SECONDS``) + into a human readable timespan and print that string to standard output." + ``--parse-length=VALUE``,"Parse a human readable length (given as the string ``VALUE``) and print the + number of metres to standard output." + ``--parse-size=VALUE``,"Parse a human readable data size (given as the string ``VALUE``) and print the + number of bytes to standard output." + ``--demo``,"Demonstrate changing the style and color of the terminal font using ANSI + escape sequences." + "``-h``, ``--help``",Show this message and exit. + +.. [[[end]]] + +A note about size units +----------------------- + +When I originally published the `humanfriendly` package I went with binary +multiples of bytes (powers of two). It was pointed out several times that this +was a poor choice (see issue `#4`_ and pull requests `#8`_ and `#9`_) and thus +the new default became decimal multiples of bytes (powers of ten): + ++------+---------------+---------------+ +| Unit | Binary value | Decimal value | ++------+---------------+---------------+ +| KB | 1024 | 1000 + ++------+---------------+---------------+ +| MB | 1048576 | 1000000 | ++------+---------------+---------------+ +| GB | 1073741824 | 1000000000 | ++------+---------------+---------------+ +| TB | 1099511627776 | 1000000000000 | ++------+---------------+---------------+ +| etc | | | ++------+---------------+---------------+ + +The option to use binary multiples of bytes remains by passing the keyword +argument `binary=True` to the `format_size()`_ and `parse_size()`_ functions. + +Windows support +--------------- + +Windows 10 gained native support for ANSI escape sequences which means commands +like ``humanfriendly --demo`` should work out of the box (if your system is +up-to-date enough). If this doesn't work then you can install the colorama_ +package, it will be used automatically once installed. + +Contact +------- + +The latest version of `humanfriendly` is available on PyPI_ and GitHub_. The +documentation is hosted on `Read the Docs`_ and includes a changelog_. For bug +reports please create an issue on GitHub_. If you have questions, suggestions, +etc. feel free to send me an e-mail at `peter@peterodding.com`_. + +License +------- + +This software is licensed under the `MIT license`_. + +© 2021 Peter Odding. + +.. External references: +.. _#4: https://github.com/xolox/python-humanfriendly/issues/4 +.. _#8: https://github.com/xolox/python-humanfriendly/pull/8 +.. _#9: https://github.com/xolox/python-humanfriendly/pull/9 +.. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code +.. _changelog: https://humanfriendly.readthedocs.io/en/latest/changelog.html +.. _colorama: https://pypi.org/project/colorama +.. _format_size(): https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.format_size +.. _GitHub: https://github.com/xolox/python-humanfriendly +.. _MIT license: https://en.wikipedia.org/wiki/MIT_License +.. _parse_size(): https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.parse_size +.. _peter@peterodding.com: peter@peterodding.com +.. _PyPI: https://pypi.org/project/humanfriendly +.. _Read the Docs: https://humanfriendly.readthedocs.io + + diff --git a/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/RECORD b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..853a10c1a8a30715a17a898abedc9d9929dc924d --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/RECORD @@ -0,0 +1,40 @@ +../../Scripts/humanfriendly.exe,sha256=N5uYjiRd7MD2U61Cg55DZioxXWjQcOXdwtzI4cQY1aM,108418 +humanfriendly-10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +humanfriendly-10.0.dist-info/LICENSE.txt,sha256=SsSPQReAnyc0BmFQRQ8SCzuxEKwdOzIXB5XgVg27wfU,1056 +humanfriendly-10.0.dist-info/METADATA,sha256=aLs0k4jN_spgKsw0Vbg6ey_jy-hAJeJ0k7y-dvOrbII,9201 +humanfriendly-10.0.dist-info/RECORD,, +humanfriendly-10.0.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110 +humanfriendly-10.0.dist-info/entry_points.txt,sha256=hU-ADsGls3mgf3plBt9B-oYLCtBDQiUJZ00khuAoqXc,58 +humanfriendly-10.0.dist-info/top_level.txt,sha256=7eKAKhckmlD4ZoWJkWmhnTs1pnP_bzF-56VTq0D7WIo,14 +humanfriendly/__init__.py,sha256=sPCMQv16m3p8xYwd3N3kUs1rewVJB3ZGDBkF0_8v6vo,31725 +humanfriendly/__pycache__/__init__.cpython-312.pyc,, +humanfriendly/__pycache__/case.cpython-312.pyc,, +humanfriendly/__pycache__/cli.cpython-312.pyc,, +humanfriendly/__pycache__/compat.cpython-312.pyc,, +humanfriendly/__pycache__/decorators.cpython-312.pyc,, +humanfriendly/__pycache__/deprecation.cpython-312.pyc,, +humanfriendly/__pycache__/prompts.cpython-312.pyc,, +humanfriendly/__pycache__/sphinx.cpython-312.pyc,, +humanfriendly/__pycache__/tables.cpython-312.pyc,, +humanfriendly/__pycache__/testing.cpython-312.pyc,, +humanfriendly/__pycache__/tests.cpython-312.pyc,, +humanfriendly/__pycache__/text.cpython-312.pyc,, +humanfriendly/__pycache__/usage.cpython-312.pyc,, +humanfriendly/case.py,sha256=fkIinj4V1S8Xl3OCSYSgqKoGzCCbVJOjI5ZznViCT1Q,6008 +humanfriendly/cli.py,sha256=ZpGqTHLwfLjFACsQacYkN9DiBZkGecPzIHysliWN1i8,9822 +humanfriendly/compat.py,sha256=7qoFGMNFizGhs5BIyiMKTDUq29DxzuXGX4MRoZLo4ms,3984 +humanfriendly/decorators.py,sha256=ivxB-U9dfXUjCl4GZ8g_gKFC4a3uyxDVi-3rlxPjvJo,1501 +humanfriendly/deprecation.py,sha256=bdx1_T8L1gF635E41E6bYTqie9P3o7rY6n4wohjkLLk,9499 +humanfriendly/prompts.py,sha256=8PSJ1Hpr3ld6YkCaXQsTHAep9BtTKYlKmQi1RiaHIEc,16335 +humanfriendly/sphinx.py,sha256=BrFxK-rX3LN4iMqgNFuOTweYfppYp--O3HqWBlu05M0,11452 +humanfriendly/tables.py,sha256=lCDnEKyyZRmrIHrDlUzzVpg9z6lKOO8ldP4fh1gzMBI,13968 +humanfriendly/terminal/__init__.py,sha256=5BzxVHKriznclRjrWwYEk2l1ct0q0WdupJIrkuI9glc,30759 +humanfriendly/terminal/__pycache__/__init__.cpython-312.pyc,, +humanfriendly/terminal/__pycache__/html.cpython-312.pyc,, +humanfriendly/terminal/__pycache__/spinners.cpython-312.pyc,, +humanfriendly/terminal/html.py,sha256=_csUZ4hID0ATwTvPXU8KrAe6ZzD_gUS7_tN3FmCHA4Q,16747 +humanfriendly/terminal/spinners.py,sha256=o7nkn8rBdTqr-XHIT972sIgIuxiDymQ5kPVkBzR7utE,11323 +humanfriendly/testing.py,sha256=hErsmBN5Crej5k1P_I0dhQK8IAwFr1IOZ9kQPIrZUys,24359 +humanfriendly/tests.py,sha256=3bkasrRgw0cAdZFHgmTo4DUHgXEnlHtRoq_t2MEafbc,68919 +humanfriendly/text.py,sha256=_WBG4SZ4bT5SH94zLUdfmB6NXbvc4gBYECEmQYXJ1sE,16212 +humanfriendly/usage.py,sha256=AhPo6DcvaBRIFGWNctU22McMzN3Ryc6ZCC83kt2Zbk4,13768 diff --git a/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ef99c6cf3283b50a273ac4c6d009a0aa85597070 --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.34.2) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ce8fb835327993d3f6319a10b722b908601de30 --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +humanfriendly = humanfriendly.cli:main + diff --git a/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f5368c4974de83a9507c8c10676150fc0f3e2b69 --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly-10.0.dist-info/top_level.txt @@ -0,0 +1 @@ +humanfriendly diff --git a/python_embeded/Lib/site-packages/humanfriendly/__init__.py b/python_embeded/Lib/site-packages/humanfriendly/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c0a333861df55f5676e6dfd69c5e5ac1ece0213 --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly/__init__.py @@ -0,0 +1,838 @@ +# Human friendly input/output in Python. +# +# Author: Peter Odding +# Last Change: September 17, 2021 +# URL: https://humanfriendly.readthedocs.io + +"""The main module of the `humanfriendly` package.""" + +# Standard library modules. +import collections +import datetime +import decimal +import numbers +import os +import os.path +import re +import time + +# Modules included in our package. +from humanfriendly.compat import is_string, monotonic +from humanfriendly.deprecation import define_aliases +from humanfriendly.text import concatenate, format, pluralize, tokenize + +# Public identifiers that require documentation. +__all__ = ( + 'CombinedUnit', + 'InvalidDate', + 'InvalidLength', + 'InvalidSize', + 'InvalidTimespan', + 'SizeUnit', + 'Timer', + '__version__', + 'coerce_boolean', + 'coerce_pattern', + 'coerce_seconds', + 'disk_size_units', + 'format_length', + 'format_number', + 'format_path', + 'format_size', + 'format_timespan', + 'length_size_units', + 'parse_date', + 'parse_length', + 'parse_path', + 'parse_size', + 'parse_timespan', + 'round_number', + 'time_units', +) + +# Semi-standard module versioning. +__version__ = '10.0' + +# Named tuples to define units of size. +SizeUnit = collections.namedtuple('SizeUnit', 'divider, symbol, name') +CombinedUnit = collections.namedtuple('CombinedUnit', 'decimal, binary') + +# Common disk size units in binary (base-2) and decimal (base-10) multiples. +disk_size_units = ( + CombinedUnit(SizeUnit(1000**1, 'KB', 'kilobyte'), SizeUnit(1024**1, 'KiB', 'kibibyte')), + CombinedUnit(SizeUnit(1000**2, 'MB', 'megabyte'), SizeUnit(1024**2, 'MiB', 'mebibyte')), + CombinedUnit(SizeUnit(1000**3, 'GB', 'gigabyte'), SizeUnit(1024**3, 'GiB', 'gibibyte')), + CombinedUnit(SizeUnit(1000**4, 'TB', 'terabyte'), SizeUnit(1024**4, 'TiB', 'tebibyte')), + CombinedUnit(SizeUnit(1000**5, 'PB', 'petabyte'), SizeUnit(1024**5, 'PiB', 'pebibyte')), + CombinedUnit(SizeUnit(1000**6, 'EB', 'exabyte'), SizeUnit(1024**6, 'EiB', 'exbibyte')), + CombinedUnit(SizeUnit(1000**7, 'ZB', 'zettabyte'), SizeUnit(1024**7, 'ZiB', 'zebibyte')), + CombinedUnit(SizeUnit(1000**8, 'YB', 'yottabyte'), SizeUnit(1024**8, 'YiB', 'yobibyte')), +) + +# Common length size units, used for formatting and parsing. +length_size_units = (dict(prefix='nm', divider=1e-09, singular='nm', plural='nm'), + dict(prefix='mm', divider=1e-03, singular='mm', plural='mm'), + dict(prefix='cm', divider=1e-02, singular='cm', plural='cm'), + dict(prefix='m', divider=1, singular='metre', plural='metres'), + dict(prefix='km', divider=1000, singular='km', plural='km')) + +# Common time units, used for formatting of time spans. +time_units = (dict(divider=1e-9, singular='nanosecond', plural='nanoseconds', abbreviations=['ns']), + dict(divider=1e-6, singular='microsecond', plural='microseconds', abbreviations=['us']), + dict(divider=1e-3, singular='millisecond', plural='milliseconds', abbreviations=['ms']), + dict(divider=1, singular='second', plural='seconds', abbreviations=['s', 'sec', 'secs']), + dict(divider=60, singular='minute', plural='minutes', abbreviations=['m', 'min', 'mins']), + dict(divider=60 * 60, singular='hour', plural='hours', abbreviations=['h']), + dict(divider=60 * 60 * 24, singular='day', plural='days', abbreviations=['d']), + dict(divider=60 * 60 * 24 * 7, singular='week', plural='weeks', abbreviations=['w']), + dict(divider=60 * 60 * 24 * 7 * 52, singular='year', plural='years', abbreviations=['y'])) + + +def coerce_boolean(value): + """ + Coerce any value to a boolean. + + :param value: Any Python value. If the value is a string: + + - The strings '1', 'yes', 'true' and 'on' are coerced to :data:`True`. + - The strings '0', 'no', 'false' and 'off' are coerced to :data:`False`. + - Other strings raise an exception. + + Other Python values are coerced using :class:`bool`. + :returns: A proper boolean value. + :raises: :exc:`exceptions.ValueError` when the value is a string but + cannot be coerced with certainty. + """ + if is_string(value): + normalized = value.strip().lower() + if normalized in ('1', 'yes', 'true', 'on'): + return True + elif normalized in ('0', 'no', 'false', 'off', ''): + return False + else: + msg = "Failed to coerce string to boolean! (%r)" + raise ValueError(format(msg, value)) + else: + return bool(value) + + +def coerce_pattern(value, flags=0): + """ + Coerce strings to compiled regular expressions. + + :param value: A string containing a regular expression pattern + or a compiled regular expression. + :param flags: The flags used to compile the pattern (an integer). + :returns: A compiled regular expression. + :raises: :exc:`~exceptions.ValueError` when `value` isn't a string + and also isn't a compiled regular expression. + """ + if is_string(value): + value = re.compile(value, flags) + else: + empty_pattern = re.compile('') + pattern_type = type(empty_pattern) + if not isinstance(value, pattern_type): + msg = "Failed to coerce value to compiled regular expression! (%r)" + raise ValueError(format(msg, value)) + return value + + +def coerce_seconds(value): + """ + Coerce a value to the number of seconds. + + :param value: An :class:`int`, :class:`float` or + :class:`datetime.timedelta` object. + :returns: An :class:`int` or :class:`float` value. + + When `value` is a :class:`datetime.timedelta` object the + :meth:`~datetime.timedelta.total_seconds()` method is called. + """ + if isinstance(value, datetime.timedelta): + return value.total_seconds() + if not isinstance(value, numbers.Number): + msg = "Failed to coerce value to number of seconds! (%r)" + raise ValueError(format(msg, value)) + return value + + +def format_size(num_bytes, keep_width=False, binary=False): + """ + Format a byte count as a human readable file size. + + :param num_bytes: The size to format in bytes (an integer). + :param keep_width: :data:`True` if trailing zeros should not be stripped, + :data:`False` if they can be stripped. + :param binary: :data:`True` to use binary multiples of bytes (base-2), + :data:`False` to use decimal multiples of bytes (base-10). + :returns: The corresponding human readable file size (a string). + + This function knows how to format sizes in bytes, kilobytes, megabytes, + gigabytes, terabytes and petabytes. Some examples: + + >>> from humanfriendly import format_size + >>> format_size(0) + '0 bytes' + >>> format_size(1) + '1 byte' + >>> format_size(5) + '5 bytes' + > format_size(1000) + '1 KB' + > format_size(1024, binary=True) + '1 KiB' + >>> format_size(1000 ** 3 * 4) + '4 GB' + """ + for unit in reversed(disk_size_units): + if num_bytes >= unit.binary.divider and binary: + number = round_number(float(num_bytes) / unit.binary.divider, keep_width=keep_width) + return pluralize(number, unit.binary.symbol, unit.binary.symbol) + elif num_bytes >= unit.decimal.divider and not binary: + number = round_number(float(num_bytes) / unit.decimal.divider, keep_width=keep_width) + return pluralize(number, unit.decimal.symbol, unit.decimal.symbol) + return pluralize(num_bytes, 'byte') + + +def parse_size(size, binary=False): + """ + Parse a human readable data size and return the number of bytes. + + :param size: The human readable file size to parse (a string). + :param binary: :data:`True` to use binary multiples of bytes (base-2) for + ambiguous unit symbols and names, :data:`False` to use + decimal multiples of bytes (base-10). + :returns: The corresponding size in bytes (an integer). + :raises: :exc:`InvalidSize` when the input can't be parsed. + + This function knows how to parse sizes in bytes, kilobytes, megabytes, + gigabytes, terabytes and petabytes. Some examples: + + >>> from humanfriendly import parse_size + >>> parse_size('42') + 42 + >>> parse_size('13b') + 13 + >>> parse_size('5 bytes') + 5 + >>> parse_size('1 KB') + 1000 + >>> parse_size('1 kilobyte') + 1000 + >>> parse_size('1 KiB') + 1024 + >>> parse_size('1 KB', binary=True) + 1024 + >>> parse_size('1.5 GB') + 1500000000 + >>> parse_size('1.5 GB', binary=True) + 1610612736 + """ + tokens = tokenize(size) + if tokens and isinstance(tokens[0], numbers.Number): + # Get the normalized unit (if any) from the tokenized input. + normalized_unit = tokens[1].lower() if len(tokens) == 2 and is_string(tokens[1]) else '' + # If the input contains only a number, it's assumed to be the number of + # bytes. The second token can also explicitly reference the unit bytes. + if len(tokens) == 1 or normalized_unit.startswith('b'): + return int(tokens[0]) + # Otherwise we expect two tokens: A number and a unit. + if normalized_unit: + # Convert plural units to singular units, for details: + # https://github.com/xolox/python-humanfriendly/issues/26 + normalized_unit = normalized_unit.rstrip('s') + for unit in disk_size_units: + # First we check for unambiguous symbols (KiB, MiB, GiB, etc) + # and names (kibibyte, mebibyte, gibibyte, etc) because their + # handling is always the same. + if normalized_unit in (unit.binary.symbol.lower(), unit.binary.name.lower()): + return int(tokens[0] * unit.binary.divider) + # Now we will deal with ambiguous prefixes (K, M, G, etc), + # symbols (KB, MB, GB, etc) and names (kilobyte, megabyte, + # gigabyte, etc) according to the caller's preference. + if (normalized_unit in (unit.decimal.symbol.lower(), unit.decimal.name.lower()) or + normalized_unit.startswith(unit.decimal.symbol[0].lower())): + return int(tokens[0] * (unit.binary.divider if binary else unit.decimal.divider)) + # We failed to parse the size specification. + msg = "Failed to parse size! (input %r was tokenized as %r)" + raise InvalidSize(format(msg, size, tokens)) + + +def format_length(num_metres, keep_width=False): + """ + Format a metre count as a human readable length. + + :param num_metres: The length to format in metres (float / integer). + :param keep_width: :data:`True` if trailing zeros should not be stripped, + :data:`False` if they can be stripped. + :returns: The corresponding human readable length (a string). + + This function supports ranges from nanometres to kilometres. + + Some examples: + + >>> from humanfriendly import format_length + >>> format_length(0) + '0 metres' + >>> format_length(1) + '1 metre' + >>> format_length(5) + '5 metres' + >>> format_length(1000) + '1 km' + >>> format_length(0.004) + '4 mm' + """ + for unit in reversed(length_size_units): + if num_metres >= unit['divider']: + number = round_number(float(num_metres) / unit['divider'], keep_width=keep_width) + return pluralize(number, unit['singular'], unit['plural']) + return pluralize(num_metres, 'metre') + + +def parse_length(length): + """ + Parse a human readable length and return the number of metres. + + :param length: The human readable length to parse (a string). + :returns: The corresponding length in metres (a float). + :raises: :exc:`InvalidLength` when the input can't be parsed. + + Some examples: + + >>> from humanfriendly import parse_length + >>> parse_length('42') + 42 + >>> parse_length('1 km') + 1000 + >>> parse_length('5mm') + 0.005 + >>> parse_length('15.3cm') + 0.153 + """ + tokens = tokenize(length) + if tokens and isinstance(tokens[0], numbers.Number): + # If the input contains only a number, it's assumed to be the number of metres. + if len(tokens) == 1: + return tokens[0] + # Otherwise we expect to find two tokens: A number and a unit. + if len(tokens) == 2 and is_string(tokens[1]): + normalized_unit = tokens[1].lower() + # Try to match the first letter of the unit. + for unit in length_size_units: + if normalized_unit.startswith(unit['prefix']): + return tokens[0] * unit['divider'] + # We failed to parse the length specification. + msg = "Failed to parse length! (input %r was tokenized as %r)" + raise InvalidLength(format(msg, length, tokens)) + + +def format_number(number, num_decimals=2): + """ + Format a number as a string including thousands separators. + + :param number: The number to format (a number like an :class:`int`, + :class:`long` or :class:`float`). + :param num_decimals: The number of decimals to render (2 by default). If no + decimal places are required to represent the number + they will be omitted regardless of this argument. + :returns: The formatted number (a string). + + This function is intended to make it easier to recognize the order of size + of the number being formatted. + + Here's an example: + + >>> from humanfriendly import format_number + >>> print(format_number(6000000)) + 6,000,000 + > print(format_number(6000000000.42)) + 6,000,000,000.42 + > print(format_number(6000000000.42, num_decimals=0)) + 6,000,000,000 + """ + integer_part, _, decimal_part = str(float(number)).partition('.') + negative_sign = integer_part.startswith('-') + reversed_digits = ''.join(reversed(integer_part.lstrip('-'))) + parts = [] + while reversed_digits: + parts.append(reversed_digits[:3]) + reversed_digits = reversed_digits[3:] + formatted_number = ''.join(reversed(','.join(parts))) + decimals_to_add = decimal_part[:num_decimals].rstrip('0') + if decimals_to_add: + formatted_number += '.' + decimals_to_add + if negative_sign: + formatted_number = '-' + formatted_number + return formatted_number + + +def round_number(count, keep_width=False): + """ + Round a floating point number to two decimal places in a human friendly format. + + :param count: The number to format. + :param keep_width: :data:`True` if trailing zeros should not be stripped, + :data:`False` if they can be stripped. + :returns: The formatted number as a string. If no decimal places are + required to represent the number, they will be omitted. + + The main purpose of this function is to be used by functions like + :func:`format_length()`, :func:`format_size()` and + :func:`format_timespan()`. + + Here are some examples: + + >>> from humanfriendly import round_number + >>> round_number(1) + '1' + >>> round_number(math.pi) + '3.14' + >>> round_number(5.001) + '5' + """ + text = '%.2f' % float(count) + if not keep_width: + text = re.sub('0+$', '', text) + text = re.sub(r'\.$', '', text) + return text + + +def format_timespan(num_seconds, detailed=False, max_units=3): + """ + Format a timespan in seconds as a human readable string. + + :param num_seconds: Any value accepted by :func:`coerce_seconds()`. + :param detailed: If :data:`True` milliseconds are represented separately + instead of being represented as fractional seconds + (defaults to :data:`False`). + :param max_units: The maximum number of units to show in the formatted time + span (an integer, defaults to three). + :returns: The formatted timespan as a string. + :raise: See :func:`coerce_seconds()`. + + Some examples: + + >>> from humanfriendly import format_timespan + >>> format_timespan(0) + '0 seconds' + >>> format_timespan(1) + '1 second' + >>> import math + >>> format_timespan(math.pi) + '3.14 seconds' + >>> hour = 60 * 60 + >>> day = hour * 24 + >>> week = day * 7 + >>> format_timespan(week * 52 + day * 2 + hour * 3) + '1 year, 2 days and 3 hours' + """ + num_seconds = coerce_seconds(num_seconds) + if num_seconds < 60 and not detailed: + # Fast path. + return pluralize(round_number(num_seconds), 'second') + else: + # Slow path. + result = [] + num_seconds = decimal.Decimal(str(num_seconds)) + relevant_units = list(reversed(time_units[0 if detailed else 3:])) + for unit in relevant_units: + # Extract the unit count from the remaining time. + divider = decimal.Decimal(str(unit['divider'])) + count = num_seconds / divider + num_seconds %= divider + # Round the unit count appropriately. + if unit != relevant_units[-1]: + # Integer rounding for all but the smallest unit. + count = int(count) + else: + # Floating point rounding for the smallest unit. + count = round_number(count) + # Only include relevant units in the result. + if count not in (0, '0'): + result.append(pluralize(count, unit['singular'], unit['plural'])) + if len(result) == 1: + # A single count/unit combination. + return result[0] + else: + if not detailed: + # Remove `insignificant' data from the formatted timespan. + result = result[:max_units] + # Format the timespan in a readable way. + return concatenate(result) + + +def parse_timespan(timespan): + """ + Parse a "human friendly" timespan into the number of seconds. + + :param value: A string like ``5h`` (5 hours), ``10m`` (10 minutes) or + ``42s`` (42 seconds). + :returns: The number of seconds as a floating point number. + :raises: :exc:`InvalidTimespan` when the input can't be parsed. + + Note that the :func:`parse_timespan()` function is not meant to be the + "mirror image" of the :func:`format_timespan()` function. Instead it's + meant to allow humans to easily and succinctly specify a timespan with a + minimal amount of typing. It's very useful to accept easy to write time + spans as e.g. command line arguments to programs. + + The time units (and abbreviations) supported by this function are: + + - ms, millisecond, milliseconds + - s, sec, secs, second, seconds + - m, min, mins, minute, minutes + - h, hour, hours + - d, day, days + - w, week, weeks + - y, year, years + + Some examples: + + >>> from humanfriendly import parse_timespan + >>> parse_timespan('42') + 42.0 + >>> parse_timespan('42s') + 42.0 + >>> parse_timespan('1m') + 60.0 + >>> parse_timespan('1h') + 3600.0 + >>> parse_timespan('1d') + 86400.0 + """ + tokens = tokenize(timespan) + if tokens and isinstance(tokens[0], numbers.Number): + # If the input contains only a number, it's assumed to be the number of seconds. + if len(tokens) == 1: + return float(tokens[0]) + # Otherwise we expect to find two tokens: A number and a unit. + if len(tokens) == 2 and is_string(tokens[1]): + normalized_unit = tokens[1].lower() + for unit in time_units: + if (normalized_unit == unit['singular'] or + normalized_unit == unit['plural'] or + normalized_unit in unit['abbreviations']): + return float(tokens[0]) * unit['divider'] + # We failed to parse the timespan specification. + msg = "Failed to parse timespan! (input %r was tokenized as %r)" + raise InvalidTimespan(format(msg, timespan, tokens)) + + +def parse_date(datestring): + """ + Parse a date/time string into a tuple of integers. + + :param datestring: The date/time string to parse. + :returns: A tuple with the numbers ``(year, month, day, hour, minute, + second)`` (all numbers are integers). + :raises: :exc:`InvalidDate` when the date cannot be parsed. + + Supported date/time formats: + + - ``YYYY-MM-DD`` + - ``YYYY-MM-DD HH:MM:SS`` + + .. note:: If you want to parse date/time strings with a fixed, known + format and :func:`parse_date()` isn't useful to you, consider + :func:`time.strptime()` or :meth:`datetime.datetime.strptime()`, + both of which are included in the Python standard library. + Alternatively for more complex tasks consider using the date/time + parsing module in the dateutil_ package. + + Examples: + + >>> from humanfriendly import parse_date + >>> parse_date('2013-06-17') + (2013, 6, 17, 0, 0, 0) + >>> parse_date('2013-06-17 02:47:42') + (2013, 6, 17, 2, 47, 42) + + Here's how you convert the result to a number (`Unix time`_): + + >>> from humanfriendly import parse_date + >>> from time import mktime + >>> mktime(parse_date('2013-06-17 02:47:42') + (-1, -1, -1)) + 1371430062.0 + + And here's how you convert it to a :class:`datetime.datetime` object: + + >>> from humanfriendly import parse_date + >>> from datetime import datetime + >>> datetime(*parse_date('2013-06-17 02:47:42')) + datetime.datetime(2013, 6, 17, 2, 47, 42) + + Here's an example that combines :func:`format_timespan()` and + :func:`parse_date()` to calculate a human friendly timespan since a + given date: + + >>> from humanfriendly import format_timespan, parse_date + >>> from time import mktime, time + >>> unix_time = mktime(parse_date('2013-06-17 02:47:42') + (-1, -1, -1)) + >>> seconds_since_then = time() - unix_time + >>> print(format_timespan(seconds_since_then)) + 1 year, 43 weeks and 1 day + + .. _dateutil: https://dateutil.readthedocs.io/en/latest/parser.html + .. _Unix time: http://en.wikipedia.org/wiki/Unix_time + """ + try: + tokens = [t.strip() for t in datestring.split()] + if len(tokens) >= 2: + date_parts = list(map(int, tokens[0].split('-'))) + [1, 1] + time_parts = list(map(int, tokens[1].split(':'))) + [0, 0, 0] + return tuple(date_parts[0:3] + time_parts[0:3]) + else: + year, month, day = (list(map(int, datestring.split('-'))) + [1, 1])[0:3] + return (year, month, day, 0, 0, 0) + except Exception: + msg = "Invalid date! (expected 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' but got: %r)" + raise InvalidDate(format(msg, datestring)) + + +def format_path(pathname): + """ + Shorten a pathname to make it more human friendly. + + :param pathname: An absolute pathname (a string). + :returns: The pathname with the user's home directory abbreviated. + + Given an absolute pathname, this function abbreviates the user's home + directory to ``~/`` in order to shorten the pathname without losing + information. It is not an error if the pathname is not relative to the + current user's home directory. + + Here's an example of its usage: + + >>> from os import environ + >>> from os.path import join + >>> vimrc = join(environ['HOME'], '.vimrc') + >>> vimrc + '/home/peter/.vimrc' + >>> from humanfriendly import format_path + >>> format_path(vimrc) + '~/.vimrc' + """ + pathname = os.path.abspath(pathname) + home = os.environ.get('HOME') + if home: + home = os.path.abspath(home) + if pathname.startswith(home): + pathname = os.path.join('~', os.path.relpath(pathname, home)) + return pathname + + +def parse_path(pathname): + """ + Convert a human friendly pathname to an absolute pathname. + + Expands leading tildes using :func:`os.path.expanduser()` and + environment variables using :func:`os.path.expandvars()` and makes the + resulting pathname absolute using :func:`os.path.abspath()`. + + :param pathname: A human friendly pathname (a string). + :returns: An absolute pathname (a string). + """ + return os.path.abspath(os.path.expanduser(os.path.expandvars(pathname))) + + +class Timer(object): + + """ + Easy to use timer to keep track of long during operations. + """ + + def __init__(self, start_time=None, resumable=False): + """ + Remember the time when the :class:`Timer` was created. + + :param start_time: The start time (a float, defaults to the current time). + :param resumable: Create a resumable timer (defaults to :data:`False`). + + When `start_time` is given :class:`Timer` uses :func:`time.time()` as a + clock source, otherwise it uses :func:`humanfriendly.compat.monotonic()`. + """ + if resumable: + self.monotonic = True + self.resumable = True + self.start_time = 0.0 + self.total_time = 0.0 + elif start_time: + self.monotonic = False + self.resumable = False + self.start_time = start_time + else: + self.monotonic = True + self.resumable = False + self.start_time = monotonic() + + def __enter__(self): + """ + Start or resume counting elapsed time. + + :returns: The :class:`Timer` object. + :raises: :exc:`~exceptions.ValueError` when the timer isn't resumable. + """ + if not self.resumable: + raise ValueError("Timer is not resumable!") + self.start_time = monotonic() + return self + + def __exit__(self, exc_type=None, exc_value=None, traceback=None): + """ + Stop counting elapsed time. + + :raises: :exc:`~exceptions.ValueError` when the timer isn't resumable. + """ + if not self.resumable: + raise ValueError("Timer is not resumable!") + if self.start_time: + self.total_time += monotonic() - self.start_time + self.start_time = 0.0 + + def sleep(self, seconds): + """ + Easy to use rate limiting of repeating actions. + + :param seconds: The number of seconds to sleep (an + integer or floating point number). + + This method sleeps for the given number of seconds minus the + :attr:`elapsed_time`. If the resulting duration is negative + :func:`time.sleep()` will still be called, but the argument + given to it will be the number 0 (negative numbers cause + :func:`time.sleep()` to raise an exception). + + The use case for this is to initialize a :class:`Timer` inside + the body of a :keyword:`for` or :keyword:`while` loop and call + :func:`Timer.sleep()` at the end of the loop body to rate limit + whatever it is that is being done inside the loop body. + + For posterity: Although the implementation of :func:`sleep()` only + requires a single line of code I've added it to :mod:`humanfriendly` + anyway because now that I've thought about how to tackle this once I + never want to have to think about it again :-P (unless I find ways to + improve this). + """ + time.sleep(max(0, seconds - self.elapsed_time)) + + @property + def elapsed_time(self): + """ + Get the number of seconds counted so far. + """ + elapsed_time = 0 + if self.resumable: + elapsed_time += self.total_time + if self.start_time: + current_time = monotonic() if self.monotonic else time.time() + elapsed_time += current_time - self.start_time + return elapsed_time + + @property + def rounded(self): + """Human readable timespan rounded to seconds (a string).""" + return format_timespan(round(self.elapsed_time)) + + def __str__(self): + """Show the elapsed time since the :class:`Timer` was created.""" + return format_timespan(self.elapsed_time) + + +class InvalidDate(Exception): + + """ + Raised when a string cannot be parsed into a date. + + For example: + + >>> from humanfriendly import parse_date + >>> parse_date('2013-06-XY') + Traceback (most recent call last): + File "humanfriendly.py", line 206, in parse_date + raise InvalidDate(format(msg, datestring)) + humanfriendly.InvalidDate: Invalid date! (expected 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' but got: '2013-06-XY') + """ + + +class InvalidSize(Exception): + + """ + Raised when a string cannot be parsed into a file size. + + For example: + + >>> from humanfriendly import parse_size + >>> parse_size('5 Z') + Traceback (most recent call last): + File "humanfriendly/__init__.py", line 267, in parse_size + raise InvalidSize(format(msg, size, tokens)) + humanfriendly.InvalidSize: Failed to parse size! (input '5 Z' was tokenized as [5, 'Z']) + """ + + +class InvalidLength(Exception): + + """ + Raised when a string cannot be parsed into a length. + + For example: + + >>> from humanfriendly import parse_length + >>> parse_length('5 Z') + Traceback (most recent call last): + File "humanfriendly/__init__.py", line 267, in parse_length + raise InvalidLength(format(msg, length, tokens)) + humanfriendly.InvalidLength: Failed to parse length! (input '5 Z' was tokenized as [5, 'Z']) + """ + + +class InvalidTimespan(Exception): + + """ + Raised when a string cannot be parsed into a timespan. + + For example: + + >>> from humanfriendly import parse_timespan + >>> parse_timespan('1 age') + Traceback (most recent call last): + File "humanfriendly/__init__.py", line 419, in parse_timespan + raise InvalidTimespan(format(msg, timespan, tokens)) + humanfriendly.InvalidTimespan: Failed to parse timespan! (input '1 age' was tokenized as [1, 'age']) + """ + + +# Define aliases for backwards compatibility. +define_aliases( + module_name=__name__, + # In humanfriendly 1.23 the format_table() function was added to render a + # table using characters like dashes and vertical bars to emulate borders. + # Since then support for other tables has been added and the name of + # format_table() has changed. + format_table='humanfriendly.tables.format_pretty_table', + # In humanfriendly 1.30 the following text manipulation functions were + # moved out into a separate module to enable their usage in other modules + # of the humanfriendly package (without causing circular imports). + compact='humanfriendly.text.compact', + concatenate='humanfriendly.text.concatenate', + dedent='humanfriendly.text.dedent', + format='humanfriendly.text.format', + is_empty_line='humanfriendly.text.is_empty_line', + pluralize='humanfriendly.text.pluralize', + tokenize='humanfriendly.text.tokenize', + trim_empty_lines='humanfriendly.text.trim_empty_lines', + # In humanfriendly 1.38 the prompt_for_choice() function was moved out into a + # separate module because several variants of interactive prompts were added. + prompt_for_choice='humanfriendly.prompts.prompt_for_choice', + # In humanfriendly 8.0 the Spinner class and minimum_spinner_interval + # variable were extracted to a new module and the erase_line_code, + # hide_cursor_code and show_cursor_code variables were moved. + AutomaticSpinner='humanfriendly.terminal.spinners.AutomaticSpinner', + Spinner='humanfriendly.terminal.spinners.Spinner', + erase_line_code='humanfriendly.terminal.ANSI_ERASE_LINE', + hide_cursor_code='humanfriendly.terminal.ANSI_SHOW_CURSOR', + minimum_spinner_interval='humanfriendly.terminal.spinners.MINIMUM_INTERVAL', + show_cursor_code='humanfriendly.terminal.ANSI_HIDE_CURSOR', +) diff --git a/python_embeded/Lib/site-packages/humanfriendly/tests.py b/python_embeded/Lib/site-packages/humanfriendly/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..72dad996b9f4623efbcd5161c160ebaf61c6fa4d --- /dev/null +++ b/python_embeded/Lib/site-packages/humanfriendly/tests.py @@ -0,0 +1,1495 @@ +#!/usr/bin/env python +# vim: fileencoding=utf-8 : + +# Tests for the `humanfriendly' package. +# +# Author: Peter Odding +# Last Change: June 11, 2021 +# URL: https://humanfriendly.readthedocs.io + +"""Test suite for the `humanfriendly` package.""" + +# Standard library modules. +import datetime +import math +import os +import random +import re +import subprocess +import sys +import time +import types +import unittest +import warnings + +# Modules included in our package. +from humanfriendly import ( + InvalidDate, + InvalidLength, + InvalidSize, + InvalidTimespan, + Timer, + coerce_boolean, + coerce_pattern, + format_length, + format_number, + format_path, + format_size, + format_timespan, + parse_date, + parse_length, + parse_path, + parse_size, + parse_timespan, + prompts, + round_number, +) +from humanfriendly.case import CaseInsensitiveDict, CaseInsensitiveKey +from humanfriendly.cli import main +from humanfriendly.compat import StringIO +from humanfriendly.decorators import cached +from humanfriendly.deprecation import DeprecationProxy, define_aliases, deprecated_args, get_aliases +from humanfriendly.prompts import ( + TooManyInvalidReplies, + prompt_for_confirmation, + prompt_for_choice, + prompt_for_input, +) +from humanfriendly.sphinx import ( + deprecation_note_callback, + man_role, + pypi_role, + setup, + special_methods_callback, + usage_message_callback, +) +from humanfriendly.tables import ( + format_pretty_table, + format_robust_table, + format_rst_table, + format_smart_table, +) +from humanfriendly.terminal import ( + ANSI_CSI, + ANSI_ERASE_LINE, + ANSI_HIDE_CURSOR, + ANSI_RESET, + ANSI_SGR, + ANSI_SHOW_CURSOR, + ansi_strip, + ansi_style, + ansi_width, + ansi_wrap, + clean_terminal_output, + connected_to_terminal, + find_terminal_size, + get_pager_command, + message, + output, + show_pager, + terminal_supports_colors, + warning, +) +from humanfriendly.terminal.html import html_to_ansi +from humanfriendly.terminal.spinners import AutomaticSpinner, Spinner +from humanfriendly.testing import ( + CallableTimedOut, + CaptureOutput, + MockedProgram, + PatchedAttribute, + PatchedItem, + TemporaryDirectory, + TestCase, + retry, + run_cli, + skip_on_raise, + touch, +) +from humanfriendly.text import ( + compact, + compact_empty_lines, + concatenate, + dedent, + generate_slug, + pluralize, + random_string, + trim_empty_lines, +) +from humanfriendly.usage import ( + find_meta_variables, + format_usage, + parse_usage, + render_usage, +) + +# Test dependencies. +from mock import MagicMock + + +class HumanFriendlyTestCase(TestCase): + + """Container for the `humanfriendly` test suite.""" + + def test_case_insensitive_dict(self): + """Test the CaseInsensitiveDict class.""" + # Test support for the dict(iterable) signature. + assert len(CaseInsensitiveDict([('key', True), ('KEY', False)])) == 1 + # Test support for the dict(iterable, **kw) signature. + assert len(CaseInsensitiveDict([('one', True), ('ONE', False)], one=False, two=True)) == 2 + # Test support for the dict(mapping) signature. + assert len(CaseInsensitiveDict(dict(key=True, KEY=False))) == 1 + # Test support for the dict(mapping, **kw) signature. + assert len(CaseInsensitiveDict(dict(one=True, ONE=False), one=False, two=True)) == 2 + # Test support for the dict(**kw) signature. + assert len(CaseInsensitiveDict(one=True, ONE=False, two=True)) == 2 + # Test support for dict.fromkeys(). + obj = CaseInsensitiveDict.fromkeys(["One", "one", "ONE", "Two", "two", "TWO"]) + assert len(obj) == 2 + # Test support for dict.get(). + obj = CaseInsensitiveDict(existing_key=42) + assert obj.get('Existing_Key') == 42 + # Test support for dict.pop(). + obj = CaseInsensitiveDict(existing_key=42) + assert obj.pop('Existing_Key') == 42 + assert len(obj) == 0 + # Test support for dict.setdefault(). + obj = CaseInsensitiveDict(existing_key=42) + assert obj.setdefault('Existing_Key') == 42 + obj.setdefault('other_key', 11) + assert obj['Other_Key'] == 11 + # Test support for dict.__contains__(). + obj = CaseInsensitiveDict(existing_key=42) + assert 'Existing_Key' in obj + # Test support for dict.__delitem__(). + obj = CaseInsensitiveDict(existing_key=42) + del obj['Existing_Key'] + assert len(obj) == 0 + # Test support for dict.__getitem__(). + obj = CaseInsensitiveDict(existing_key=42) + assert obj['Existing_Key'] == 42 + # Test support for dict.__setitem__(). + obj = CaseInsensitiveDict(existing_key=42) + obj['Existing_Key'] = 11 + assert obj['existing_key'] == 11 + + def test_case_insensitive_key(self): + """Test the CaseInsensitiveKey class.""" + # Test the __eq__() special method. + polite = CaseInsensitiveKey("Please don't shout") + rude = CaseInsensitiveKey("PLEASE DON'T SHOUT") + assert polite == rude + # Test the __hash__() special method. + mapping = {} + mapping[polite] = 1 + mapping[rude] = 2 + assert len(mapping) == 1 + + def test_capture_output(self): + """Test the CaptureOutput class.""" + with CaptureOutput() as capturer: + sys.stdout.write("Something for stdout.\n") + sys.stderr.write("And for stderr.\n") + assert capturer.stdout.get_lines() == ["Something for stdout."] + assert capturer.stderr.get_lines() == ["And for stderr."] + + def test_skip_on_raise(self): + """Test the skip_on_raise() decorator.""" + def test_fn(): + raise NotImplementedError() + decorator_fn = skip_on_raise(NotImplementedError) + decorated_fn = decorator_fn(test_fn) + self.assertRaises(NotImplementedError, test_fn) + self.assertRaises(unittest.SkipTest, decorated_fn) + + def test_retry_raise(self): + """Test :func:`~humanfriendly.testing.retry()` based on assertion errors.""" + # Define a helper function that will raise an assertion error on the + # first call and return a string on the second call. + def success_helper(): + if not hasattr(success_helper, 'was_called'): + setattr(success_helper, 'was_called', True) + assert False + else: + return 'yes' + assert retry(success_helper) == 'yes' + + # Define a helper function that always raises an assertion error. + def failure_helper(): + assert False + with self.assertRaises(AssertionError): + retry(failure_helper, timeout=1) + + def test_retry_return(self): + """Test :func:`~humanfriendly.testing.retry()` based on return values.""" + # Define a helper function that will return False on the first call and + # return a number on the second call. + def success_helper(): + if not hasattr(success_helper, 'was_called'): + # On the first call we return False. + setattr(success_helper, 'was_called', True) + return False + else: + # On the second call we return a number. + return 42 + assert retry(success_helper) == 42 + with self.assertRaises(CallableTimedOut): + retry(lambda: False, timeout=1) + + def test_mocked_program(self): + """Test :class:`humanfriendly.testing.MockedProgram`.""" + name = random_string() + script = dedent(''' + # This goes to stdout. + tr a-z A-Z + # This goes to stderr. + echo Fake warning >&2 + ''') + with MockedProgram(name=name, returncode=42, script=script) as directory: + assert os.path.isdir(directory) + assert os.path.isfile(os.path.join(directory, name)) + program = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = program.communicate(input=b'hello world\n') + assert program.returncode == 42 + assert stdout == b'HELLO WORLD\n' + assert stderr == b'Fake warning\n' + + def test_temporary_directory(self): + """Test :class:`humanfriendly.testing.TemporaryDirectory`.""" + with TemporaryDirectory() as directory: + assert os.path.isdir(directory) + temporary_file = os.path.join(directory, 'some-file') + with open(temporary_file, 'w') as handle: + handle.write("Hello world!") + assert not os.path.exists(temporary_file) + assert not os.path.exists(directory) + + def test_touch(self): + """Test :func:`humanfriendly.testing.touch()`.""" + with TemporaryDirectory() as directory: + # Create a file in the temporary directory. + filename = os.path.join(directory, random_string()) + assert not os.path.isfile(filename) + touch(filename) + assert os.path.isfile(filename) + # Create a file in a subdirectory. + filename = os.path.join(directory, random_string(), random_string()) + assert not os.path.isfile(filename) + touch(filename) + assert os.path.isfile(filename) + + def test_patch_attribute(self): + """Test :class:`humanfriendly.testing.PatchedAttribute`.""" + class Subject(object): + my_attribute = 42 + instance = Subject() + assert instance.my_attribute == 42 + with PatchedAttribute(instance, 'my_attribute', 13) as return_value: + assert return_value is instance + assert instance.my_attribute == 13 + assert instance.my_attribute == 42 + + def test_patch_item(self): + """Test :class:`humanfriendly.testing.PatchedItem`.""" + instance = dict(my_item=True) + assert instance['my_item'] is True + with PatchedItem(instance, 'my_item', False) as return_value: + assert return_value is instance + assert instance['my_item'] is False + assert instance['my_item'] is True + + def test_run_cli_intercepts_exit(self): + """Test that run_cli() intercepts SystemExit.""" + returncode, output = run_cli(lambda: sys.exit(42)) + self.assertEqual(returncode, 42) + + def test_run_cli_intercepts_error(self): + """Test that run_cli() intercepts exceptions.""" + returncode, output = run_cli(self.run_cli_raise_other) + self.assertEqual(returncode, 1) + + def run_cli_raise_other(self): + """run_cli() sample that raises an exception.""" + raise ValueError() + + def test_run_cli_intercepts_output(self): + """Test that run_cli() intercepts output.""" + expected_output = random_string() + "\n" + returncode, output = run_cli(lambda: sys.stdout.write(expected_output)) + self.assertEqual(returncode, 0) + self.assertEqual(output, expected_output) + + def test_caching_decorator(self): + """Test the caching decorator.""" + # Confirm that the caching decorator works. + a = cached(lambda: random.random()) + b = cached(lambda: random.random()) + assert a() == a() + assert b() == b() + # Confirm that functions have their own cache. + assert a() != b() + + def test_compact(self): + """Test :func:`humanfriendly.text.compact()`.""" + assert compact(' a \n\n b ') == 'a b' + assert compact(''' + %s template notation + ''', 'Simple') == 'Simple template notation' + assert compact(''' + More {type} template notation + ''', type='readable') == 'More readable template notation' + + def test_compact_empty_lines(self): + """Test :func:`humanfriendly.text.compact_empty_lines()`.""" + # Simple strings pass through untouched. + assert compact_empty_lines('foo') == 'foo' + # Horizontal whitespace remains untouched. + assert compact_empty_lines('\tfoo') == '\tfoo' + # Line breaks should be preserved. + assert compact_empty_lines('foo\nbar') == 'foo\nbar' + # Vertical whitespace should be preserved. + assert compact_empty_lines('foo\n\nbar') == 'foo\n\nbar' + # Vertical whitespace should be compressed. + assert compact_empty_lines('foo\n\n\nbar') == 'foo\n\nbar' + assert compact_empty_lines('foo\n\n\n\nbar') == 'foo\n\nbar' + assert compact_empty_lines('foo\n\n\n\n\nbar') == 'foo\n\nbar' + + def test_dedent(self): + """Test :func:`humanfriendly.text.dedent()`.""" + assert dedent('\n line 1\n line 2\n\n') == 'line 1\n line 2\n' + assert dedent(''' + Dedented, %s text + ''', 'interpolated') == 'Dedented, interpolated text\n' + assert dedent(''' + Dedented, {op} text + ''', op='formatted') == 'Dedented, formatted text\n' + + def test_pluralization(self): + """Test :func:`humanfriendly.text.pluralize()`.""" + assert pluralize(1, 'word') == '1 word' + assert pluralize(2, 'word') == '2 words' + assert pluralize(1, 'box', 'boxes') == '1 box' + assert pluralize(2, 'box', 'boxes') == '2 boxes' + + def test_generate_slug(self): + """Test :func:`humanfriendly.text.generate_slug()`.""" + # Test the basic functionality. + self.assertEqual('some-random-text', generate_slug('Some Random Text!')) + # Test that previous output doesn't change. + self.assertEqual('some-random-text', generate_slug('some-random-text')) + # Test that inputs which can't be converted to a slug raise an exception. + with self.assertRaises(ValueError): + generate_slug(' ') + with self.assertRaises(ValueError): + generate_slug('-') + + def test_boolean_coercion(self): + """Test :func:`humanfriendly.coerce_boolean()`.""" + for value in [True, 'TRUE', 'True', 'true', 'on', 'yes', '1']: + self.assertEqual(True, coerce_boolean(value)) + for value in [False, 'FALSE', 'False', 'false', 'off', 'no', '0']: + self.assertEqual(False, coerce_boolean(value)) + with self.assertRaises(ValueError): + coerce_boolean('not a boolean') + + def test_pattern_coercion(self): + """Test :func:`humanfriendly.coerce_pattern()`.""" + empty_pattern = re.compile('') + # Make sure strings are converted to compiled regular expressions. + assert isinstance(coerce_pattern('foobar'), type(empty_pattern)) + # Make sure compiled regular expressions pass through untouched. + assert empty_pattern is coerce_pattern(empty_pattern) + # Make sure flags are respected. + pattern = coerce_pattern('foobar', re.IGNORECASE) + assert pattern.match('FOOBAR') + # Make sure invalid values raise the expected exception. + with self.assertRaises(ValueError): + coerce_pattern([]) + + def test_format_timespan(self): + """Test :func:`humanfriendly.format_timespan()`.""" + minute = 60 + hour = minute * 60 + day = hour * 24 + week = day * 7 + year = week * 52 + assert '1 nanosecond' == format_timespan(0.000000001, detailed=True) + assert '500 nanoseconds' == format_timespan(0.0000005, detailed=True) + assert '1 microsecond' == format_timespan(0.000001, detailed=True) + assert '500 microseconds' == format_timespan(0.0005, detailed=True) + assert '1 millisecond' == format_timespan(0.001, detailed=True) + assert '500 milliseconds' == format_timespan(0.5, detailed=True) + assert '0.5 seconds' == format_timespan(0.5, detailed=False) + assert '0 seconds' == format_timespan(0) + assert '0.54 seconds' == format_timespan(0.54321) + assert '1 second' == format_timespan(1) + assert '3.14 seconds' == format_timespan(math.pi) + assert '1 minute' == format_timespan(minute) + assert '1 minute and 20 seconds' == format_timespan(80) + assert '2 minutes' == format_timespan(minute * 2) + assert '1 hour' == format_timespan(hour) + assert '2 hours' == format_timespan(hour * 2) + assert '1 day' == format_timespan(day) + assert '2 days' == format_timespan(day * 2) + assert '1 week' == format_timespan(week) + assert '2 weeks' == format_timespan(week * 2) + assert '1 year' == format_timespan(year) + assert '2 years' == format_timespan(year * 2) + assert '6 years, 5 weeks, 4 days, 3 hours, 2 minutes and 500 milliseconds' == \ + format_timespan(year * 6 + week * 5 + day * 4 + hour * 3 + minute * 2 + 0.5, detailed=True) + assert '1 year, 2 weeks and 3 days' == \ + format_timespan(year + week * 2 + day * 3 + hour * 12) + # Make sure milliseconds are never shown separately when detailed=False. + # https://github.com/xolox/python-humanfriendly/issues/10 + assert '1 minute, 1 second and 100 milliseconds' == format_timespan(61.10, detailed=True) + assert '1 minute and 1.1 seconds' == format_timespan(61.10, detailed=False) + # Test for loss of precision as reported in issue 11: + # https://github.com/xolox/python-humanfriendly/issues/11 + assert '1 minute and 0.3 seconds' == format_timespan(60.300) + assert '5 minutes and 0.3 seconds' == format_timespan(300.300) + assert '1 second and 15 milliseconds' == format_timespan(1.015, detailed=True) + assert '10 seconds and 15 milliseconds' == format_timespan(10.015, detailed=True) + assert '1 microsecond and 50 nanoseconds' == format_timespan(0.00000105, detailed=True) + # Test the datetime.timedelta support: + # https://github.com/xolox/python-humanfriendly/issues/27 + now = datetime.datetime.now() + then = now - datetime.timedelta(hours=23) + assert '23 hours' == format_timespan(now - then) + + def test_parse_timespan(self): + """Test :func:`humanfriendly.parse_timespan()`.""" + self.assertEqual(0, parse_timespan('0')) + self.assertEqual(0, parse_timespan('0s')) + self.assertEqual(0.000000001, parse_timespan('1ns')) + self.assertEqual(0.000000051, parse_timespan('51ns')) + self.assertEqual(0.000001, parse_timespan('1us')) + self.assertEqual(0.000052, parse_timespan('52us')) + self.assertEqual(0.001, parse_timespan('1ms')) + self.assertEqual(0.001, parse_timespan('1 millisecond')) + self.assertEqual(0.5, parse_timespan('500 milliseconds')) + self.assertEqual(0.5, parse_timespan('0.5 seconds')) + self.assertEqual(5, parse_timespan('5s')) + self.assertEqual(5, parse_timespan('5 seconds')) + self.assertEqual(60 * 2, parse_timespan('2m')) + self.assertEqual(60 * 2, parse_timespan('2 minutes')) + self.assertEqual(60 * 3, parse_timespan('3 min')) + self.assertEqual(60 * 3, parse_timespan('3 mins')) + self.assertEqual(60 * 60 * 3, parse_timespan('3 h')) + self.assertEqual(60 * 60 * 3, parse_timespan('3 hours')) + self.assertEqual(60 * 60 * 24 * 4, parse_timespan('4d')) + self.assertEqual(60 * 60 * 24 * 4, parse_timespan('4 days')) + self.assertEqual(60 * 60 * 24 * 7 * 5, parse_timespan('5 w')) + self.assertEqual(60 * 60 * 24 * 7 * 5, parse_timespan('5 weeks')) + with self.assertRaises(InvalidTimespan): + parse_timespan('1z') + + def test_parse_date(self): + """Test :func:`humanfriendly.parse_date()`.""" + self.assertEqual((2013, 6, 17, 0, 0, 0), parse_date('2013-06-17')) + self.assertEqual((2013, 6, 17, 2, 47, 42), parse_date('2013-06-17 02:47:42')) + self.assertEqual((2016, 11, 30, 0, 47, 17), parse_date(u'2016-11-30 00:47:17')) + with self.assertRaises(InvalidDate): + parse_date('2013-06-XY') + + def test_format_size(self): + """Test :func:`humanfriendly.format_size()`.""" + self.assertEqual('0 bytes', format_size(0)) + self.assertEqual('1 byte', format_size(1)) + self.assertEqual('42 bytes', format_size(42)) + self.assertEqual('1 KB', format_size(1000 ** 1)) + self.assertEqual('1 MB', format_size(1000 ** 2)) + self.assertEqual('1 GB', format_size(1000 ** 3)) + self.assertEqual('1 TB', format_size(1000 ** 4)) + self.assertEqual('1 PB', format_size(1000 ** 5)) + self.assertEqual('1 EB', format_size(1000 ** 6)) + self.assertEqual('1 ZB', format_size(1000 ** 7)) + self.assertEqual('1 YB', format_size(1000 ** 8)) + self.assertEqual('1 KiB', format_size(1024 ** 1, binary=True)) + self.assertEqual('1 MiB', format_size(1024 ** 2, binary=True)) + self.assertEqual('1 GiB', format_size(1024 ** 3, binary=True)) + self.assertEqual('1 TiB', format_size(1024 ** 4, binary=True)) + self.assertEqual('1 PiB', format_size(1024 ** 5, binary=True)) + self.assertEqual('1 EiB', format_size(1024 ** 6, binary=True)) + self.assertEqual('1 ZiB', format_size(1024 ** 7, binary=True)) + self.assertEqual('1 YiB', format_size(1024 ** 8, binary=True)) + self.assertEqual('45 KB', format_size(1000 * 45)) + self.assertEqual('2.9 TB', format_size(1000 ** 4 * 2.9)) + + def test_parse_size(self): + """Test :func:`humanfriendly.parse_size()`.""" + self.assertEqual(0, parse_size('0B')) + self.assertEqual(42, parse_size('42')) + self.assertEqual(42, parse_size('42B')) + self.assertEqual(1000, parse_size('1k')) + self.assertEqual(1024, parse_size('1k', binary=True)) + self.assertEqual(1000, parse_size('1 KB')) + self.assertEqual(1000, parse_size('1 kilobyte')) + self.assertEqual(1024, parse_size('1 kilobyte', binary=True)) + self.assertEqual(1000 ** 2 * 69, parse_size('69 MB')) + self.assertEqual(1000 ** 3, parse_size('1 GB')) + self.assertEqual(1000 ** 4, parse_size('1 TB')) + self.assertEqual(1000 ** 5, parse_size('1 PB')) + self.assertEqual(1000 ** 6, parse_size('1 EB')) + self.assertEqual(1000 ** 7, parse_size('1 ZB')) + self.assertEqual(1000 ** 8, parse_size('1 YB')) + self.assertEqual(1000 ** 3 * 1.5, parse_size('1.5 GB')) + self.assertEqual(1024 ** 8 * 1.5, parse_size('1.5 YiB')) + with self.assertRaises(InvalidSize): + parse_size('1q') + with self.assertRaises(InvalidSize): + parse_size('a') + + def test_format_length(self): + """Test :func:`humanfriendly.format_length()`.""" + self.assertEqual('0 metres', format_length(0)) + self.assertEqual('1 metre', format_length(1)) + self.assertEqual('42 metres', format_length(42)) + self.assertEqual('1 km', format_length(1 * 1000)) + self.assertEqual('15.3 cm', format_length(0.153)) + self.assertEqual('1 cm', format_length(1e-02)) + self.assertEqual('1 mm', format_length(1e-03)) + self.assertEqual('1 nm', format_length(1e-09)) + + def test_parse_length(self): + """Test :func:`humanfriendly.parse_length()`.""" + self.assertEqual(0, parse_length('0m')) + self.assertEqual(42, parse_length('42')) + self.assertEqual(1.5, parse_length('1.5')) + self.assertEqual(42, parse_length('42m')) + self.assertEqual(1000, parse_length('1km')) + self.assertEqual(0.153, parse_length('15.3 cm')) + self.assertEqual(1e-02, parse_length('1cm')) + self.assertEqual(1e-03, parse_length('1mm')) + self.assertEqual(1e-09, parse_length('1nm')) + with self.assertRaises(InvalidLength): + parse_length('1z') + with self.assertRaises(InvalidLength): + parse_length('a') + + def test_format_number(self): + """Test :func:`humanfriendly.format_number()`.""" + self.assertEqual('1', format_number(1)) + self.assertEqual('1.5', format_number(1.5)) + self.assertEqual('1.56', format_number(1.56789)) + self.assertEqual('1.567', format_number(1.56789, 3)) + self.assertEqual('1,000', format_number(1000)) + self.assertEqual('1,000', format_number(1000.12, 0)) + self.assertEqual('1,000,000', format_number(1000000)) + self.assertEqual('1,000,000.42', format_number(1000000.42)) + # Regression test for https://github.com/xolox/python-humanfriendly/issues/40. + self.assertEqual('-285.67', format_number(-285.67)) + + def test_round_number(self): + """Test :func:`humanfriendly.round_number()`.""" + self.assertEqual('1', round_number(1)) + self.assertEqual('1', round_number(1.0)) + self.assertEqual('1.00', round_number(1, keep_width=True)) + self.assertEqual('3.14', round_number(3.141592653589793)) + + def test_format_path(self): + """Test :func:`humanfriendly.format_path()`.""" + friendly_path = os.path.join('~', '.vimrc') + absolute_path = os.path.join(os.environ['HOME'], '.vimrc') + self.assertEqual(friendly_path, format_path(absolute_path)) + + def test_parse_path(self): + """Test :func:`humanfriendly.parse_path()`.""" + friendly_path = os.path.join('~', '.vimrc') + absolute_path = os.path.join(os.environ['HOME'], '.vimrc') + self.assertEqual(absolute_path, parse_path(friendly_path)) + + def test_pretty_tables(self): + """Test :func:`humanfriendly.tables.format_pretty_table()`.""" + # The simplest case possible :-). + data = [['Just one column']] + assert format_pretty_table(data) == dedent(""" + ------------------- + | Just one column | + ------------------- + """).strip() + # A bit more complex: two rows, three columns, varying widths. + data = [['One', 'Two', 'Three'], ['1', '2', '3']] + assert format_pretty_table(data) == dedent(""" + --------------------- + | One | Two | Three | + | 1 | 2 | 3 | + --------------------- + """).strip() + # A table including column names. + column_names = ['One', 'Two', 'Three'] + data = [['1', '2', '3'], ['a', 'b', 'c']] + assert ansi_strip(format_pretty_table(data, column_names)) == dedent(""" + --------------------- + | One | Two | Three | + --------------------- + | 1 | 2 | 3 | + | a | b | c | + --------------------- + """).strip() + # A table that contains a column with only numeric data (will be right aligned). + column_names = ['Just a label', 'Important numbers'] + data = [['Row one', '15'], ['Row two', '300']] + assert ansi_strip(format_pretty_table(data, column_names)) == dedent(""" + ------------------------------------ + | Just a label | Important numbers | + ------------------------------------ + | Row one | 15 | + | Row two | 300 | + ------------------------------------ + """).strip() + + def test_robust_tables(self): + """Test :func:`humanfriendly.tables.format_robust_table()`.""" + column_names = ['One', 'Two', 'Three'] + data = [['1', '2', '3'], ['a', 'b', 'c']] + assert ansi_strip(format_robust_table(data, column_names)) == dedent(""" + -------- + One: 1 + Two: 2 + Three: 3 + -------- + One: a + Two: b + Three: c + -------- + """).strip() + column_names = ['One', 'Two', 'Three'] + data = [['1', '2', '3'], ['a', 'b', 'Here comes a\nmulti line column!']] + assert ansi_strip(format_robust_table(data, column_names)) == dedent(""" + ------------------ + One: 1 + Two: 2 + Three: 3 + ------------------ + One: a + Two: b + Three: + Here comes a + multi line column! + ------------------ + """).strip() + + def test_smart_tables(self): + """Test :func:`humanfriendly.tables.format_smart_table()`.""" + column_names = ['One', 'Two', 'Three'] + data = [['1', '2', '3'], ['a', 'b', 'c']] + assert ansi_strip(format_smart_table(data, column_names)) == dedent(""" + --------------------- + | One | Two | Three | + --------------------- + | 1 | 2 | 3 | + | a | b | c | + --------------------- + """).strip() + column_names = ['One', 'Two', 'Three'] + data = [['1', '2', '3'], ['a', 'b', 'Here comes a\nmulti line column!']] + assert ansi_strip(format_smart_table(data, column_names)) == dedent(""" + ------------------ + One: 1 + Two: 2 + Three: 3 + ------------------ + One: a + Two: b + Three: + Here comes a + multi line column! + ------------------ + """).strip() + + def test_rst_tables(self): + """Test :func:`humanfriendly.tables.format_rst_table()`.""" + # Generate a table with column names. + column_names = ['One', 'Two', 'Three'] + data = [['1', '2', '3'], ['a', 'b', 'c']] + self.assertEqual( + format_rst_table(data, column_names), + dedent(""" + === === ===== + One Two Three + === === ===== + 1 2 3 + a b c + === === ===== + """).rstrip(), + ) + # Generate a table without column names. + data = [['1', '2', '3'], ['a', 'b', 'c']] + self.assertEqual( + format_rst_table(data), + dedent(""" + = = = + 1 2 3 + a b c + = = = + """).rstrip(), + ) + + def test_concatenate(self): + """Test :func:`humanfriendly.text.concatenate()`.""" + assert concatenate([]) == '' + assert concatenate(['one']) == 'one' + assert concatenate(['one', 'two']) == 'one and two' + assert concatenate(['one', 'two', 'three']) == 'one, two and three' + # Test the 'conjunction' option. + assert concatenate(['one', 'two', 'three'], conjunction='or') == 'one, two or three' + # Test the 'serial_comma' option. + assert concatenate(['one', 'two', 'three'], serial_comma=True) == 'one, two, and three' + + def test_split(self): + """Test :func:`humanfriendly.text.split()`.""" + from humanfriendly.text import split + self.assertEqual(split(''), []) + self.assertEqual(split('foo'), ['foo']) + self.assertEqual(split('foo, bar'), ['foo', 'bar']) + self.assertEqual(split('foo, bar, baz'), ['foo', 'bar', 'baz']) + self.assertEqual(split('foo,bar,baz'), ['foo', 'bar', 'baz']) + + def test_timer(self): + """Test :func:`humanfriendly.Timer`.""" + for seconds, text in ((1, '1 second'), + (2, '2 seconds'), + (60, '1 minute'), + (60 * 2, '2 minutes'), + (60 * 60, '1 hour'), + (60 * 60 * 2, '2 hours'), + (60 * 60 * 24, '1 day'), + (60 * 60 * 24 * 2, '2 days'), + (60 * 60 * 24 * 7, '1 week'), + (60 * 60 * 24 * 7 * 2, '2 weeks')): + t = Timer(time.time() - seconds) + self.assertEqual(round_number(t.elapsed_time, keep_width=True), '%i.00' % seconds) + self.assertEqual(str(t), text) + # Test rounding to seconds. + t = Timer(time.time() - 2.2) + self.assertEqual(t.rounded, '2 seconds') + # Test automatic timer. + automatic_timer = Timer() + time.sleep(1) + # XXX The following normalize_timestamp(ndigits=0) calls are intended + # to compensate for unreliable clock sources in virtual machines + # like those encountered on Travis CI, see also: + # https://travis-ci.org/xolox/python-humanfriendly/jobs/323944263 + self.assertEqual(normalize_timestamp(automatic_timer.elapsed_time, 0), '1.00') + # Test resumable timer. + resumable_timer = Timer(resumable=True) + for i in range(2): + with resumable_timer: + time.sleep(1) + self.assertEqual(normalize_timestamp(resumable_timer.elapsed_time, 0), '2.00') + # Make sure Timer.__enter__() returns the timer object. + with Timer(resumable=True) as timer: + assert timer is not None + + def test_spinner(self): + """Test :func:`humanfriendly.Spinner`.""" + stream = StringIO() + spinner = Spinner(label='test spinner', total=4, stream=stream, interactive=True) + for progress in [1, 2, 3, 4]: + spinner.step(progress=progress) + time.sleep(0.2) + spinner.clear() + output = stream.getvalue() + output = (output.replace(ANSI_SHOW_CURSOR, '') + .replace(ANSI_HIDE_CURSOR, '')) + lines = [line for line in output.split(ANSI_ERASE_LINE) if line] + self.assertTrue(len(lines) > 0) + self.assertTrue(all('test spinner' in line for line in lines)) + self.assertTrue(all('%' in line for line in lines)) + self.assertEqual(sorted(set(lines)), sorted(lines)) + + def test_automatic_spinner(self): + """ + Test :func:`humanfriendly.AutomaticSpinner`. + + There's not a lot to test about the :class:`.AutomaticSpinner` class, + but by at least running it here we are assured that the code functions + on all supported Python versions. :class:`.AutomaticSpinner` is built + on top of the :class:`.Spinner` class so at least we also have the + tests for the :class:`.Spinner` class to back us up. + """ + with AutomaticSpinner(label='test spinner'): + time.sleep(1) + + def test_prompt_for_choice(self): + """Test :func:`humanfriendly.prompts.prompt_for_choice()`.""" + # Choice selection without any options should raise an exception. + with self.assertRaises(ValueError): + prompt_for_choice([]) + # If there's only one option no prompt should be rendered so we expect + # the following code to not raise an EOFError exception (despite + # connecting standard input to /dev/null). + with open(os.devnull) as handle: + with PatchedAttribute(sys, 'stdin', handle): + only_option = 'only one option (shortcut)' + assert prompt_for_choice([only_option]) == only_option + # Choice selection by full string match. + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: 'foo'): + assert prompt_for_choice(['foo', 'bar']) == 'foo' + # Choice selection by substring input. + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: 'f'): + assert prompt_for_choice(['foo', 'bar']) == 'foo' + # Choice selection by number. + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: '2'): + assert prompt_for_choice(['foo', 'bar']) == 'bar' + # Choice selection by going with the default. + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: ''): + assert prompt_for_choice(['foo', 'bar'], default='bar') == 'bar' + # Invalid substrings are refused. + replies = ['', 'q', 'z'] + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: replies.pop(0)): + assert prompt_for_choice(['foo', 'bar', 'baz']) == 'baz' + # Choice selection by substring input requires an unambiguous substring match. + replies = ['a', 'q'] + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: replies.pop(0)): + assert prompt_for_choice(['foo', 'bar', 'baz', 'qux']) == 'qux' + # Invalid numbers are refused. + replies = ['42', '2'] + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: replies.pop(0)): + assert prompt_for_choice(['foo', 'bar', 'baz']) == 'bar' + # Test that interactive prompts eventually give up on invalid replies. + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: ''): + with self.assertRaises(TooManyInvalidReplies): + prompt_for_choice(['a', 'b', 'c']) + + def test_prompt_for_confirmation(self): + """Test :func:`humanfriendly.prompts.prompt_for_confirmation()`.""" + # Test some (more or less) reasonable replies that indicate agreement. + for reply in 'yes', 'Yes', 'YES', 'y', 'Y': + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: reply): + assert prompt_for_confirmation("Are you sure?") is True + # Test some (more or less) reasonable replies that indicate disagreement. + for reply in 'no', 'No', 'NO', 'n', 'N': + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: reply): + assert prompt_for_confirmation("Are you sure?") is False + # Test that empty replies select the default choice. + for default_choice in True, False: + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: ''): + assert prompt_for_confirmation("Are you sure?", default=default_choice) is default_choice + # Test that a warning is shown when no input nor a default is given. + replies = ['', 'y'] + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: replies.pop(0)): + with CaptureOutput(merged=True) as capturer: + assert prompt_for_confirmation("Are you sure?") is True + assert "there's no default choice" in capturer.get_text() + # Test that the default reply is shown in uppercase. + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: 'y'): + for default_value, expected_text in (True, 'Y/n'), (False, 'y/N'), (None, 'y/n'): + with CaptureOutput(merged=True) as capturer: + assert prompt_for_confirmation("Are you sure?", default=default_value) is True + assert expected_text in capturer.get_text() + # Test that interactive prompts eventually give up on invalid replies. + with PatchedAttribute(prompts, 'interactive_prompt', lambda p: ''): + with self.assertRaises(TooManyInvalidReplies): + prompt_for_confirmation("Are you sure?") + + def test_prompt_for_input(self): + """Test :func:`humanfriendly.prompts.prompt_for_input()`.""" + with open(os.devnull) as handle: + with PatchedAttribute(sys, 'stdin', handle): + # If standard input isn't connected to a terminal the default value should be returned. + default_value = "To seek the holy grail!" + assert prompt_for_input("What is your quest?", default=default_value) == default_value + # If standard input isn't connected to a terminal and no default value + # is given the EOFError exception should be propagated to the caller. + with self.assertRaises(EOFError): + prompt_for_input("What is your favorite color?") + + def test_cli(self): + """Test the command line interface.""" + # Test that the usage message is printed by default. + returncode, output = run_cli(main) + assert 'Usage:' in output + # Test that the usage message can be requested explicitly. + returncode, output = run_cli(main, '--help') + assert 'Usage:' in output + # Test handling of invalid command line options. + returncode, output = run_cli(main, '--unsupported-option') + assert returncode != 0 + # Test `humanfriendly --format-number'. + returncode, output = run_cli(main, '--format-number=1234567') + assert output.strip() == '1,234,567' + # Test `humanfriendly --format-size'. + random_byte_count = random.randint(1024, 1024 * 1024) + returncode, output = run_cli(main, '--format-size=%i' % random_byte_count) + assert output.strip() == format_size(random_byte_count) + # Test `humanfriendly --format-size --binary'. + random_byte_count = random.randint(1024, 1024 * 1024) + returncode, output = run_cli(main, '--format-size=%i' % random_byte_count, '--binary') + assert output.strip() == format_size(random_byte_count, binary=True) + # Test `humanfriendly --format-length'. + random_len = random.randint(1024, 1024 * 1024) + returncode, output = run_cli(main, '--format-length=%i' % random_len) + assert output.strip() == format_length(random_len) + random_len = float(random_len) / 12345.6 + returncode, output = run_cli(main, '--format-length=%f' % random_len) + assert output.strip() == format_length(random_len) + # Test `humanfriendly --format-table'. + returncode, output = run_cli(main, '--format-table', '--delimiter=\t', input='1\t2\t3\n4\t5\t6\n7\t8\t9') + assert output.strip() == dedent(''' + ------------- + | 1 | 2 | 3 | + | 4 | 5 | 6 | + | 7 | 8 | 9 | + ------------- + ''').strip() + # Test `humanfriendly --format-timespan'. + random_timespan = random.randint(5, 600) + returncode, output = run_cli(main, '--format-timespan=%i' % random_timespan) + assert output.strip() == format_timespan(random_timespan) + # Test `humanfriendly --parse-size'. + returncode, output = run_cli(main, '--parse-size=5 KB') + assert int(output) == parse_size('5 KB') + # Test `humanfriendly --parse-size'. + returncode, output = run_cli(main, '--parse-size=5 YiB') + assert int(output) == parse_size('5 YB', binary=True) + # Test `humanfriendly --parse-length'. + returncode, output = run_cli(main, '--parse-length=5 km') + assert int(output) == parse_length('5 km') + returncode, output = run_cli(main, '--parse-length=1.05 km') + assert float(output) == parse_length('1.05 km') + # Test `humanfriendly --run-command'. + returncode, output = run_cli(main, '--run-command', 'bash', '-c', 'sleep 2 && exit 42') + assert returncode == 42 + # Test `humanfriendly --demo'. The purpose of this test is + # to ensure that the demo runs successfully on all versions + # of Python and outputs the expected sections (recognized by + # their headings) without triggering exceptions. This was + # written as a regression test after issue #28 was reported: + # https://github.com/xolox/python-humanfriendly/issues/28 + returncode, output = run_cli(main, '--demo') + assert returncode == 0 + lines = [ansi_strip(line) for line in output.splitlines()] + assert "Text styles:" in lines + assert "Foreground colors:" in lines + assert "Background colors:" in lines + assert "256 color mode (standard colors):" in lines + assert "256 color mode (high-intensity colors):" in lines + assert "256 color mode (216 colors):" in lines + assert "256 color mode (gray scale colors):" in lines + + def test_ansi_style(self): + """Test :func:`humanfriendly.terminal.ansi_style()`.""" + assert ansi_style(bold=True) == '%s1%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(faint=True) == '%s2%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(italic=True) == '%s3%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(underline=True) == '%s4%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(inverse=True) == '%s7%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(strike_through=True) == '%s9%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(color='blue') == '%s34%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(background='blue') == '%s44%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(color='blue', bright=True) == '%s94%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(color=214) == '%s38;5;214%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(background=214) == '%s39;5;214%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(color=(0, 0, 0)) == '%s38;2;0;0;0%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(color=(255, 255, 255)) == '%s38;2;255;255;255%s' % (ANSI_CSI, ANSI_SGR) + assert ansi_style(background=(50, 100, 150)) == '%s48;2;50;100;150%s' % (ANSI_CSI, ANSI_SGR) + with self.assertRaises(ValueError): + ansi_style(color='unknown') + + def test_ansi_width(self): + """Test :func:`humanfriendly.terminal.ansi_width()`.""" + text = "Whatever" + # Make sure ansi_width() works as expected on strings without ANSI escape sequences. + assert len(text) == ansi_width(text) + # Wrap a text in ANSI escape sequences and make sure ansi_width() treats it as expected. + wrapped = ansi_wrap(text, bold=True) + # Make sure ansi_wrap() changed the text. + assert wrapped != text + # Make sure ansi_wrap() added additional bytes. + assert len(wrapped) > len(text) + # Make sure the result of ansi_width() stays the same. + assert len(text) == ansi_width(wrapped) + + def test_ansi_wrap(self): + """Test :func:`humanfriendly.terminal.ansi_wrap()`.""" + text = "Whatever" + # Make sure ansi_wrap() does nothing when no keyword arguments are given. + assert text == ansi_wrap(text) + # Make sure ansi_wrap() starts the text with the CSI sequence. + assert ansi_wrap(text, bold=True).startswith(ANSI_CSI) + # Make sure ansi_wrap() ends the text by resetting the ANSI styles. + assert ansi_wrap(text, bold=True).endswith(ANSI_RESET) + + def test_html_to_ansi(self): + """Test the :func:`humanfriendly.terminal.html_to_ansi()` function.""" + assert html_to_ansi("Just some plain text") == "Just some plain text" + # Hyperlinks. + assert html_to_ansi('python.org') == \ + '\x1b[0m\x1b[4;94mpython.org\x1b[0m (\x1b[0m\x1b[4;94mhttps://python.org\x1b[0m)' + # Make sure `mailto:' prefixes are stripped (they're not at all useful in a terminal). + assert html_to_ansi('peter@peterodding.com') == \ + '\x1b[0m\x1b[4;94mpeter@peterodding.com\x1b[0m' + # Bold text. + assert html_to_ansi("Let's try bold") == "Let's try \x1b[0m\x1b[1mbold\x1b[0m" + assert html_to_ansi("Let's try bold") == \ + "Let's try \x1b[0m\x1b[1mbold\x1b[0m" + # Italic text. + assert html_to_ansi("Let's try italic") == \ + "Let's try \x1b[0m\x1b[3mitalic\x1b[0m" + assert html_to_ansi("Let's try italic") == \ + "Let's try \x1b[0m\x1b[3mitalic\x1b[0m" + # Underlined text. + assert html_to_ansi("Let's try underline") == \ + "Let's try \x1b[0m\x1b[4munderline\x1b[0m" + assert html_to_ansi("Let's try underline") == \ + "Let's try \x1b[0m\x1b[4munderline\x1b[0m" + # Strike-through text. + assert html_to_ansi("Let's try strike-through") == \ + "Let's try \x1b[0m\x1b[9mstrike-through\x1b[0m" + assert html_to_ansi("Let's try strike-through") == \ + "Let's try \x1b[0m\x1b[9mstrike-through\x1b[0m" + # Pre-formatted text. + assert html_to_ansi("Let's try pre-formatted") == \ + "Let's try \x1b[0m\x1b[33mpre-formatted\x1b[0m" + # Text colors (with a 6 digit hexadecimal color value). + assert html_to_ansi("Let's try text colors") == \ + "Let's try \x1b[0m\x1b[38;2;170;187;204mtext colors\x1b[0m" + # Background colors (with an rgb(N, N, N) expression). + assert html_to_ansi("Let's try background colors") == \ + "Let's try \x1b[0m\x1b[48;2;50;50;50mbackground colors\x1b[0m" + # Line breaks. + assert html_to_ansi("Let's try some
line
breaks") == \ + "Let's try some\nline\nbreaks" + # Check that decimal entities are decoded. + assert html_to_ansi("&") == "&" + # Check that named entities are decoded. + assert html_to_ansi("&") == "&" + assert html_to_ansi(">") == ">" + assert html_to_ansi("<") == "<" + # Check that hexadecimal entities are decoded. + assert html_to_ansi("&") == "&" + # Check that the text callback is actually called. + + def callback(text): + return text.replace(':wink:', ';-)') + + assert ':wink:' not in html_to_ansi(':wink:', callback=callback) + # Check that the text callback doesn't process preformatted text. + assert ':wink:' in html_to_ansi(':wink:', callback=callback) + # Try a somewhat convoluted but nevertheless real life example from my + # personal chat archives that causes humanfriendly releases 4.15 and + # 4.15.1 to raise an exception. + assert html_to_ansi(u''' + Tweakers zit er idd nog steeds:

+ peter@peter-work> curl -s tweakers.net | grep -i hosting
+ <a href="http://www.true.nl/webhosting/" + rel="external" id="true" title="Hosting door True"></a>
+ Hosting door <a href="http://www.true.nl/vps/" + title="VPS hosting" rel="external">True + ''') + + def test_generate_output(self): + """Test the :func:`humanfriendly.terminal.output()` function.""" + text = "Standard output generated by output()" + with CaptureOutput(merged=False) as capturer: + output(text) + self.assertEqual([text], capturer.stdout.get_lines()) + self.assertEqual([], capturer.stderr.get_lines()) + + def test_generate_message(self): + """Test the :func:`humanfriendly.terminal.message()` function.""" + text = "Standard error generated by message()" + with CaptureOutput(merged=False) as capturer: + message(text) + self.assertEqual([], capturer.stdout.get_lines()) + self.assertEqual([text], capturer.stderr.get_lines()) + + def test_generate_warning(self): + """Test the :func:`humanfriendly.terminal.warning()` function.""" + from capturer import CaptureOutput + text = "Standard error generated by warning()" + with CaptureOutput(merged=False) as capturer: + warning(text) + self.assertEqual([], capturer.stdout.get_lines()) + self.assertEqual([ansi_wrap(text, color='red')], self.ignore_coverage_warning(capturer.stderr)) + + def ignore_coverage_warning(self, stream): + """ + Filter out coverage.py warning from standard error. + + This is intended to remove the following line from the lines captured + on the standard error stream: + + Coverage.py warning: No data was collected. (no-data-collected) + """ + return [line for line in stream.get_lines() if 'no-data-collected' not in line] + + def test_clean_output(self): + """Test :func:`humanfriendly.terminal.clean_terminal_output()`.""" + # Simple output should pass through unharmed (single line). + assert clean_terminal_output('foo') == ['foo'] + # Simple output should pass through unharmed (multiple lines). + assert clean_terminal_output('foo\nbar') == ['foo', 'bar'] + # Carriage returns and preceding substrings are removed. + assert clean_terminal_output('foo\rbar\nbaz') == ['bar', 'baz'] + # Carriage returns move the cursor to the start of the line without erasing text. + assert clean_terminal_output('aaa\rab') == ['aba'] + # Backspace moves the cursor one position back without erasing text. + assert clean_terminal_output('aaa\b\bb') == ['aba'] + # Trailing empty lines should be stripped. + assert clean_terminal_output('foo\nbar\nbaz\n\n\n') == ['foo', 'bar', 'baz'] + + def test_find_terminal_size(self): + """Test :func:`humanfriendly.terminal.find_terminal_size()`.""" + lines, columns = find_terminal_size() + # We really can't assert any minimum or maximum values here because it + # simply doesn't make any sense; it's impossible for me to anticipate + # on what environments this test suite will run in the future. + assert lines > 0 + assert columns > 0 + # The find_terminal_size_using_ioctl() function is the default + # implementation and it will likely work fine. This makes it hard to + # test the fall back code paths though. However there's an easy way to + # make find_terminal_size_using_ioctl() fail ... + saved_stdin = sys.stdin + saved_stdout = sys.stdout + saved_stderr = sys.stderr + try: + # What do you mean this is brute force?! ;-) + sys.stdin = StringIO() + sys.stdout = StringIO() + sys.stderr = StringIO() + # Now find_terminal_size_using_ioctl() should fail even though + # find_terminal_size_using_stty() might work fine. + lines, columns = find_terminal_size() + assert lines > 0 + assert columns > 0 + # There's also an ugly way to make `stty size' fail: The + # subprocess.Popen class uses os.execvp() underneath, so if we + # clear the $PATH it will break. + saved_path = os.environ['PATH'] + try: + os.environ['PATH'] = '' + # Now find_terminal_size_using_stty() should fail. + lines, columns = find_terminal_size() + assert lines > 0 + assert columns > 0 + finally: + os.environ['PATH'] = saved_path + finally: + sys.stdin = saved_stdin + sys.stdout = saved_stdout + sys.stderr = saved_stderr + + def test_terminal_capabilities(self): + """Test the functions that check for terminal capabilities.""" + from capturer import CaptureOutput + for test_stream in connected_to_terminal, terminal_supports_colors: + # This test suite should be able to run interactively as well as + # non-interactively, so we can't expect or demand that standard streams + # will always be connected to a terminal. Fortunately Capturer enables + # us to fake it :-). + for stream in sys.stdout, sys.stderr: + with CaptureOutput(): + assert test_stream(stream) + # Test something that we know can never be a terminal. + with open(os.devnull) as handle: + assert not test_stream(handle) + # Verify that objects without isatty() don't raise an exception. + assert not test_stream(object()) + + def test_show_pager(self): + """Test :func:`humanfriendly.terminal.show_pager()`.""" + original_pager = os.environ.get('PAGER', None) + try: + # We specifically avoid `less' because it would become awkward to + # run the test suite in an interactive terminal :-). + os.environ['PAGER'] = 'cat' + # Generate a significant amount of random text spread over multiple + # lines that we expect to be reported literally on the terminal. + random_text = "\n".join(random_string(25) for i in range(50)) + # Run the pager command and validate the output. + with CaptureOutput() as capturer: + show_pager(random_text) + assert random_text in capturer.get_text() + finally: + if original_pager is not None: + # Restore the original $PAGER value. + os.environ['PAGER'] = original_pager + else: + # Clear the custom $PAGER value. + os.environ.pop('PAGER') + + def test_get_pager_command(self): + """Test :func:`humanfriendly.terminal.get_pager_command()`.""" + # Make sure --RAW-CONTROL-CHARS isn't used when it's not needed. + assert '--RAW-CONTROL-CHARS' not in get_pager_command("Usage message") + # Make sure --RAW-CONTROL-CHARS is used when it's needed. + assert '--RAW-CONTROL-CHARS' in get_pager_command(ansi_wrap("Usage message", bold=True)) + # Make sure that less-specific options are only used when valid. + options_specific_to_less = ['--no-init', '--quit-if-one-screen'] + for pager in 'cat', 'less': + original_pager = os.environ.get('PAGER', None) + try: + # Set $PAGER to `cat' or `less'. + os.environ['PAGER'] = pager + # Get the pager command line. + command_line = get_pager_command() + # Check for less-specific options. + if pager == 'less': + assert all(opt in command_line for opt in options_specific_to_less) + else: + assert not any(opt in command_line for opt in options_specific_to_less) + finally: + if original_pager is not None: + # Restore the original $PAGER value. + os.environ['PAGER'] = original_pager + else: + # Clear the custom $PAGER value. + os.environ.pop('PAGER') + + def test_find_meta_variables(self): + """Test :func:`humanfriendly.usage.find_meta_variables()`.""" + assert sorted(find_meta_variables(""" + Here's one example: --format-number=VALUE + Here's another example: --format-size=BYTES + A final example: --format-timespan=SECONDS + This line doesn't contain a META variable. + """)) == sorted(['VALUE', 'BYTES', 'SECONDS']) + + def test_parse_usage_simple(self): + """Test :func:`humanfriendly.usage.parse_usage()` (a simple case).""" + introduction, options = self.preprocess_parse_result(""" + Usage: my-fancy-app [OPTIONS] + + Boring description. + + Supported options: + + -h, --help + + Show this message and exit. + """) + # The following fragments are (expected to be) part of the introduction. + assert "Usage: my-fancy-app [OPTIONS]" in introduction + assert "Boring description." in introduction + assert "Supported options:" in introduction + # The following fragments are (expected to be) part of the documented options. + assert "-h, --help" in options + assert "Show this message and exit." in options + + def test_parse_usage_tricky(self): + """Test :func:`humanfriendly.usage.parse_usage()` (a tricky case).""" + introduction, options = self.preprocess_parse_result(""" + Usage: my-fancy-app [OPTIONS] + + Here's the introduction to my-fancy-app. Some of the lines in the + introduction start with a command line option just to confuse the + parsing algorithm :-) + + For example + --an-awesome-option + is still part of the introduction. + + Supported options: + + -a, --an-awesome-option + + Explanation why this is an awesome option. + + -b, --a-boring-option + + Explanation why this is a boring option. + """) + # The following fragments are (expected to be) part of the introduction. + assert "Usage: my-fancy-app [OPTIONS]" in introduction + assert any('still part of the introduction' in p for p in introduction) + assert "Supported options:" in introduction + # The following fragments are (expected to be) part of the documented options. + assert "-a, --an-awesome-option" in options + assert "Explanation why this is an awesome option." in options + assert "-b, --a-boring-option" in options + assert "Explanation why this is a boring option." in options + + def test_parse_usage_commas(self): + """Test :func:`humanfriendly.usage.parse_usage()` against option labels containing commas.""" + introduction, options = self.preprocess_parse_result(""" + Usage: my-fancy-app [OPTIONS] + + Some introduction goes here. + + Supported options: + + -f, --first-option + + Explanation of first option. + + -s, --second-option=WITH,COMMA + + This should be a separate option's description. + """) + # The following fragments are (expected to be) part of the introduction. + assert "Usage: my-fancy-app [OPTIONS]" in introduction + assert "Some introduction goes here." in introduction + assert "Supported options:" in introduction + # The following fragments are (expected to be) part of the documented options. + assert "-f, --first-option" in options + assert "Explanation of first option." in options + assert "-s, --second-option=WITH,COMMA" in options + assert "This should be a separate option's description." in options + + def preprocess_parse_result(self, text): + """Ignore leading/trailing whitespace in usage parsing tests.""" + return tuple([p.strip() for p in r] for r in parse_usage(dedent(text))) + + def test_format_usage(self): + """Test :func:`humanfriendly.usage.format_usage()`.""" + # Test that options are highlighted. + usage_text = "Just one --option" + formatted_text = format_usage(usage_text) + assert len(formatted_text) > len(usage_text) + assert formatted_text.startswith("Just one ") + # Test that the "Usage: ..." line is highlighted. + usage_text = "Usage: humanfriendly [OPTIONS]" + formatted_text = format_usage(usage_text) + assert len(formatted_text) > len(usage_text) + assert usage_text in formatted_text + assert not formatted_text.startswith(usage_text) + # Test that meta variables aren't erroneously highlighted. + usage_text = ( + "--valid-option=VALID_METAVAR\n" + "VALID_METAVAR is bogus\n" + "INVALID_METAVAR should not be highlighted\n" + ) + formatted_text = format_usage(usage_text) + formatted_lines = formatted_text.splitlines() + # Make sure the meta variable in the second line is highlighted. + assert ANSI_CSI in formatted_lines[1] + # Make sure the meta variable in the third line isn't highlighted. + assert ANSI_CSI not in formatted_lines[2] + + def test_render_usage(self): + """Test :func:`humanfriendly.usage.render_usage()`.""" + assert render_usage("Usage: some-command WITH ARGS") == "**Usage:** `some-command WITH ARGS`" + assert render_usage("Supported options:") == "**Supported options:**" + assert 'code-block' in render_usage(dedent(""" + Here comes a shell command: + + $ echo test + test + """)) + assert all(token in render_usage(dedent(""" + Supported options: + + -n, --dry-run + + Don't change anything. + """)) for token in ('`-n`', '`--dry-run`')) + + def test_deprecated_args(self): + """Test the deprecated_args() decorator function.""" + @deprecated_args('foo', 'bar') + def test_function(**options): + assert options['foo'] == 'foo' + assert options.get('bar') in (None, 'bar') + return 42 + fake_fn = MagicMock() + with PatchedAttribute(warnings, 'warn', fake_fn): + assert test_function('foo', 'bar') == 42 + with self.assertRaises(TypeError): + test_function('foo', 'bar', 'baz') + assert fake_fn.was_called + + def test_alias_proxy_deprecation_warning(self): + """Test that the DeprecationProxy class emits deprecation warnings.""" + fake_fn = MagicMock() + with PatchedAttribute(warnings, 'warn', fake_fn): + module = sys.modules[__name__] + aliases = dict(concatenate='humanfriendly.text.concatenate') + proxy = DeprecationProxy(module, aliases) + assert proxy.concatenate == concatenate + assert fake_fn.was_called + + def test_alias_proxy_sphinx_compensation(self): + """Test that the DeprecationProxy class emits deprecation warnings.""" + with PatchedItem(sys.modules, 'sphinx', types.ModuleType('sphinx')): + define_aliases(__name__, concatenate='humanfriendly.text.concatenate') + assert "concatenate" in dir(sys.modules[__name__]) + assert "concatenate" in get_aliases(__name__) + + def test_alias_proxy_sphinx_integration(self): + """Test that aliases can be injected into generated documentation.""" + module = sys.modules[__name__] + define_aliases(__name__, concatenate='humanfriendly.text.concatenate') + lines = module.__doc__.splitlines() + deprecation_note_callback(app=None, what=None, name=None, obj=module, options=None, lines=lines) + # Check that something was injected. + assert "\n".join(lines) != module.__doc__ + + def test_sphinx_customizations(self): + """Test the :mod:`humanfriendly.sphinx` module.""" + class FakeApp(object): + + def __init__(self): + self.callbacks = {} + self.roles = {} + + def __documented_special_method__(self): + """Documented unofficial special method.""" + pass + + def __undocumented_special_method__(self): + # Intentionally not documented :-). + pass + + def add_role(self, name, callback): + self.roles[name] = callback + + def connect(self, event, callback): + self.callbacks.setdefault(event, []).append(callback) + + def bogus_usage(self): + """Usage: This is not supposed to be reformatted!""" + pass + + # Test event callback registration. + fake_app = FakeApp() + setup(fake_app) + assert man_role == fake_app.roles['man'] + assert pypi_role == fake_app.roles['pypi'] + assert deprecation_note_callback in fake_app.callbacks['autodoc-process-docstring'] + assert special_methods_callback in fake_app.callbacks['autodoc-skip-member'] + assert usage_message_callback in fake_app.callbacks['autodoc-process-docstring'] + # Test that `special methods' which are documented aren't skipped. + assert special_methods_callback( + app=None, what=None, name=None, + obj=FakeApp.__documented_special_method__, + skip=True, options=None, + ) is False + # Test that `special methods' which are undocumented are skipped. + assert special_methods_callback( + app=None, what=None, name=None, + obj=FakeApp.__undocumented_special_method__, + skip=True, options=None, + ) is True + # Test formatting of usage messages. obj/lines + from humanfriendly import cli, sphinx + # We expect the docstring in the `cli' module to be reformatted + # (because it contains a usage message in the expected format). + assert self.docstring_is_reformatted(cli) + # We don't expect the docstring in the `sphinx' module to be + # reformatted (because it doesn't contain a usage message). + assert not self.docstring_is_reformatted(sphinx) + # We don't expect the docstring of the following *method* to be + # reformatted because only *module* docstrings should be reformatted. + assert not self.docstring_is_reformatted(fake_app.bogus_usage) + + def docstring_is_reformatted(self, entity): + """Check whether :func:`.usage_message_callback()` reformats a module's docstring.""" + lines = trim_empty_lines(entity.__doc__).splitlines() + saved_lines = list(lines) + usage_message_callback( + app=None, what=None, name=None, + obj=entity, options=None, lines=lines, + ) + return lines != saved_lines + + +def normalize_timestamp(value, ndigits=1): + """ + Round timestamps to the given number of digits. + + This helps to make the test suite less sensitive to timing issues caused by + multitasking, processor scheduling, etc. + """ + return '%.2f' % round(float(value), ndigits=ndigits) diff --git a/python_embeded/Lib/site-packages/hydra/__init__.py b/python_embeded/Lib/site-packages/hydra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb91a833c59ce4c286aabf2642263b61a0e561e6 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/__init__.py @@ -0,0 +1,23 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved + +# Source of truth for Hydra's version +__version__ = "1.3.2" +from hydra import utils +from hydra.errors import MissingConfigException +from hydra.main import main +from hydra.types import TaskFunction + +from .compose import compose +from .initialize import initialize, initialize_config_dir, initialize_config_module + +__all__ = [ + "__version__", + "MissingConfigException", + "main", + "utils", + "TaskFunction", + "compose", + "initialize", + "initialize_config_module", + "initialize_config_dir", +] diff --git a/python_embeded/Lib/site-packages/hydra/compose.py b/python_embeded/Lib/site-packages/hydra/compose.py new file mode 100644 index 0000000000000000000000000000000000000000..09b150d6e2a6a346e68041ac1a168d9614757dd2 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/compose.py @@ -0,0 +1,66 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from textwrap import dedent +from typing import List, Optional + +from omegaconf import DictConfig, OmegaConf, open_dict + +from hydra import version +from hydra.core.global_hydra import GlobalHydra +from hydra.types import RunMode + +from ._internal.deprecation_warning import deprecation_warning + + +def compose( + config_name: Optional[str] = None, + overrides: Optional[List[str]] = None, + return_hydra_config: bool = False, + strict: Optional[bool] = None, +) -> DictConfig: + """ + :param config_name: the name of the config + (usually the file name without the .yaml extension) + :param overrides: list of overrides for config file + :param return_hydra_config: True to return the hydra config node in the result + :param strict: DEPRECATED. If false, returned config has struct mode disabled. + :return: the composed config + """ + + if overrides is None: + overrides = [] + + assert ( + GlobalHydra().is_initialized() + ), "GlobalHydra is not initialized, use @hydra.main() or call one of the hydra initialization methods first" + + gh = GlobalHydra.instance() + assert gh.hydra is not None + cfg = gh.hydra.compose_config( + config_name=config_name, + overrides=overrides, + run_mode=RunMode.RUN, + from_shell=False, + with_log_configuration=False, + ) + assert isinstance(cfg, DictConfig) + + if not return_hydra_config: + if "hydra" in cfg: + with open_dict(cfg): + del cfg["hydra"] + + if strict is not None: + if version.base_at_least("1.2"): + raise TypeError("got an unexpected 'strict' argument") + else: + deprecation_warning( + dedent( + """ + The strict flag in the compose API is deprecated. + See https://hydra.cc/docs/1.2/upgrades/0.11_to_1.0/strict_mode_flag_deprecated for more info. + """ + ) + ) + OmegaConf.set_struct(cfg, strict) + + return cfg diff --git a/python_embeded/Lib/site-packages/hydra/errors.py b/python_embeded/Lib/site-packages/hydra/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..427e8375506063772c16868cdaba7b6a336ff2dd --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/errors.py @@ -0,0 +1,45 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from typing import Optional, Sequence + + +class HydraException(Exception): + ... + + +class CompactHydraException(HydraException): + ... + + +class OverrideParseException(CompactHydraException): + def __init__(self, override: str, message: str) -> None: + super(OverrideParseException, self).__init__(message) + self.override = override + self.message = message + + +class InstantiationException(CompactHydraException): + ... + + +class ConfigCompositionException(CompactHydraException): + ... + + +class SearchPathException(CompactHydraException): + ... + + +class MissingConfigException(IOError, ConfigCompositionException): + def __init__( + self, + message: str, + missing_cfg_file: Optional[str] = None, + options: Optional[Sequence[str]] = None, + ) -> None: + super(MissingConfigException, self).__init__(message) + self.missing_cfg_file = missing_cfg_file + self.options = options + + +class HydraDeprecationError(HydraException): + ... diff --git a/python_embeded/Lib/site-packages/hydra/initialize.py b/python_embeded/Lib/site-packages/hydra/initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..7f8110db189f4c6514f25204b5414da5de439c9c --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/initialize.py @@ -0,0 +1,179 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import copy +import os +from textwrap import dedent +from typing import Any, Optional + +from hydra import version +from hydra._internal.deprecation_warning import deprecation_warning +from hydra._internal.hydra import Hydra +from hydra._internal.utils import ( + create_config_search_path, + detect_calling_file_or_module_from_stack_frame, + detect_task_name, +) +from hydra.core.global_hydra import GlobalHydra +from hydra.core.singleton import Singleton +from hydra.errors import HydraException + + +def get_gh_backup() -> Any: + if GlobalHydra in Singleton._instances: + return copy.deepcopy(Singleton._instances[GlobalHydra]) + else: + return None + + +def restore_gh_from_backup(_gh_backup: Any) -> Any: + if _gh_backup is None: + del Singleton._instances[GlobalHydra] + else: + Singleton._instances[GlobalHydra] = _gh_backup + + +_UNSPECIFIED_: Any = object() + + +class initialize: + """ + Initializes Hydra and add the config_path to the config search path. + config_path is relative to the parent of the caller. + Hydra detects the caller type automatically at runtime. + + Supported callers: + - Python scripts + - Python modules + - Unit tests + - Jupyter notebooks. + :param config_path: path relative to the parent of the caller + :param job_name: the value for hydra.job.name (By default it is automatically detected based on the caller) + :param caller_stack_depth: stack depth of the caller, defaults to 1 (direct caller). + """ + + def __init__( + self, + config_path: Optional[str] = _UNSPECIFIED_, + job_name: Optional[str] = None, + caller_stack_depth: int = 1, + version_base: Optional[str] = _UNSPECIFIED_, + ) -> None: + self._gh_backup = get_gh_backup() + + version.setbase(version_base) + + if config_path is _UNSPECIFIED_: + if version.base_at_least("1.2"): + config_path = None + elif version_base is _UNSPECIFIED_: + url = "https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_hydra_main_config_path" + deprecation_warning( + message=dedent( + f"""\ + config_path is not specified in hydra.initialize(). + See {url} for more information.""" + ), + stacklevel=2, + ) + config_path = "." + else: + config_path = "." + + if config_path is not None and os.path.isabs(config_path): + raise HydraException("config_path in initialize() must be relative") + calling_file, calling_module = detect_calling_file_or_module_from_stack_frame( + caller_stack_depth + 1 + ) + if job_name is None: + job_name = detect_task_name( + calling_file=calling_file, calling_module=calling_module + ) + + Hydra.create_main_hydra_file_or_module( + calling_file=calling_file, + calling_module=calling_module, + config_path=config_path, + job_name=job_name, + ) + + def __enter__(self, *args: Any, **kwargs: Any) -> None: + ... + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + restore_gh_from_backup(self._gh_backup) + + def __repr__(self) -> str: + return "hydra.initialize()" + + +class initialize_config_module: + """ + Initializes Hydra and add the config_module to the config search path. + The config module must be importable (an __init__.py must exist at its top level) + :param config_module: absolute module name, for example "foo.bar.conf". + :param job_name: the value for hydra.job.name (default is 'app') + """ + + def __init__( + self, + config_module: str, + job_name: str = "app", + version_base: Optional[str] = _UNSPECIFIED_, + ): + self._gh_backup = get_gh_backup() + + version.setbase(version_base) + + Hydra.create_main_hydra_file_or_module( + calling_file=None, + calling_module=f"{config_module}.{job_name}", + config_path=None, + job_name=job_name, + ) + + def __enter__(self, *args: Any, **kwargs: Any) -> None: + ... + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + restore_gh_from_backup(self._gh_backup) + + def __repr__(self) -> str: + return "hydra.initialize_config_module()" + + +class initialize_config_dir: + """ + Initializes Hydra and add an absolute config dir to the to the config search path. + The config_dir is always a path on the file system and is must be an absolute path. + Relative paths will result in an error. + :param config_dir: absolute file system path + :param job_name: the value for hydra.job.name (default is 'app') + """ + + def __init__( + self, + config_dir: str, + job_name: str = "app", + version_base: Optional[str] = _UNSPECIFIED_, + ) -> None: + self._gh_backup = get_gh_backup() + + version.setbase(version_base) + + # Relative here would be interpreted as relative to cwd, which - depending on when it run + # may have unexpected meaning. best to force an absolute path to avoid confusion. + # Can consider using hydra.utils.to_absolute_path() to convert it at a future point if there is demand. + if not os.path.isabs(config_dir): + raise HydraException( + "initialize_config_dir() requires an absolute config_dir as input" + ) + csp = create_config_search_path(search_path_dir=config_dir) + Hydra.create_main_hydra2(task_name=job_name, config_search_path=csp) + + def __enter__(self, *args: Any, **kwargs: Any) -> None: + ... + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + restore_gh_from_backup(self._gh_backup) + + def __repr__(self) -> str: + return "hydra.initialize_config_dir()" diff --git a/python_embeded/Lib/site-packages/hydra/main.py b/python_embeded/Lib/site-packages/hydra/main.py new file mode 100644 index 0000000000000000000000000000000000000000..134bec0b5707f85081e040f205bc47b3b2b8ea60 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/main.py @@ -0,0 +1,104 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import copy +import functools +import pickle +import warnings +from pathlib import Path +from textwrap import dedent +from typing import Any, Callable, List, Optional + +from omegaconf import DictConfig, open_dict, read_write + +from . import version +from ._internal.deprecation_warning import deprecation_warning +from ._internal.utils import _run_hydra, get_args_parser +from .core.hydra_config import HydraConfig +from .core.utils import _flush_loggers, configure_log +from .types import TaskFunction + +_UNSPECIFIED_: Any = object() + + +def _get_rerun_conf(file_path: str, overrides: List[str]) -> DictConfig: + msg = "Experimental rerun CLI option, other command line args are ignored." + warnings.warn(msg, UserWarning) + file = Path(file_path) + if not file.exists(): + raise ValueError(f"File {file} does not exist!") + + if len(overrides) > 0: + msg = "Config overrides are not supported as of now." + warnings.warn(msg, UserWarning) + + with open(str(file), "rb") as input: + config = pickle.load(input) # nosec + configure_log(config.hydra.job_logging, config.hydra.verbose) + HydraConfig.instance().set_config(config) + task_cfg = copy.deepcopy(config) + with read_write(task_cfg): + with open_dict(task_cfg): + del task_cfg["hydra"] + assert isinstance(task_cfg, DictConfig) + return task_cfg + + +def main( + config_path: Optional[str] = _UNSPECIFIED_, + config_name: Optional[str] = None, + version_base: Optional[str] = _UNSPECIFIED_, +) -> Callable[[TaskFunction], Any]: + """ + :param config_path: The config path, a directory where Hydra will search for + config files. This path is added to Hydra's searchpath. + Relative paths are interpreted relative to the declaring python + file. Alternatively, you can use the prefix `pkg://` to specify + a python package to add to the searchpath. + If config_path is None no directory is added to the Config search path. + :param config_name: The name of the config (usually the file name without the .yaml extension) + """ + + version.setbase(version_base) + + if config_path is _UNSPECIFIED_: + if version.base_at_least("1.2"): + config_path = None + elif version_base is _UNSPECIFIED_: + url = "https://hydra.cc/docs/1.2/upgrades/1.0_to_1.1/changes_to_hydra_main_config_path" + deprecation_warning( + message=dedent( + f""" + config_path is not specified in @hydra.main(). + See {url} for more information.""" + ), + stacklevel=2, + ) + config_path = "." + else: + config_path = "." + + def main_decorator(task_function: TaskFunction) -> Callable[[], None]: + @functools.wraps(task_function) + def decorated_main(cfg_passthrough: Optional[DictConfig] = None) -> Any: + if cfg_passthrough is not None: + return task_function(cfg_passthrough) + else: + args_parser = get_args_parser() + args = args_parser.parse_args() + if args.experimental_rerun is not None: + cfg = _get_rerun_conf(args.experimental_rerun, args.overrides) + task_function(cfg) + _flush_loggers() + else: + # no return value from run_hydra() as it may sometime actually run the task_function + # multiple times (--multirun) + _run_hydra( + args=args, + args_parser=args_parser, + task_function=task_function, + config_path=config_path, + config_name=config_name, + ) + + return decorated_main + + return main_decorator diff --git a/python_embeded/Lib/site-packages/hydra/py.typed b/python_embeded/Lib/site-packages/hydra/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/hydra/types.py b/python_embeded/Lib/site-packages/hydra/types.py new file mode 100644 index 0000000000000000000000000000000000000000..0050a773beb7e0c7faf6cf99835f022264f3b554 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/types.py @@ -0,0 +1,90 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from dataclasses import dataclass +from enum import Enum +from typing import TYPE_CHECKING, Any, Callable + +from omegaconf import MISSING + +from hydra import version + +from ._internal.deprecation_warning import deprecation_warning + +TaskFunction = Callable[[Any], Any] + + +if TYPE_CHECKING: + from hydra._internal.callbacks import Callbacks + from hydra.core.config_loader import ConfigLoader + + +@dataclass +class HydraContext: + config_loader: "ConfigLoader" + callbacks: "Callbacks" + + +@dataclass +class TargetConf: + """ + This class is going away in Hydra 1.2. + You should no longer extend it or annotate with it. + instantiate will work correctly if you pass in a DictConfig object or any dataclass that has the + _target_ attribute. + """ + + _target_: str = MISSING + + def __post_init__(self) -> None: + if version.base_at_least("1.2"): + raise TypeError("TargetConf is unsupported since Hydra 1.2") + else: + msg = "\nTargetConf is deprecated since Hydra 1.1 and will be removed in Hydra 1.2." + deprecation_warning(message=msg) + + +class RunMode(Enum): + RUN = 1 + MULTIRUN = 2 + + +class ConvertMode(Enum): + """ConvertMode for instantiate, controls return type. + + A config is either config or instance-like (`_target_` field). + + If instance-like, instantiate resolves the callable (class or + function) and returns the result of the call on the rest of the + parameters. + + If "none", config-like configs will be kept as is. + + If "partial", config-like configs will be converted to native python + containers (list and dict), unless they are structured configs ( + dataclasses or attr instances). Structured configs remain as DictConfig objects. + + If "object", config-like configs will be converted to native python + containers (list and dict), unless they are structured configs ( + dataclasses or attr instances). Structured configs are converted to instances + of the backing dataclass or attr class using OmegaConf.to_object. + + If "all", config-like configs will all be converted to native python + containers (list and dict). + """ + + # Use DictConfig/ListConfig + NONE = "none" + # Convert the OmegaConf config to primitive container, Structured Configs are preserved + PARTIAL = "partial" + # Convert the OmegaConf config to primitive container, Structured Configs are converted to + # dataclass / attr class instances. + OBJECT = "object" + # Fully convert the OmegaConf config to primitive containers (dict, list and primitives). + ALL = "all" + + def __eq__(self, other: Any) -> Any: + if isinstance(other, ConvertMode): + return other.value == self.value + elif isinstance(other, str): + return other.upper() == self.name.upper() + else: + return NotImplemented diff --git a/python_embeded/Lib/site-packages/hydra/utils.py b/python_embeded/Lib/site-packages/hydra/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..93d3f5f22f17888f80a10410493b775af17fe999 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/utils.py @@ -0,0 +1,117 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved + +import logging.config +import os +from pathlib import Path +from typing import Any, Callable + +import hydra._internal.instantiate._instantiate2 +import hydra.types +from hydra._internal.utils import _locate +from hydra.core.hydra_config import HydraConfig + +log = logging.getLogger(__name__) + +# Instantiation related symbols +instantiate = hydra._internal.instantiate._instantiate2.instantiate +call = instantiate +ConvertMode = hydra.types.ConvertMode + + +def get_class(path: str) -> type: + """ + Look up a class based on a dotpath. + Fails if the path does not point to a class. + + >>> import my_module + >>> from hydra.utils import get_class + >>> assert get_class("my_module.MyClass") is my_module.MyClass + """ + try: + cls = _locate(path) + if not isinstance(cls, type): + raise ValueError( + f"Located non-class of type '{type(cls).__name__}'" + + f" while loading '{path}'" + ) + return cls + except Exception as e: + log.error(f"Error getting class at {path}: {e}") + raise e + + +def get_method(path: str) -> Callable[..., Any]: + """ + Look up a callable based on a dotpath. + Fails if the path does not point to a callable object. + + >>> import my_module + >>> from hydra.utils import get_method + >>> assert get_method("my_module.my_function") is my_module.my_function + """ + try: + obj = _locate(path) + if not callable(obj): + raise ValueError( + f"Located non-callable of type '{type(obj).__name__}'" + + f" while loading '{path}'" + ) + cl: Callable[..., Any] = obj + return cl + except Exception as e: + log.error(f"Error getting callable at {path} : {e}") + raise e + + +# Alias for get_method +get_static_method = get_method + + +def get_object(path: str) -> Any: + """ + Look up an entity based on the dotpath. + Does not perform any type checks on the entity. + + >>> import my_module + >>> from hydra.utils import get_object + >>> assert get_object("my_module.my_object") is my_module.my_object + """ + try: + obj = _locate(path) + return obj + except Exception as e: + log.error(f"Error getting object at {path} : {e}") + raise e + + +def get_original_cwd() -> str: + """ + :return: the original working directory the Hydra application was launched from + """ + if not HydraConfig.initialized(): + raise ValueError( + "get_original_cwd() must only be used after HydraConfig is initialized" + ) + ret = HydraConfig.get().runtime.cwd + assert ret is not None and isinstance(ret, str) + return ret + + +def to_absolute_path(path: str) -> str: + """ + converts the specified path to be absolute path. + if the input path is relative, it's interpreted as relative to the original working directory + if it's absolute, it's returned as is + :param path: path to convert + :return: + """ + p = Path(path) + if not HydraConfig.initialized(): + base = Path(os.getcwd()) + else: + base = Path(get_original_cwd()) + if p.is_absolute(): + ret = p + else: + ret = base / p + return str(ret) diff --git a/python_embeded/Lib/site-packages/hydra/version.py b/python_embeded/Lib/site-packages/hydra/version.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6c329b0ea001de5d3acbd45cee74abad85bfa9 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra/version.py @@ -0,0 +1,80 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved + +# Source of truth for Hydra's version + +from textwrap import dedent +from typing import Any, Optional + +from packaging.version import Version + +from . import __version__ +from ._internal.deprecation_warning import deprecation_warning +from .core.singleton import Singleton +from .errors import HydraException + +_UNSPECIFIED_: Any = object() + +__compat_version__: Version = Version("1.1") + + +class VersionBase(metaclass=Singleton): + def __init__(self) -> None: + self.version_base: Optional[Version] = _UNSPECIFIED_ + + def setbase(self, version: "Version") -> None: + assert isinstance( + version, Version + ), f"Unexpected Version type : {type(version)}" + self.version_base = version + + def getbase(self) -> Optional[Version]: + return self.version_base + + @staticmethod + def instance(*args: Any, **kwargs: Any) -> "VersionBase": + return Singleton.instance(VersionBase, *args, **kwargs) # type: ignore + + @staticmethod + def set_instance(instance: "VersionBase") -> None: + assert isinstance(instance, VersionBase) + Singleton._instances[VersionBase] = instance # type: ignore + + +def _get_version(ver: str) -> Version: + # Only consider major.minor as packaging will compare "1.2.0.dev2" < "1.2" + pver = Version(ver) + return Version(f"{pver.major}.{pver.minor}") + + +def base_at_least(ver: str) -> bool: + _version_base = VersionBase.instance().getbase() + if type(_version_base) is type(_UNSPECIFIED_): + VersionBase.instance().setbase(__compat_version__) + _version_base = __compat_version__ + assert isinstance(_version_base, Version) + return _version_base >= _get_version(ver) + + +def getbase() -> Optional[Version]: + return VersionBase.instance().getbase() + + +def setbase(ver: Any) -> None: + if type(ver) is type(_UNSPECIFIED_): + deprecation_warning( + message=dedent( + f""" + The version_base parameter is not specified. + Please specify a compatability version level, or None. + Will assume defaults for version {__compat_version__}""" + ), + stacklevel=3, + ) + _version_base = __compat_version__ + elif ver is None: + _version_base = _get_version(__version__) + else: + _version_base = _get_version(ver) + if _version_base < __compat_version__: + raise HydraException(f'version_base must be >= "{__compat_version__}"') + VersionBase.instance().setbase(_version_base) diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/LICENSE b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b96dcb0480a0b0be0727976e5202a1e7b23edc3f --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/METADATA b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..89017efbd21c66a707b946cd6d06e0d7d253d301 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/METADATA @@ -0,0 +1,110 @@ +Metadata-Version: 2.1 +Name: hydra-core +Version: 1.3.2 +Summary: A framework for elegantly configuring complex applications +Home-page: https://github.com/facebookresearch/hydra +Author: Omry Yadan +Author-email: omry@fb.com +License: MIT +Keywords: command-line configuration yaml tab-completion +Classifier: License :: OSI Approved :: MIT License +Classifier: Development Status :: 4 - Beta +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: Windows +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: omegaconf (<2.4,>=2.2) +Requires-Dist: antlr4-python3-runtime (==4.9.*) +Requires-Dist: packaging +Requires-Dist: importlib-resources ; python_version < "3.9" + +

logo

+ +

+ + PyPI + + + CircleCI + + + PyPI - License + + + PyPI - Python Version + + + Downloads + + + Code style: black + + + Total alerts + + + Language grade: Python + +

+ A framework for elegantly configuring complex applications. +

+

+ Check the website for more information,
+ or click the thumbnail below for a one-minute video introduction to Hydra.
+

+

+ + 1 minute overview + +

+

+ +---------------------- + + +### Releases + +#### Stable + +**Hydra 1.3** is the stable version of Hydra. +- [Documentation](https://hydra.cc/docs/1.3/intro/) +- Installation : `pip install hydra-core --upgrade` + +See the [NEWS.md](NEWS.md) file for a summary of recent changes to Hydra. + +### License +Hydra is licensed under [MIT License](LICENSE). + +## Hydra Ecosystem + +#### Check out these third-party libraries that build on Hydra's functionality: +* [hydra-zen](https://github.com/mit-ll-responsible-ai/hydra-zen): Pythonic utilities for working with Hydra. Dynamic config generation capabilities, enhanced config store features, a Python API for launching Hydra jobs, and more. +* [lightning-hydra-template](https://github.com/ashleve/lightning-hydra-template): user-friendly template combining Hydra with [Pytorch-Lightning](https://github.com/Lightning-AI/lightning) for ML experimentation. +* [hydra-torch](https://github.com/pytorch/hydra-torch): [configen](https://github.com/facebookresearch/hydra/tree/main/tools/configen)-generated configuration classes enabling type-safe PyTorch configuration for Hydra apps. +* NVIDIA's DeepLearningExamples repository contains a Hydra Launcher plugin, the [distributed_launcher](https://github.com/NVIDIA/DeepLearningExamples/tree/9c34e35c218514b8607d7cf381d8a982a01175e9/Tools/PyTorch/TimeSeriesPredictionPlatform/distributed_launcher), which makes use of the pytorch [distributed.launch](https://pytorch.org/docs/stable/distributed.html#launch-utility) API. + +#### Ask questions in Github Discussions or StackOverflow (Use the tag #fb-hydra or #omegaconf): +* [Github Discussions](https://github.com/facebookresearch/hydra/discussions) +* [StackOverflow](https://stackexchange.com/filters/391828/hydra-questions) +* [Twitter](https://twitter.com/Hydra_Framework) + +Check out the Meta AI [blog post](https://ai.facebook.com/blog/reengineering-facebook-ais-deep-learning-platforms-for-interoperability/) to learn about how Hydra fits into Meta's efforts to reengineer deep learning platforms for interoperability. + +### Citing Hydra +If you use Hydra in your research please use the following BibTeX entry: +```BibTeX +@Misc{Yadan2019Hydra, + author = {Omry Yadan}, + title = {Hydra - A framework for elegantly configuring complex applications}, + howpublished = {Github}, + year = {2019}, + url = {https://github.com/facebookresearch/hydra} +} +``` + diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/RECORD b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..265bfb62113a44b31fb072100c3d425022541948 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/RECORD @@ -0,0 +1,229 @@ +hydra/__init__.py,sha256=RfXj7duXieCLncBhvAP-dK_yiBX7AP1c5OT1ZJ4mzqQ,586 +hydra/__pycache__/__init__.cpython-312.pyc,, +hydra/__pycache__/compose.cpython-312.pyc,, +hydra/__pycache__/errors.cpython-312.pyc,, +hydra/__pycache__/initialize.cpython-312.pyc,, +hydra/__pycache__/main.cpython-312.pyc,, +hydra/__pycache__/types.cpython-312.pyc,, +hydra/__pycache__/utils.cpython-312.pyc,, +hydra/__pycache__/version.cpython-312.pyc,, +hydra/_internal/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/_internal/__pycache__/__init__.cpython-312.pyc,, +hydra/_internal/__pycache__/callbacks.cpython-312.pyc,, +hydra/_internal/__pycache__/config_loader_impl.cpython-312.pyc,, +hydra/_internal/__pycache__/config_repository.cpython-312.pyc,, +hydra/_internal/__pycache__/config_search_path_impl.cpython-312.pyc,, +hydra/_internal/__pycache__/defaults_list.cpython-312.pyc,, +hydra/_internal/__pycache__/deprecation_warning.cpython-312.pyc,, +hydra/_internal/__pycache__/hydra.cpython-312.pyc,, +hydra/_internal/__pycache__/sources_registry.cpython-312.pyc,, +hydra/_internal/__pycache__/utils.cpython-312.pyc,, +hydra/_internal/callbacks.py,sha256=8oihvw_Qgjl462wvC-51IymMlDw92vJ326WUhnIflH8,2310 +hydra/_internal/config_loader_impl.py,sha256=pfp4-GhTZUmQj33IvdqbllTEUDAd41mobB0aO7S4Aik,23925 +hydra/_internal/config_repository.py,sha256=xFZxs-OrN9EWT9gInHO-2RWIqv2VD02J74utekteEsU,13541 +hydra/_internal/config_search_path_impl.py,sha256=EZNyyd4bupjj6BZkRcG6Sf_lHrY6B-rZwS9Ggy1_7LU,3565 +hydra/_internal/core_plugins/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/_internal/core_plugins/__pycache__/__init__.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/bash_completion.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/basic_launcher.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/basic_sweeper.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/file_config_source.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/fish_completion.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/importlib_resources_config_source.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/structured_config_source.cpython-312.pyc,, +hydra/_internal/core_plugins/__pycache__/zsh_completion.cpython-312.pyc,, +hydra/_internal/core_plugins/bash_completion.py,sha256=Cat1tWgNyO2XCx2hmJ9ccT7igmAXnZd5tS0Kjd-yBuI,2957 +hydra/_internal/core_plugins/basic_launcher.py,sha256=pwa-Fkyguojr7EhL9rTM-JKSLASJ_VDwos4_W-OVux8,2755 +hydra/_internal/core_plugins/basic_sweeper.py,sha256=08K6gKtgb5XOStc4RgZ0Qi1w2eO4Q_DDIFmyQhgSigc,6580 +hydra/_internal/core_plugins/file_config_source.py,sha256=DXFmLksisy-lUK1FV8rkkww7C8CkSY3gymI6DVRtX3w,2317 +hydra/_internal/core_plugins/fish_completion.py,sha256=-koFBCRDZuUdqa_4sX6rNcHAo8e4VDLOyQmBtMHYpIM,2395 +hydra/_internal/core_plugins/importlib_resources_config_source.py,sha256=1hNPJ_Bx56qqaUhk9297iji5bOkdjUDOYL457GOmgyw,3686 +hydra/_internal/core_plugins/structured_config_source.py,sha256=Rfnn2JQEIrA5JWkT2WtpMLAl8xXVKVd_oaUduomippw,2348 +hydra/_internal/core_plugins/zsh_completion.py,sha256=QyJYgft0iFi5oCMA67b10N1v0DOzLypII5gPjIA-a5A,1564 +hydra/_internal/defaults_list.py,sha256=P8t0hgLaxeTKOyVJEZgdSdci3ojXhggl__aasNVEvF0,27080 +hydra/_internal/deprecation_warning.py,sha256=LnpqHkxTd-nCol4ZRsSsIWvmw3QmXW0640Q6AH76EmI,435 +hydra/_internal/grammar/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/_internal/grammar/__pycache__/__init__.cpython-312.pyc,, +hydra/_internal/grammar/__pycache__/functions.cpython-312.pyc,, +hydra/_internal/grammar/__pycache__/grammar_functions.cpython-312.pyc,, +hydra/_internal/grammar/__pycache__/utils.cpython-312.pyc,, +hydra/_internal/grammar/functions.py,sha256=qqH0PUgKCsTbucVB-HaJurm7kofhqKhXSYwMcD65hY0,2657 +hydra/_internal/grammar/grammar_functions.py,sha256=Tm41GXsVVRXr7t8PNAlvtuHPUTdYPXV32q04BfFdhOg,11797 +hydra/_internal/grammar/utils.py,sha256=yAjqmRXhub_TyUFLwRPWdIMqzvEBIgiX7mM-MnKaRlA,2133 +hydra/_internal/hydra.py,sha256=dLGZgMjrn-68mrF_yBcgoaCnZYbuHUWdr4Zwk4LDT4A,24147 +hydra/_internal/instantiate/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/_internal/instantiate/__pycache__/__init__.cpython-312.pyc,, +hydra/_internal/instantiate/__pycache__/_instantiate2.cpython-312.pyc,, +hydra/_internal/instantiate/_instantiate2.py,sha256=nk1NlHv-5M4uLfJunM_2sPIith5fTIIJb5Pl-irgv_M,14582 +hydra/_internal/sources_registry.py,sha256=a4rbFFdJjUWNJeqMqSq7XDI4gA4f4qcvZ40nsev3zro,1298 +hydra/_internal/utils.py,sha256=fXv__IqF6nHyO4IDfdYrAjgJw8yUb0_KUuwYt8AHRRs,22368 +hydra/compose.py,sha256=l1yF3TNFc3-7gzUYNO1DG6N2MO8hG5Yn0ibv22T8sAg,2105 +hydra/conf/__init__.py,sha256=SJas-v9d3FLB4MoY2_ZgixQH0z2hrTZCNcJ0SC4W5sA,5367 +hydra/conf/__pycache__/__init__.cpython-312.pyc,, +hydra/conf/hydra/env/default.yaml,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +hydra/conf/hydra/help/default.yaml,sha256=AUD1lPqLfdy2r53PCTFHNUuowx9jJMIRbC4lgvHCbH8,849 +hydra/conf/hydra/hydra_help/default.yaml,sha256=ze_nZtRYnL9NbKsyVuZPMlOopBCA_KhA4Ef0yzzh_Wo,642 +hydra/conf/hydra/hydra_logging/default.yaml,sha256=MeOAlUeXmwvu_CuhjQ9VxAFMjeopDm8_9ra2vp-B3BA,306 +hydra/conf/hydra/hydra_logging/disabled.yaml,sha256=mRf0I709p7OCmm0y5QTxMKwQumK13Ma-N4VmTXe_yu4,63 +hydra/conf/hydra/hydra_logging/hydra_debug.yaml,sha256=xA2oHZaKsrhjeMq7w1KWOnGdQeIhAxyh_qFO_sPZ8BQ,453 +hydra/conf/hydra/hydra_logging/none.yaml,sha256=gSCRtxF28DB3-gedm1zek7kiN8kyaNYD_m6tRJUaol4,54 +hydra/conf/hydra/job_logging/default.yaml,sha256=7fW0NU3vyIKV6HbtiLuCLCT0gtk3y-QXgwBsCPW2ooA,477 +hydra/conf/hydra/job_logging/disabled.yaml,sha256=mRf0I709p7OCmm0y5QTxMKwQumK13Ma-N4VmTXe_yu4,63 +hydra/conf/hydra/job_logging/none.yaml,sha256=gSCRtxF28DB3-gedm1zek7kiN8kyaNYD_m6tRJUaol4,54 +hydra/conf/hydra/job_logging/stdout.yaml,sha256=7hHFp_oMHxrMKILBbc2fJySl_7y2u_9RbEentTs2zRY,280 +hydra/conf/hydra/output/default.yaml,sha256=reeuSYxBy0_oqnzUM9sSULVAzjb8p7IsxJBHUccxtD8,152 +hydra/core/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/core/__pycache__/__init__.cpython-312.pyc,, +hydra/core/__pycache__/config_loader.cpython-312.pyc,, +hydra/core/__pycache__/config_search_path.cpython-312.pyc,, +hydra/core/__pycache__/config_store.cpython-312.pyc,, +hydra/core/__pycache__/default_element.cpython-312.pyc,, +hydra/core/__pycache__/global_hydra.cpython-312.pyc,, +hydra/core/__pycache__/hydra_config.cpython-312.pyc,, +hydra/core/__pycache__/object_type.cpython-312.pyc,, +hydra/core/__pycache__/plugins.cpython-312.pyc,, +hydra/core/__pycache__/singleton.cpython-312.pyc,, +hydra/core/__pycache__/utils.cpython-312.pyc,, +hydra/core/config_loader.py,sha256=Tad4xnUwFilgY26eDyW2ufKTfH3unABQRyZf3GHlVAc,1577 +hydra/core/config_search_path.py,sha256=VGfSUlZTuE1XzMFoTluk6TflRWilMC237c3HIuDZa5U,2070 +hydra/core/config_store.py,sha256=jricEy6sBv-IfOxBrv4oYxHR1Afl9aAfiiqdtcoFaN0,4609 +hydra/core/default_element.py,sha256=dWnHKVU7L9C2n0uQevrgpXnGXG3nGPrw8yFACFujyrA,18196 +hydra/core/global_hydra.py,sha256=iEap-YFkxNhkbjuu5vElm7-nWpAmyB9x8Yk420YFsOc,1324 +hydra/core/hydra_config.py,sha256=H6kHPrsG8Cuyd8f4vvrWhqS4RTW1RcK-pdSUodPJnPI,1561 +hydra/core/object_type.py,sha256=usNw3bC9dhY0cNCRgjd0V8rKka2KswBDukSWGM9uVgk,166 +hydra/core/override_parser/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/core/override_parser/__pycache__/__init__.cpython-312.pyc,, +hydra/core/override_parser/__pycache__/overrides_parser.cpython-312.pyc,, +hydra/core/override_parser/__pycache__/overrides_visitor.cpython-312.pyc,, +hydra/core/override_parser/__pycache__/types.cpython-312.pyc,, +hydra/core/override_parser/overrides_parser.py,sha256=nK8k8aDznA6zozWdSih8KIJN5qKUJadFLuW8SqQveno,4720 +hydra/core/override_parser/overrides_visitor.py,sha256=Mz3LJfUUMad5oDYPvJ4ikd3VF2g6SwpWF1-HknxAUUM,15505 +hydra/core/override_parser/types.py,sha256=1Yn1g1tap6uw4NdSr4nwMDwoqkQ3TCBUkyy1Bk6CELc,15969 +hydra/core/plugins.py,sha256=uwNG8A-68rAHUybO2rPimnmn94JTRU4FxfrQAgS3vr0,10390 +hydra/core/singleton.py,sha256=JFVdknkZ57Q91clfnvNUjOL0k85ksOXfTgFozBjbwTk,1338 +hydra/core/utils.py,sha256=vetFUh9jAa-Zfx-XetioCKcSDf7jk4mJkVSY8sjMONg,10502 +hydra/errors.py,sha256=UUYsCUnmruoxXJ4rdEZzEEhGlmO0XpmitPV52rWgCj4,1071 +hydra/experimental/__init__.py,sha256=LXsinWfSh6NWcg5ykYlh39w6YP4K0eTL66enyb5msx4,293 +hydra/experimental/__pycache__/__init__.cpython-312.pyc,, +hydra/experimental/__pycache__/callback.cpython-312.pyc,, +hydra/experimental/__pycache__/callbacks.cpython-312.pyc,, +hydra/experimental/__pycache__/compose.cpython-312.pyc,, +hydra/experimental/__pycache__/initialize.cpython-312.pyc,, +hydra/experimental/callback.py,sha256=C81NmVIkrO_x_Hx6cP9Gk2Bha1eZUZcUFqQ7h5jt5Lw,2378 +hydra/experimental/callbacks.py,sha256=hNeJHD6P97RCuWKSdh2PQM_0RAnTApWS6-5itREpWQY,2336 +hydra/experimental/compose.py,sha256=1R8-RGoR8ShhL6XFOgSjtoYsMw2X3x99fOsER13JspY,845 +hydra/experimental/initialize.py,sha256=qRJgHq3ny53fWyMg2WRRs6mTVMJveh-uDafNOtd-sKE,4280 +hydra/extra/__pycache__/pytest_plugin.cpython-312.pyc,, +hydra/extra/pytest_plugin.py,sha256=XwdmKS_Xat8PgtXcZGsLECC_KV17SlWB5HIjgytEwlQ,2612 +hydra/grammar/.gitignore,sha256=JvbRQEPLotalz9jq9ech5OCzehPqN1O-hKph7r5X0X8,21 +hydra/grammar/OverrideLexer.g4,sha256=SLf4ErlQqLhuqYcxm1-csIdcu-60bvVxSpiZ5EVnlEY,2825 +hydra/grammar/OverrideParser.g4,sha256=3_p5QSlZ8KloLGKQecC0_rZlFGe6t3cfLQz-EMHwiB8,3115 +hydra/grammar/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/grammar/__pycache__/__init__.cpython-312.pyc,, +hydra/grammar/gen/.gitignore,sha256=vdSMzqaxj4aI7cH5OV3jvNZV3zoOSCfHoloOw1mjc1g,15 +hydra/grammar/gen/OverrideLexer.interp,sha256=CAB_gEC1QNK8Z2PWuVfqdtJ2JB8UohDbFU9gIOCgJi8,14138 +hydra/grammar/gen/OverrideLexer.py,sha256=QnpWqy5IwvVEwj6lUMtCQNOX7TTAxyuIiViIQpcb3n4,16474 +hydra/grammar/gen/OverrideLexer.tokens,sha256=ACZgg3CkJwkQxl_n0s6d_3rRUzkbHEchRf7FHa2xZoQ,289 +hydra/grammar/gen/OverrideParser.interp,sha256=Xw3O4PVsBEG721C5fZHbRaNDXYYnNucMfYBnlh6nipI,5685 +hydra/grammar/gen/OverrideParser.py,sha256=EUpl4DORSkb_uOk40yISotNgzm9PBmc4D37KcOurmPU,50516 +hydra/grammar/gen/OverrideParser.tokens,sha256=ACZgg3CkJwkQxl_n0s6d_3rRUzkbHEchRf7FHa2xZoQ,289 +hydra/grammar/gen/OverrideParserListener.py,sha256=ebXxzEWA3YV3Z6duMMb4OljCOSSpR2gGhWztc8IL-iM,4476 +hydra/grammar/gen/OverrideParserVisitor.py,sha256=N6Ga-PNK5KM0s9YLPXO07k0dCk-2r5kUMUzh0ulBpeM,2834 +hydra/grammar/gen/__pycache__/OverrideLexer.cpython-312.pyc,, +hydra/grammar/gen/__pycache__/OverrideParser.cpython-312.pyc,, +hydra/grammar/gen/__pycache__/OverrideParserListener.cpython-312.pyc,, +hydra/grammar/gen/__pycache__/OverrideParserVisitor.cpython-312.pyc,, +hydra/initialize.py,sha256=HgB87jmyNJwImdGQ1xyw_B1z_Hd8QsIwEUFWOBgy6Q4,6035 +hydra/main.py,sha256=t6_RYPzn-nrp_6Rae3dVxONXVu4OVgNNtS9q2OKLcOA,3999 +hydra/plugins/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/plugins/__pycache__/__init__.cpython-312.pyc,, +hydra/plugins/__pycache__/completion_plugin.cpython-312.pyc,, +hydra/plugins/__pycache__/config_source.cpython-312.pyc,, +hydra/plugins/__pycache__/launcher.cpython-312.pyc,, +hydra/plugins/__pycache__/plugin.cpython-312.pyc,, +hydra/plugins/__pycache__/search_path_plugin.cpython-312.pyc,, +hydra/plugins/__pycache__/sweeper.cpython-312.pyc,, +hydra/plugins/completion_plugin.py,sha256=_1VjimIuA0QDJm_LI98SoOPpi_L6Oad8ljP5FRbAU-I,11275 +hydra/plugins/config_source.py,sha256=W1E60f-J18e_29G6PV32P-MlWAY438uZGbjMkQHMtHQ,5109 +hydra/plugins/launcher.py,sha256=v1ojrXmKmG69lbubCppepJt6URDJwFnhO4gTTZuo6BM,974 +hydra/plugins/plugin.py,sha256=eTvzaLxlJCmbMbroP9Z1u8wxNWa4R0qPAGqLzh6WM7M,120 +hydra/plugins/search_path_plugin.py,sha256=bn78U0cxqP2QZUkCh23LbtR0rDthewm8iOCGfv5gcF8,333 +hydra/plugins/sweeper.py,sha256=J6fVEpbiiDxHCLadLX1wDX3484oxYoDv0q0Jv9TNfaY,2108 +hydra/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +hydra/test_utils/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/test_utils/__pycache__/__init__.cpython-312.pyc,, +hydra/test_utils/__pycache__/a_module.cpython-312.pyc,, +hydra/test_utils/__pycache__/completion.cpython-312.pyc,, +hydra/test_utils/__pycache__/config_source_common_tests.cpython-312.pyc,, +hydra/test_utils/__pycache__/example_app.cpython-312.pyc,, +hydra/test_utils/__pycache__/launcher_common_tests.cpython-312.pyc,, +hydra/test_utils/__pycache__/test_utils.cpython-312.pyc,, +hydra/test_utils/a_module.py,sha256=QHSQjj55BP3g0uz7ESTGNn_p6TJirYdFer8Xbh5M6Wg,228 +hydra/test_utils/completion.py,sha256=ctgyUAoLRKQ05BrNweexBvA-9aeITu1HrUFAtfIrCi0,344 +hydra/test_utils/config_source_common_tests.py,sha256=zWi3KaWhEJ76EnN-5Q6qiuoNvqUpM5LlbzvgOJI1YLk,10900 +hydra/test_utils/configs/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/test_utils/configs/__pycache__/__init__.cpython-312.pyc,, +hydra/test_utils/configs/accessing_hydra_config.yaml,sha256=f8yFOBhVJ3I0hga2uDxi-xHk7QUqIuYozrOIkrvh4G8,92 +hydra/test_utils/configs/completion_test/additional_searchpath.yaml,sha256=RGca4IOnI2g0ha3W29uMBrw4uKKaaAu-r43SFKpb3JY,201 +hydra/test_utils/configs/completion_test/config.yaml,sha256=onD8qwP45YO6uUiaNK6sdQYteWtCeu6stg_JUxWc4Zs,276 +hydra/test_utils/configs/completion_test/group/dict.yaml,sha256=oWGInDFSV2mNHsuy5WaltWR-0jzJr5OsgVvdx6AxgS8,117 +hydra/test_utils/configs/completion_test/group/list.yaml,sha256=2-PX667W1Zto3zIrEvYD4UTH9jEtWR6FEIthukyiiRs,106 +hydra/test_utils/configs/completion_test/hydra/launcher/fairtask.yaml,sha256=5d7flmlKaueWrLwxJRrly8h8Yu14z-zmEH6oVcUAB6w,44 +hydra/test_utils/configs/completion_test/missing_default.yaml,sha256=BXNHsVCvz997Bd1JV43lhwlzYOGDnGA7hcA5AGcXMks,25 +hydra/test_utils/configs/completion_test/test_hydra/launcher/fairtask.yaml,sha256=5d7flmlKaueWrLwxJRrly8h8Yu14z-zmEH6oVcUAB6w,44 +hydra/test_utils/configs/completion_test_additional_file/additional_group/file_opt_additional.yaml,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +hydra/test_utils/configs/completion_test_additional_file/group/file_opt.yaml,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +hydra/test_utils/configs/completion_test_additional_package/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/test_utils/configs/completion_test_additional_package/__pycache__/__init__.cpython-312.pyc,, +hydra/test_utils/configs/completion_test_additional_package/additional_group/pkg_opt_additional.yaml,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +hydra/test_utils/configs/completion_test_additional_package/group/pkg_opt.yaml,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +hydra/test_utils/configs/compose.yaml,sha256=PbvagKNJBdD8K9iV5kHd1k0wSYUPxfCjTv5rlkpiAwY,66 +hydra/test_utils/configs/conf.zip,sha256=XEcej6nwGh_GVQdJliLaZt_yvpbxv40AlH8UMyJwpLs,210 +hydra/test_utils/configs/config.yaml,sha256=jvSKJD57W9fusuDdeWzGMmEkue2eB4Y8z67YK4R1fo0,45 +hydra/test_utils/configs/config.yml,sha256=OXO4U6morVmVmXOIP1_09a7VaWKWLK_8itBFpdBIXLY,55 +hydra/test_utils/configs/custom_resolver.yaml,sha256=1vVJqYjuhrLZljWaZSiRldUNIclX01dup0C-wfwXhnk,26 +hydra/test_utils/configs/db/mysql.yaml,sha256=OhvOLGF11LrYqD7F4hElfJDGWrRAiN2P5FzzebYvgWM,42 +hydra/test_utils/configs/db/postgresql.yaml,sha256=YLxrF76CCl4ezdCkxnVAH2xHS6w_1-R2pko748n7B_c,70 +hydra/test_utils/configs/db/validated_mysql.yaml,sha256=4t357FDiODkD7eY1YveNsbuiLpl6tLnh3zQH9viHCYk,68 +hydra/test_utils/configs/db/validated_postgresql.yaml,sha256=NaMWjp4CC_M2Ef5njP0g-5F7docESNDRJ9q66Rig0G8,101 +hydra/test_utils/configs/db_conf.yaml,sha256=EwJbm3o9wfYfPc5WdU6anorcatikENpMSOrLYMSPe5c,24 +hydra/test_utils/configs/defaults_not_list.yaml,sha256=TGijnGK1kGosfiL11q6QCBaOd1h5AoYqRwW4rm4srY4,41 +hydra/test_utils/configs/group1/abc.cde.yaml,sha256=38OuMSH0NPr_GHZLyRZj_MKQ3Eh6DkmimFSH66_3Y8E,28 +hydra/test_utils/configs/group1/file1.yaml,sha256=YQt7eI9ChNBTwhWz6TaMal5wEbrEwYIHx65Vy1eJoPU,28 +hydra/test_utils/configs/group1/file2.yaml,sha256=wAju0MHYv7R9IrF4MukME4pqGq0TsEddGfu1mghEOE8,28 +hydra/test_utils/configs/group2/file1.yaml,sha256=1nGQpv2YZPZBARi-PBsBxM9USDisHC9gS3idm1xxU4c,29 +hydra/test_utils/configs/group2/file2.yaml,sha256=CxJUCyfUgvv129J-CuEQobot0H0Y0W9yq_hf7fjdcSk,29 +hydra/test_utils/configs/missing-default.yaml,sha256=h_tYW2f9FHU194574y4nW1eTcOqRJ2NNFdWWD74Ztb8,25 +hydra/test_utils/configs/missing-optional-default.yaml,sha256=SnHTJeh9op11czTFCIoMFwCci9G3Wtr6S-1DQAHqxbs,36 +hydra/test_utils/configs/missing_init_py/.gitignore,sha256=kCpRPdl3S_jqYYZaOrc0-xa6-l3KqVjNRXc6jCkd_-Q,12 +hydra/test_utils/configs/missing_init_py/test.yaml,sha256=RPxWgmo0Tv8QFgW5AMXByB91h7259MlDoTZKqrWso-I,6 +hydra/test_utils/configs/optional-default.yaml,sha256=jwH3O7Wn5fTdDYpXzCMFxSY8KEkU2bJPSZ3d_wLaF3Y,37 +hydra/test_utils/configs/overriding_output_dir.yaml,sha256=30luCOSutKoCnSKOf0ixoUkRagpUejbserz4VH5mEgk,27 +hydra/test_utils/configs/overriding_run_dir.yaml,sha256=qkstQzIBVkqOJFlziQdurKeNUshx3WoJZG13WsVg1js,27 +hydra/test_utils/configs/package_tests/__init__.py,sha256=nlNcRa8JrCTvjVYxoVH3f-uv5yqSrWv-stlB8MSlTjU,71 +hydra/test_utils/configs/package_tests/__pycache__/__init__.cpython-312.pyc,, +hydra/test_utils/configs/package_tests/group1/option1.yaml,sha256=IvqLmZEXrlkuj0ZTGo5NzPGfi2UxXKUAmKx_xVlpHt4,41 +hydra/test_utils/configs/package_tests/group1/option2.yaml,sha256=ZY-wEvZgZ9nQwB8oytNd_0uzgoxqUk7sza5f1PC4RLI,41 +hydra/test_utils/configs/package_tests/group2/option1.yaml,sha256=mPUhhwInAsKJEA1Z9laGXcbi8y36vPlkqP9LTexQwwc,41 +hydra/test_utils/configs/package_tests/group2/option2.yaml,sha256=LLBCZrMTnfsAFNaG2uOORaHm8lmbMWKtTzDpQFDkNdw,41 +hydra/test_utils/configs/package_tests/pkg_override.yaml,sha256=K7UZYvrYuPJnvVbC6ukhJDWvoQfSV84l3iUFWXs1Psw,55 +hydra/test_utils/configs/package_tests/two_packages_one_group.yaml,sha256=D8qyM20PXYvYC43lokYet8WdknJG-itUnYfDD9okWRI,60 +hydra/test_utils/configs/schema_key_error.yaml,sha256=BgPV_otZ8OxZfcn3xvSquLGdxM7f44KWNPJ2jFcxafU,56 +hydra/test_utils/configs/schema_validation_error.yaml,sha256=T61LUtehGtAMU_t44J9btkD6vxjDikdNGWcS2AKGHjY,54 +hydra/test_utils/configs/some_config.yaml,sha256=WfxBETosvbSbpDYGusT2KQk2wgHOaCo0WaXBGUzU3oI,38 +hydra/test_utils/configs/top_level_list/file1.yaml,sha256=JPFXvrO7aYFybvktEExKoefg40ux6Eo7IzoCCpY9_VM,4 +hydra/test_utils/configs/unspecified_mandatory_default.yaml,sha256=UOFn7b-MBSvyuuAoco3t3uEHDMWiTxgM5-iOGhcVejQ,26 +hydra/test_utils/example_app.py,sha256=EeviU2MudEMera8AfGJ1wQ5WyWqwu6NQ7GF4KvVpzFo,323 +hydra/test_utils/launcher_common_tests.py,sha256=JE-a9e6QzzwIEwGBCxn501HTOvQOl1054CzgL8bOUiw,23552 +hydra/test_utils/test_utils.py,sha256=jL_MWw3nuII4JrS_GOoPHD0OFcgpx2ezmAAy2aSD7hU,15335 +hydra/types.py,sha256=ek7sEeAiaDpkVmndhHFUXSQIJnVKi4IqUf-JYhy86xY,2913 +hydra/utils.py,sha256=IIILg5TmAZi4F_if49eliLZ3SOxY95ey5wKQ_DPGAs0,3272 +hydra/version.py,sha256=07N_T8N48zL9VAifYpP39T2UZ_U15ttnlysdGWDKoh4,2573 +hydra_core-1.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +hydra_core-1.3.2.dist-info/LICENSE,sha256=UkEte8fOQVfqYou6rLiCngqcs8WPV_mRdhJryM8r_IU,1086 +hydra_core-1.3.2.dist-info/METADATA,sha256=OZBGy_mufrq439AJ4rT3SCEscQoOdcpQGnK7stRW4uc,5480 +hydra_core-1.3.2.dist-info/RECORD,, +hydra_core-1.3.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +hydra_core-1.3.2.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92 +hydra_core-1.3.2.dist-info/entry_points.txt,sha256=rDwQ60t46fQ9gkvlsjN-RvQcJdbDUhRdSxPANxU_32E,52 +hydra_core-1.3.2.dist-info/top_level.txt,sha256=izgzyEMiRL3xiwDnTKYJY7UL0mWcGbI7tqJ9o3FMbQI,6 diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/REQUESTED b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..57e3d840d59a650ac5bccbad5baeec47d155f0ad --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.38.4) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..9fdfdc88316d9a34270bff43520752ae1a06f636 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[pytest11] +hydra_pytest = hydra.extra.pytest_plugin diff --git a/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/top_level.txt b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..83f02065ddfc215f8f31d8b9c7fbdf33aa6031b4 --- /dev/null +++ b/python_embeded/Lib/site-packages/hydra_core-1.3.2.dist-info/top_level.txt @@ -0,0 +1 @@ +hydra diff --git a/python_embeded/Lib/site-packages/idna-3.10.dist-info/INSTALLER b/python_embeded/Lib/site-packages/idna-3.10.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna-3.10.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/idna-3.10.dist-info/LICENSE.md b/python_embeded/Lib/site-packages/idna-3.10.dist-info/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..19b6b45242c16a1025465309eec2ca5009319de3 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna-3.10.dist-info/LICENSE.md @@ -0,0 +1,31 @@ +BSD 3-Clause License + +Copyright (c) 2013-2024, Kim Davies and contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/python_embeded/Lib/site-packages/idna-3.10.dist-info/METADATA b/python_embeded/Lib/site-packages/idna-3.10.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c42623e9423c23b555d9d352bc5dab518ede02c2 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna-3.10.dist-info/METADATA @@ -0,0 +1,250 @@ +Metadata-Version: 2.1 +Name: idna +Version: 3.10 +Summary: Internationalized Domain Names in Applications (IDNA) +Author-email: Kim Davies +Requires-Python: >=3.6 +Description-Content-Type: text/x-rst +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: System Administrators +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: Name Service (DNS) +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Utilities +Requires-Dist: ruff >= 0.6.2 ; extra == "all" +Requires-Dist: mypy >= 1.11.2 ; extra == "all" +Requires-Dist: pytest >= 8.3.2 ; extra == "all" +Requires-Dist: flake8 >= 7.1.1 ; extra == "all" +Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.rst +Project-URL: Issue tracker, https://github.com/kjd/idna/issues +Project-URL: Source, https://github.com/kjd/idna +Provides-Extra: all + +Internationalized Domain Names in Applications (IDNA) +===================================================== + +Support for the Internationalized Domain Names in +Applications (IDNA) protocol as specified in `RFC 5891 +`_. This is the latest version of +the protocol and is sometimes referred to as “IDNA 2008”. + +This library also provides support for Unicode Technical +Standard 46, `Unicode IDNA Compatibility Processing +`_. + +This acts as a suitable replacement for the “encodings.idna” +module that comes with the Python standard library, but which +only supports the older superseded IDNA specification (`RFC 3490 +`_). + +Basic functions are simply executed: + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('ドメイン.テスト') + b'xn--eckwd4c7c.xn--zckzah' + >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) + ドメイン.テスト + + +Installation +------------ + +This package is available for installation from PyPI: + +.. code-block:: bash + + $ python3 -m pip install idna + + +Usage +----- + +For typical usage, the ``encode`` and ``decode`` functions will take a +domain name argument and perform a conversion to A-labels or U-labels +respectively. + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('ドメイン.テスト') + b'xn--eckwd4c7c.xn--zckzah' + >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) + ドメイン.テスト + +You may use the codec encoding and decoding methods using the +``idna.codec`` module: + +.. code-block:: pycon + + >>> import idna.codec + >>> print('домен.испытание'.encode('idna2008')) + b'xn--d1acufc.xn--80akhbyknj4f' + >>> print(b'xn--d1acufc.xn--80akhbyknj4f'.decode('idna2008')) + домен.испытание + +Conversions can be applied at a per-label basis using the ``ulabel`` or +``alabel`` functions if necessary: + +.. code-block:: pycon + + >>> idna.alabel('测试') + b'xn--0zwm56d' + +Compatibility Mapping (UTS #46) ++++++++++++++++++++++++++++++++ + +As described in `RFC 5895 `_, the +IDNA specification does not normalize input from different potential +ways a user may input a domain name. This functionality, known as +a “mapping”, is considered by the specification to be a local +user-interface issue distinct from IDNA conversion functionality. + +This library provides one such mapping that was developed by the +Unicode Consortium. Known as `Unicode IDNA Compatibility Processing +`_, it provides for both a regular +mapping for typical applications, as well as a transitional mapping to +help migrate from older IDNA 2003 applications. Strings are +preprocessed according to Section 4.4 “Preprocessing for IDNA2008” +prior to the IDNA operations. + +For example, “Königsgäßchen” is not a permissible label as *LATIN +CAPITAL LETTER K* is not allowed (nor are capital letters in general). +UTS 46 will convert this into lower case prior to applying the IDNA +conversion. + +.. code-block:: pycon + + >>> import idna + >>> idna.encode('Königsgäßchen') + ... + idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed + >>> idna.encode('Königsgäßchen', uts46=True) + b'xn--knigsgchen-b4a3dun' + >>> print(idna.decode('xn--knigsgchen-b4a3dun')) + königsgäßchen + +Transitional processing provides conversions to help transition from +the older 2003 standard to the current standard. For example, in the +original IDNA specification, the *LATIN SMALL LETTER SHARP S* (ß) was +converted into two *LATIN SMALL LETTER S* (ss), whereas in the current +IDNA specification this conversion is not performed. + +.. code-block:: pycon + + >>> idna.encode('Königsgäßchen', uts46=True, transitional=True) + 'xn--knigsgsschen-lcb0w' + +Implementers should use transitional processing with caution, only in +rare cases where conversion from legacy labels to current labels must be +performed (i.e. IDNA implementations that pre-date 2008). For typical +applications that just need to convert labels, transitional processing +is unlikely to be beneficial and could produce unexpected incompatible +results. + +``encodings.idna`` Compatibility +++++++++++++++++++++++++++++++++ + +Function calls from the Python built-in ``encodings.idna`` module are +mapped to their IDNA 2008 equivalents using the ``idna.compat`` module. +Simply substitute the ``import`` clause in your code to refer to the new +module name. + +Exceptions +---------- + +All errors raised during the conversion following the specification +should raise an exception derived from the ``idna.IDNAError`` base +class. + +More specific exceptions that may be generated as ``idna.IDNABidiError`` +when the error reflects an illegal combination of left-to-right and +right-to-left characters in a label; ``idna.InvalidCodepoint`` when +a specific codepoint is an illegal character in an IDN label (i.e. +INVALID); and ``idna.InvalidCodepointContext`` when the codepoint is +illegal based on its positional context (i.e. it is CONTEXTO or CONTEXTJ +but the contextual requirements are not satisfied.) + +Building and Diagnostics +------------------------ + +The IDNA and UTS 46 functionality relies upon pre-calculated lookup +tables for performance. These tables are derived from computing against +eligibility criteria in the respective standards. These tables are +computed using the command-line script ``tools/idna-data``. + +This tool will fetch relevant codepoint data from the Unicode repository +and perform the required calculations to identify eligibility. There are +three main modes: + +* ``idna-data make-libdata``. Generates ``idnadata.py`` and + ``uts46data.py``, the pre-calculated lookup tables used for IDNA and + UTS 46 conversions. Implementers who wish to track this library against + a different Unicode version may use this tool to manually generate a + different version of the ``idnadata.py`` and ``uts46data.py`` files. + +* ``idna-data make-table``. Generate a table of the IDNA disposition + (e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix + B.1 of RFC 5892 and the pre-computed tables published by `IANA + `_. + +* ``idna-data U+0061``. Prints debugging output on the various + properties associated with an individual Unicode codepoint (in this + case, U+0061), that are used to assess the IDNA and UTS 46 status of a + codepoint. This is helpful in debugging or analysis. + +The tool accepts a number of arguments, described using ``idna-data +-h``. Most notably, the ``--version`` argument allows the specification +of the version of Unicode to be used in computing the table data. For +example, ``idna-data --version 9.0.0 make-libdata`` will generate +library data against Unicode 9.0.0. + + +Additional Notes +---------------- + +* **Packages**. The latest tagged release version is published in the + `Python Package Index `_. + +* **Version support**. This library supports Python 3.6 and higher. + As this library serves as a low-level toolkit for a variety of + applications, many of which strive for broad compatibility with older + Python versions, there is no rush to remove older interpreter support. + Removing support for older versions should be well justified in that the + maintenance burden has become too high. + +* **Python 2**. Python 2 is supported by version 2.x of this library. + Use "idna<3" in your requirements file if you need this library for + a Python 2 application. Be advised that these versions are no longer + actively developed. + +* **Testing**. The library has a test suite based on each rule of the + IDNA specification, as well as tests that are provided as part of the + Unicode Technical Standard 46, `Unicode IDNA Compatibility Processing + `_. + +* **Emoji**. It is an occasional request to support emoji domains in + this library. Encoding of symbols like emoji is expressly prohibited by + the technical standard IDNA 2008 and emoji domains are broadly phased + out across the domain industry due to associated security risks. For + now, applications that need to support these non-compliant labels + may wish to consider trying the encode/decode operation in this library + first, and then falling back to using `encodings.idna`. See `the Github + project `_ for more discussion. + diff --git a/python_embeded/Lib/site-packages/idna-3.10.dist-info/RECORD b/python_embeded/Lib/site-packages/idna-3.10.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..3e137414d8471736227ba6f360d41931d498ef0e --- /dev/null +++ b/python_embeded/Lib/site-packages/idna-3.10.dist-info/RECORD @@ -0,0 +1,24 @@ +idna-3.10.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +idna-3.10.dist-info/LICENSE.md,sha256=pZ8LDvNjWHQQmkRhykT_enDVBpboFHZ7-vch1Mmw2w8,1541 +idna-3.10.dist-info/METADATA,sha256=URR5ZyDfQ1PCEGhkYoojqfi2Ra0tau2--lhwG4XSfjI,10158 +idna-3.10.dist-info/RECORD,, +idna-3.10.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +idna-3.10.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +idna-3.10.dist-info/direct_url.json,sha256=hlV2OPTEBqRnywB2tYpkzJyaET_5pKllJRnyTv2bSLk,267 +idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868 +idna/__pycache__/__init__.cpython-312.pyc,, +idna/__pycache__/codec.cpython-312.pyc,, +idna/__pycache__/compat.cpython-312.pyc,, +idna/__pycache__/core.cpython-312.pyc,, +idna/__pycache__/idnadata.cpython-312.pyc,, +idna/__pycache__/intranges.cpython-312.pyc,, +idna/__pycache__/package_data.cpython-312.pyc,, +idna/__pycache__/uts46data.cpython-312.pyc,, +idna/codec.py,sha256=PEew3ItwzjW4hymbasnty2N2OXvNcgHB-JjrBuxHPYY,3422 +idna/compat.py,sha256=RzLy6QQCdl9784aFhb2EX9EKGCJjg0P3PilGdeXXcx8,316 +idna/core.py,sha256=YJYyAMnwiQEPjVC4-Fqu_p4CJ6yKKuDGmppBNQNQpFs,13239 +idna/idnadata.py,sha256=W30GcIGvtOWYwAjZj4ZjuouUutC6ffgNuyjJy7fZ-lo,78306 +idna/intranges.py,sha256=amUtkdhYcQG8Zr-CoMM_kVRacxkivC1WgxN1b63KKdU,1898 +idna/package_data.py,sha256=q59S3OXsc5VI8j6vSD0sGBMyk6zZ4vWFREE88yCJYKs,21 +idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +idna/uts46data.py,sha256=rt90K9J40gUSwppDPCrhjgi5AA6pWM65dEGRSf6rIhM,239289 diff --git a/python_embeded/Lib/site-packages/idna-3.10.dist-info/REQUESTED b/python_embeded/Lib/site-packages/idna-3.10.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/idna-3.10.dist-info/WHEEL b/python_embeded/Lib/site-packages/idna-3.10.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..3b5e64b5e6c4a210201d1676a891fd57b15cda99 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna-3.10.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.9.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/python_embeded/Lib/site-packages/idna-3.10.dist-info/direct_url.json b/python_embeded/Lib/site-packages/idna-3.10.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..456b32fd6d8b3b53ea546c005c1435440c2fe228 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna-3.10.dist-info/direct_url.json @@ -0,0 +1 @@ +{"archive_info": {"hash": "sha256=946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", "hashes": {"sha256": "946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3"}}, "url": "file:///C:/a/ComfyUI/cu128_python_deps/idna-3.10-py3-none-any.whl"} \ No newline at end of file diff --git a/python_embeded/Lib/site-packages/idna/__init__.py b/python_embeded/Lib/site-packages/idna/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cfdc030a751b089fc7e38fc88093b791605d501d --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/__init__.py @@ -0,0 +1,45 @@ +from .core import ( + IDNABidiError, + IDNAError, + InvalidCodepoint, + InvalidCodepointContext, + alabel, + check_bidi, + check_hyphen_ok, + check_initial_combiner, + check_label, + check_nfc, + decode, + encode, + ulabel, + uts46_remap, + valid_contextj, + valid_contexto, + valid_label_length, + valid_string_length, +) +from .intranges import intranges_contain +from .package_data import __version__ + +__all__ = [ + "__version__", + "IDNABidiError", + "IDNAError", + "InvalidCodepoint", + "InvalidCodepointContext", + "alabel", + "check_bidi", + "check_hyphen_ok", + "check_initial_combiner", + "check_label", + "check_nfc", + "decode", + "encode", + "intranges_contain", + "ulabel", + "uts46_remap", + "valid_contextj", + "valid_contexto", + "valid_label_length", + "valid_string_length", +] diff --git a/python_embeded/Lib/site-packages/idna/codec.py b/python_embeded/Lib/site-packages/idna/codec.py new file mode 100644 index 0000000000000000000000000000000000000000..913abfd6a23ce547f84de2adc41221012f1007d6 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/codec.py @@ -0,0 +1,122 @@ +import codecs +import re +from typing import Any, Optional, Tuple + +from .core import IDNAError, alabel, decode, encode, ulabel + +_unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]") + + +class Codec(codecs.Codec): + def encode(self, data: str, errors: str = "strict") -> Tuple[bytes, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return b"", 0 + + return encode(data), len(data) + + def decode(self, data: bytes, errors: str = "strict") -> Tuple[str, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return "", 0 + + return decode(data), len(data) + + +class IncrementalEncoder(codecs.BufferedIncrementalEncoder): + def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[bytes, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return b"", 0 + + labels = _unicode_dots_re.split(data) + trailing_dot = b"" + if labels: + if not labels[-1]: + trailing_dot = b"." + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = b"." + + result = [] + size = 0 + for label in labels: + result.append(alabel(label)) + if size: + size += 1 + size += len(label) + + # Join with U+002E + result_bytes = b".".join(result) + trailing_dot + size += len(trailing_dot) + return result_bytes, size + + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, data: Any, errors: str, final: bool) -> Tuple[str, int]: + if errors != "strict": + raise IDNAError('Unsupported error handling "{}"'.format(errors)) + + if not data: + return ("", 0) + + if not isinstance(data, str): + data = str(data, "ascii") + + labels = _unicode_dots_re.split(data) + trailing_dot = "" + if labels: + if not labels[-1]: + trailing_dot = "." + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = "." + + result = [] + size = 0 + for label in labels: + result.append(ulabel(label)) + if size: + size += 1 + size += len(label) + + result_str = ".".join(result) + trailing_dot + size += len(trailing_dot) + return (result_str, size) + + +class StreamWriter(Codec, codecs.StreamWriter): + pass + + +class StreamReader(Codec, codecs.StreamReader): + pass + + +def search_function(name: str) -> Optional[codecs.CodecInfo]: + if name != "idna2008": + return None + return codecs.CodecInfo( + name=name, + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamwriter=StreamWriter, + streamreader=StreamReader, + ) + + +codecs.register(search_function) diff --git a/python_embeded/Lib/site-packages/idna/compat.py b/python_embeded/Lib/site-packages/idna/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..1df9f2a70e6815908f2784e88897a9a359eef84c --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/compat.py @@ -0,0 +1,15 @@ +from typing import Any, Union + +from .core import decode, encode + + +def ToASCII(label: str) -> bytes: + return encode(label) + + +def ToUnicode(label: Union[bytes, bytearray]) -> str: + return decode(label) + + +def nameprep(s: Any) -> None: + raise NotImplementedError("IDNA 2008 does not utilise nameprep protocol") diff --git a/python_embeded/Lib/site-packages/idna/core.py b/python_embeded/Lib/site-packages/idna/core.py new file mode 100644 index 0000000000000000000000000000000000000000..9115f123f0274832af5ba1cf3c5481cc5353eecd --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/core.py @@ -0,0 +1,437 @@ +import bisect +import re +import unicodedata +from typing import Optional, Union + +from . import idnadata +from .intranges import intranges_contain + +_virama_combining_class = 9 +_alabel_prefix = b"xn--" +_unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]") + + +class IDNAError(UnicodeError): + """Base exception for all IDNA-encoding related problems""" + + pass + + +class IDNABidiError(IDNAError): + """Exception when bidirectional requirements are not satisfied""" + + pass + + +class InvalidCodepoint(IDNAError): + """Exception when a disallowed or unallocated codepoint is used""" + + pass + + +class InvalidCodepointContext(IDNAError): + """Exception when the codepoint is not valid in the context it is used""" + + pass + + +def _combining_class(cp: int) -> int: + v = unicodedata.combining(chr(cp)) + if v == 0: + if not unicodedata.name(chr(cp)): + raise ValueError("Unknown character in unicodedata") + return v + + +def _is_script(cp: str, script: str) -> bool: + return intranges_contain(ord(cp), idnadata.scripts[script]) + + +def _punycode(s: str) -> bytes: + return s.encode("punycode") + + +def _unot(s: int) -> str: + return "U+{:04X}".format(s) + + +def valid_label_length(label: Union[bytes, str]) -> bool: + if len(label) > 63: + return False + return True + + +def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool: + if len(label) > (254 if trailing_dot else 253): + return False + return True + + +def check_bidi(label: str, check_ltr: bool = False) -> bool: + # Bidi rules should only be applied if string contains RTL characters + bidi_label = False + for idx, cp in enumerate(label, 1): + direction = unicodedata.bidirectional(cp) + if direction == "": + # String likely comes from a newer version of Unicode + raise IDNABidiError("Unknown directionality in label {} at position {}".format(repr(label), idx)) + if direction in ["R", "AL", "AN"]: + bidi_label = True + if not bidi_label and not check_ltr: + return True + + # Bidi rule 1 + direction = unicodedata.bidirectional(label[0]) + if direction in ["R", "AL"]: + rtl = True + elif direction == "L": + rtl = False + else: + raise IDNABidiError("First codepoint in label {} must be directionality L, R or AL".format(repr(label))) + + valid_ending = False + number_type: Optional[str] = None + for idx, cp in enumerate(label, 1): + direction = unicodedata.bidirectional(cp) + + if rtl: + # Bidi rule 2 + if direction not in [ + "R", + "AL", + "AN", + "EN", + "ES", + "CS", + "ET", + "ON", + "BN", + "NSM", + ]: + raise IDNABidiError("Invalid direction for codepoint at position {} in a right-to-left label".format(idx)) + # Bidi rule 3 + if direction in ["R", "AL", "EN", "AN"]: + valid_ending = True + elif direction != "NSM": + valid_ending = False + # Bidi rule 4 + if direction in ["AN", "EN"]: + if not number_type: + number_type = direction + else: + if number_type != direction: + raise IDNABidiError("Can not mix numeral types in a right-to-left label") + else: + # Bidi rule 5 + if direction not in ["L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"]: + raise IDNABidiError("Invalid direction for codepoint at position {} in a left-to-right label".format(idx)) + # Bidi rule 6 + if direction in ["L", "EN"]: + valid_ending = True + elif direction != "NSM": + valid_ending = False + + if not valid_ending: + raise IDNABidiError("Label ends with illegal codepoint directionality") + + return True + + +def check_initial_combiner(label: str) -> bool: + if unicodedata.category(label[0])[0] == "M": + raise IDNAError("Label begins with an illegal combining character") + return True + + +def check_hyphen_ok(label: str) -> bool: + if label[2:4] == "--": + raise IDNAError("Label has disallowed hyphens in 3rd and 4th position") + if label[0] == "-" or label[-1] == "-": + raise IDNAError("Label must not start or end with a hyphen") + return True + + +def check_nfc(label: str) -> None: + if unicodedata.normalize("NFC", label) != label: + raise IDNAError("Label must be in Normalization Form C") + + +def valid_contextj(label: str, pos: int) -> bool: + cp_value = ord(label[pos]) + + if cp_value == 0x200C: + if pos > 0: + if _combining_class(ord(label[pos - 1])) == _virama_combining_class: + return True + + ok = False + for i in range(pos - 1, -1, -1): + joining_type = idnadata.joining_types.get(ord(label[i])) + if joining_type == ord("T"): + continue + elif joining_type in [ord("L"), ord("D")]: + ok = True + break + else: + break + + if not ok: + return False + + ok = False + for i in range(pos + 1, len(label)): + joining_type = idnadata.joining_types.get(ord(label[i])) + if joining_type == ord("T"): + continue + elif joining_type in [ord("R"), ord("D")]: + ok = True + break + else: + break + return ok + + if cp_value == 0x200D: + if pos > 0: + if _combining_class(ord(label[pos - 1])) == _virama_combining_class: + return True + return False + + else: + return False + + +def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: + cp_value = ord(label[pos]) + + if cp_value == 0x00B7: + if 0 < pos < len(label) - 1: + if ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C: + return True + return False + + elif cp_value == 0x0375: + if pos < len(label) - 1 and len(label) > 1: + return _is_script(label[pos + 1], "Greek") + return False + + elif cp_value == 0x05F3 or cp_value == 0x05F4: + if pos > 0: + return _is_script(label[pos - 1], "Hebrew") + return False + + elif cp_value == 0x30FB: + for cp in label: + if cp == "\u30fb": + continue + if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"): + return True + return False + + elif 0x660 <= cp_value <= 0x669: + for cp in label: + if 0x6F0 <= ord(cp) <= 0x06F9: + return False + return True + + elif 0x6F0 <= cp_value <= 0x6F9: + for cp in label: + if 0x660 <= ord(cp) <= 0x0669: + return False + return True + + return False + + +def check_label(label: Union[str, bytes, bytearray]) -> None: + if isinstance(label, (bytes, bytearray)): + label = label.decode("utf-8") + if len(label) == 0: + raise IDNAError("Empty Label") + + check_nfc(label) + check_hyphen_ok(label) + check_initial_combiner(label) + + for pos, cp in enumerate(label): + cp_value = ord(cp) + if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]): + continue + elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]): + try: + if not valid_contextj(label, pos): + raise InvalidCodepointContext( + "Joiner {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label)) + ) + except ValueError: + raise IDNAError( + "Unknown codepoint adjacent to joiner {} at position {} in {}".format( + _unot(cp_value), pos + 1, repr(label) + ) + ) + elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]): + if not valid_contexto(label, pos): + raise InvalidCodepointContext( + "Codepoint {} not allowed at position {} in {}".format(_unot(cp_value), pos + 1, repr(label)) + ) + else: + raise InvalidCodepoint( + "Codepoint {} at position {} of {} not allowed".format(_unot(cp_value), pos + 1, repr(label)) + ) + + check_bidi(label) + + +def alabel(label: str) -> bytes: + try: + label_bytes = label.encode("ascii") + ulabel(label_bytes) + if not valid_label_length(label_bytes): + raise IDNAError("Label too long") + return label_bytes + except UnicodeEncodeError: + pass + + check_label(label) + label_bytes = _alabel_prefix + _punycode(label) + + if not valid_label_length(label_bytes): + raise IDNAError("Label too long") + + return label_bytes + + +def ulabel(label: Union[str, bytes, bytearray]) -> str: + if not isinstance(label, (bytes, bytearray)): + try: + label_bytes = label.encode("ascii") + except UnicodeEncodeError: + check_label(label) + return label + else: + label_bytes = label + + label_bytes = label_bytes.lower() + if label_bytes.startswith(_alabel_prefix): + label_bytes = label_bytes[len(_alabel_prefix) :] + if not label_bytes: + raise IDNAError("Malformed A-label, no Punycode eligible content found") + if label_bytes.decode("ascii")[-1] == "-": + raise IDNAError("A-label must not end with a hyphen") + else: + check_label(label_bytes) + return label_bytes.decode("ascii") + + try: + label = label_bytes.decode("punycode") + except UnicodeError: + raise IDNAError("Invalid A-label") + check_label(label) + return label + + +def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: + """Re-map the characters in the string according to UTS46 processing.""" + from .uts46data import uts46data + + output = "" + + for pos, char in enumerate(domain): + code_point = ord(char) + try: + uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1] + status = uts46row[1] + replacement: Optional[str] = None + if len(uts46row) == 3: + replacement = uts46row[2] + if ( + status == "V" + or (status == "D" and not transitional) + or (status == "3" and not std3_rules and replacement is None) + ): + output += char + elif replacement is not None and ( + status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional) + ): + output += replacement + elif status != "I": + raise IndexError() + except IndexError: + raise InvalidCodepoint( + "Codepoint {} not allowed at position {} in {}".format(_unot(code_point), pos + 1, repr(domain)) + ) + + return unicodedata.normalize("NFC", output) + + +def encode( + s: Union[str, bytes, bytearray], + strict: bool = False, + uts46: bool = False, + std3_rules: bool = False, + transitional: bool = False, +) -> bytes: + if not isinstance(s, str): + try: + s = str(s, "ascii") + except UnicodeDecodeError: + raise IDNAError("should pass a unicode string to the function rather than a byte string.") + if uts46: + s = uts46_remap(s, std3_rules, transitional) + trailing_dot = False + result = [] + if strict: + labels = s.split(".") + else: + labels = _unicode_dots_re.split(s) + if not labels or labels == [""]: + raise IDNAError("Empty domain") + if labels[-1] == "": + del labels[-1] + trailing_dot = True + for label in labels: + s = alabel(label) + if s: + result.append(s) + else: + raise IDNAError("Empty label") + if trailing_dot: + result.append(b"") + s = b".".join(result) + if not valid_string_length(s, trailing_dot): + raise IDNAError("Domain too long") + return s + + +def decode( + s: Union[str, bytes, bytearray], + strict: bool = False, + uts46: bool = False, + std3_rules: bool = False, +) -> str: + try: + if not isinstance(s, str): + s = str(s, "ascii") + except UnicodeDecodeError: + raise IDNAError("Invalid ASCII in A-label") + if uts46: + s = uts46_remap(s, std3_rules, False) + trailing_dot = False + result = [] + if not strict: + labels = _unicode_dots_re.split(s) + else: + labels = s.split(".") + if not labels or labels == [""]: + raise IDNAError("Empty domain") + if not labels[-1]: + del labels[-1] + trailing_dot = True + for label in labels: + s = ulabel(label) + if s: + result.append(s) + else: + raise IDNAError("Empty label") + if trailing_dot: + result.append("") + return ".".join(result) diff --git a/python_embeded/Lib/site-packages/idna/idnadata.py b/python_embeded/Lib/site-packages/idna/idnadata.py new file mode 100644 index 0000000000000000000000000000000000000000..4be6004622efcdc36a8d15efc0ac3e138a4bae02 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/idnadata.py @@ -0,0 +1,4243 @@ +# This file is automatically generated by tools/idna-data + +__version__ = "15.1.0" +scripts = { + "Greek": ( + 0x37000000374, + 0x37500000378, + 0x37A0000037E, + 0x37F00000380, + 0x38400000385, + 0x38600000387, + 0x3880000038B, + 0x38C0000038D, + 0x38E000003A2, + 0x3A3000003E2, + 0x3F000000400, + 0x1D2600001D2B, + 0x1D5D00001D62, + 0x1D6600001D6B, + 0x1DBF00001DC0, + 0x1F0000001F16, + 0x1F1800001F1E, + 0x1F2000001F46, + 0x1F4800001F4E, + 0x1F5000001F58, + 0x1F5900001F5A, + 0x1F5B00001F5C, + 0x1F5D00001F5E, + 0x1F5F00001F7E, + 0x1F8000001FB5, + 0x1FB600001FC5, + 0x1FC600001FD4, + 0x1FD600001FDC, + 0x1FDD00001FF0, + 0x1FF200001FF5, + 0x1FF600001FFF, + 0x212600002127, + 0xAB650000AB66, + 0x101400001018F, + 0x101A0000101A1, + 0x1D2000001D246, + ), + "Han": ( + 0x2E8000002E9A, + 0x2E9B00002EF4, + 0x2F0000002FD6, + 0x300500003006, + 0x300700003008, + 0x30210000302A, + 0x30380000303C, + 0x340000004DC0, + 0x4E000000A000, + 0xF9000000FA6E, + 0xFA700000FADA, + 0x16FE200016FE4, + 0x16FF000016FF2, + 0x200000002A6E0, + 0x2A7000002B73A, + 0x2B7400002B81E, + 0x2B8200002CEA2, + 0x2CEB00002EBE1, + 0x2EBF00002EE5E, + 0x2F8000002FA1E, + 0x300000003134B, + 0x31350000323B0, + ), + "Hebrew": ( + 0x591000005C8, + 0x5D0000005EB, + 0x5EF000005F5, + 0xFB1D0000FB37, + 0xFB380000FB3D, + 0xFB3E0000FB3F, + 0xFB400000FB42, + 0xFB430000FB45, + 0xFB460000FB50, + ), + "Hiragana": ( + 0x304100003097, + 0x309D000030A0, + 0x1B0010001B120, + 0x1B1320001B133, + 0x1B1500001B153, + 0x1F2000001F201, + ), + "Katakana": ( + 0x30A1000030FB, + 0x30FD00003100, + 0x31F000003200, + 0x32D0000032FF, + 0x330000003358, + 0xFF660000FF70, + 0xFF710000FF9E, + 0x1AFF00001AFF4, + 0x1AFF50001AFFC, + 0x1AFFD0001AFFF, + 0x1B0000001B001, + 0x1B1200001B123, + 0x1B1550001B156, + 0x1B1640001B168, + ), +} +joining_types = { + 0xAD: 84, + 0x300: 84, + 0x301: 84, + 0x302: 84, + 0x303: 84, + 0x304: 84, + 0x305: 84, + 0x306: 84, + 0x307: 84, + 0x308: 84, + 0x309: 84, + 0x30A: 84, + 0x30B: 84, + 0x30C: 84, + 0x30D: 84, + 0x30E: 84, + 0x30F: 84, + 0x310: 84, + 0x311: 84, + 0x312: 84, + 0x313: 84, + 0x314: 84, + 0x315: 84, + 0x316: 84, + 0x317: 84, + 0x318: 84, + 0x319: 84, + 0x31A: 84, + 0x31B: 84, + 0x31C: 84, + 0x31D: 84, + 0x31E: 84, + 0x31F: 84, + 0x320: 84, + 0x321: 84, + 0x322: 84, + 0x323: 84, + 0x324: 84, + 0x325: 84, + 0x326: 84, + 0x327: 84, + 0x328: 84, + 0x329: 84, + 0x32A: 84, + 0x32B: 84, + 0x32C: 84, + 0x32D: 84, + 0x32E: 84, + 0x32F: 84, + 0x330: 84, + 0x331: 84, + 0x332: 84, + 0x333: 84, + 0x334: 84, + 0x335: 84, + 0x336: 84, + 0x337: 84, + 0x338: 84, + 0x339: 84, + 0x33A: 84, + 0x33B: 84, + 0x33C: 84, + 0x33D: 84, + 0x33E: 84, + 0x33F: 84, + 0x340: 84, + 0x341: 84, + 0x342: 84, + 0x343: 84, + 0x344: 84, + 0x345: 84, + 0x346: 84, + 0x347: 84, + 0x348: 84, + 0x349: 84, + 0x34A: 84, + 0x34B: 84, + 0x34C: 84, + 0x34D: 84, + 0x34E: 84, + 0x34F: 84, + 0x350: 84, + 0x351: 84, + 0x352: 84, + 0x353: 84, + 0x354: 84, + 0x355: 84, + 0x356: 84, + 0x357: 84, + 0x358: 84, + 0x359: 84, + 0x35A: 84, + 0x35B: 84, + 0x35C: 84, + 0x35D: 84, + 0x35E: 84, + 0x35F: 84, + 0x360: 84, + 0x361: 84, + 0x362: 84, + 0x363: 84, + 0x364: 84, + 0x365: 84, + 0x366: 84, + 0x367: 84, + 0x368: 84, + 0x369: 84, + 0x36A: 84, + 0x36B: 84, + 0x36C: 84, + 0x36D: 84, + 0x36E: 84, + 0x36F: 84, + 0x483: 84, + 0x484: 84, + 0x485: 84, + 0x486: 84, + 0x487: 84, + 0x488: 84, + 0x489: 84, + 0x591: 84, + 0x592: 84, + 0x593: 84, + 0x594: 84, + 0x595: 84, + 0x596: 84, + 0x597: 84, + 0x598: 84, + 0x599: 84, + 0x59A: 84, + 0x59B: 84, + 0x59C: 84, + 0x59D: 84, + 0x59E: 84, + 0x59F: 84, + 0x5A0: 84, + 0x5A1: 84, + 0x5A2: 84, + 0x5A3: 84, + 0x5A4: 84, + 0x5A5: 84, + 0x5A6: 84, + 0x5A7: 84, + 0x5A8: 84, + 0x5A9: 84, + 0x5AA: 84, + 0x5AB: 84, + 0x5AC: 84, + 0x5AD: 84, + 0x5AE: 84, + 0x5AF: 84, + 0x5B0: 84, + 0x5B1: 84, + 0x5B2: 84, + 0x5B3: 84, + 0x5B4: 84, + 0x5B5: 84, + 0x5B6: 84, + 0x5B7: 84, + 0x5B8: 84, + 0x5B9: 84, + 0x5BA: 84, + 0x5BB: 84, + 0x5BC: 84, + 0x5BD: 84, + 0x5BF: 84, + 0x5C1: 84, + 0x5C2: 84, + 0x5C4: 84, + 0x5C5: 84, + 0x5C7: 84, + 0x610: 84, + 0x611: 84, + 0x612: 84, + 0x613: 84, + 0x614: 84, + 0x615: 84, + 0x616: 84, + 0x617: 84, + 0x618: 84, + 0x619: 84, + 0x61A: 84, + 0x61C: 84, + 0x620: 68, + 0x622: 82, + 0x623: 82, + 0x624: 82, + 0x625: 82, + 0x626: 68, + 0x627: 82, + 0x628: 68, + 0x629: 82, + 0x62A: 68, + 0x62B: 68, + 0x62C: 68, + 0x62D: 68, + 0x62E: 68, + 0x62F: 82, + 0x630: 82, + 0x631: 82, + 0x632: 82, + 0x633: 68, + 0x634: 68, + 0x635: 68, + 0x636: 68, + 0x637: 68, + 0x638: 68, + 0x639: 68, + 0x63A: 68, + 0x63B: 68, + 0x63C: 68, + 0x63D: 68, + 0x63E: 68, + 0x63F: 68, + 0x640: 67, + 0x641: 68, + 0x642: 68, + 0x643: 68, + 0x644: 68, + 0x645: 68, + 0x646: 68, + 0x647: 68, + 0x648: 82, + 0x649: 68, + 0x64A: 68, + 0x64B: 84, + 0x64C: 84, + 0x64D: 84, + 0x64E: 84, + 0x64F: 84, + 0x650: 84, + 0x651: 84, + 0x652: 84, + 0x653: 84, + 0x654: 84, + 0x655: 84, + 0x656: 84, + 0x657: 84, + 0x658: 84, + 0x659: 84, + 0x65A: 84, + 0x65B: 84, + 0x65C: 84, + 0x65D: 84, + 0x65E: 84, + 0x65F: 84, + 0x66E: 68, + 0x66F: 68, + 0x670: 84, + 0x671: 82, + 0x672: 82, + 0x673: 82, + 0x675: 82, + 0x676: 82, + 0x677: 82, + 0x678: 68, + 0x679: 68, + 0x67A: 68, + 0x67B: 68, + 0x67C: 68, + 0x67D: 68, + 0x67E: 68, + 0x67F: 68, + 0x680: 68, + 0x681: 68, + 0x682: 68, + 0x683: 68, + 0x684: 68, + 0x685: 68, + 0x686: 68, + 0x687: 68, + 0x688: 82, + 0x689: 82, + 0x68A: 82, + 0x68B: 82, + 0x68C: 82, + 0x68D: 82, + 0x68E: 82, + 0x68F: 82, + 0x690: 82, + 0x691: 82, + 0x692: 82, + 0x693: 82, + 0x694: 82, + 0x695: 82, + 0x696: 82, + 0x697: 82, + 0x698: 82, + 0x699: 82, + 0x69A: 68, + 0x69B: 68, + 0x69C: 68, + 0x69D: 68, + 0x69E: 68, + 0x69F: 68, + 0x6A0: 68, + 0x6A1: 68, + 0x6A2: 68, + 0x6A3: 68, + 0x6A4: 68, + 0x6A5: 68, + 0x6A6: 68, + 0x6A7: 68, + 0x6A8: 68, + 0x6A9: 68, + 0x6AA: 68, + 0x6AB: 68, + 0x6AC: 68, + 0x6AD: 68, + 0x6AE: 68, + 0x6AF: 68, + 0x6B0: 68, + 0x6B1: 68, + 0x6B2: 68, + 0x6B3: 68, + 0x6B4: 68, + 0x6B5: 68, + 0x6B6: 68, + 0x6B7: 68, + 0x6B8: 68, + 0x6B9: 68, + 0x6BA: 68, + 0x6BB: 68, + 0x6BC: 68, + 0x6BD: 68, + 0x6BE: 68, + 0x6BF: 68, + 0x6C0: 82, + 0x6C1: 68, + 0x6C2: 68, + 0x6C3: 82, + 0x6C4: 82, + 0x6C5: 82, + 0x6C6: 82, + 0x6C7: 82, + 0x6C8: 82, + 0x6C9: 82, + 0x6CA: 82, + 0x6CB: 82, + 0x6CC: 68, + 0x6CD: 82, + 0x6CE: 68, + 0x6CF: 82, + 0x6D0: 68, + 0x6D1: 68, + 0x6D2: 82, + 0x6D3: 82, + 0x6D5: 82, + 0x6D6: 84, + 0x6D7: 84, + 0x6D8: 84, + 0x6D9: 84, + 0x6DA: 84, + 0x6DB: 84, + 0x6DC: 84, + 0x6DF: 84, + 0x6E0: 84, + 0x6E1: 84, + 0x6E2: 84, + 0x6E3: 84, + 0x6E4: 84, + 0x6E7: 84, + 0x6E8: 84, + 0x6EA: 84, + 0x6EB: 84, + 0x6EC: 84, + 0x6ED: 84, + 0x6EE: 82, + 0x6EF: 82, + 0x6FA: 68, + 0x6FB: 68, + 0x6FC: 68, + 0x6FF: 68, + 0x70F: 84, + 0x710: 82, + 0x711: 84, + 0x712: 68, + 0x713: 68, + 0x714: 68, + 0x715: 82, + 0x716: 82, + 0x717: 82, + 0x718: 82, + 0x719: 82, + 0x71A: 68, + 0x71B: 68, + 0x71C: 68, + 0x71D: 68, + 0x71E: 82, + 0x71F: 68, + 0x720: 68, + 0x721: 68, + 0x722: 68, + 0x723: 68, + 0x724: 68, + 0x725: 68, + 0x726: 68, + 0x727: 68, + 0x728: 82, + 0x729: 68, + 0x72A: 82, + 0x72B: 68, + 0x72C: 82, + 0x72D: 68, + 0x72E: 68, + 0x72F: 82, + 0x730: 84, + 0x731: 84, + 0x732: 84, + 0x733: 84, + 0x734: 84, + 0x735: 84, + 0x736: 84, + 0x737: 84, + 0x738: 84, + 0x739: 84, + 0x73A: 84, + 0x73B: 84, + 0x73C: 84, + 0x73D: 84, + 0x73E: 84, + 0x73F: 84, + 0x740: 84, + 0x741: 84, + 0x742: 84, + 0x743: 84, + 0x744: 84, + 0x745: 84, + 0x746: 84, + 0x747: 84, + 0x748: 84, + 0x749: 84, + 0x74A: 84, + 0x74D: 82, + 0x74E: 68, + 0x74F: 68, + 0x750: 68, + 0x751: 68, + 0x752: 68, + 0x753: 68, + 0x754: 68, + 0x755: 68, + 0x756: 68, + 0x757: 68, + 0x758: 68, + 0x759: 82, + 0x75A: 82, + 0x75B: 82, + 0x75C: 68, + 0x75D: 68, + 0x75E: 68, + 0x75F: 68, + 0x760: 68, + 0x761: 68, + 0x762: 68, + 0x763: 68, + 0x764: 68, + 0x765: 68, + 0x766: 68, + 0x767: 68, + 0x768: 68, + 0x769: 68, + 0x76A: 68, + 0x76B: 82, + 0x76C: 82, + 0x76D: 68, + 0x76E: 68, + 0x76F: 68, + 0x770: 68, + 0x771: 82, + 0x772: 68, + 0x773: 82, + 0x774: 82, + 0x775: 68, + 0x776: 68, + 0x777: 68, + 0x778: 82, + 0x779: 82, + 0x77A: 68, + 0x77B: 68, + 0x77C: 68, + 0x77D: 68, + 0x77E: 68, + 0x77F: 68, + 0x7A6: 84, + 0x7A7: 84, + 0x7A8: 84, + 0x7A9: 84, + 0x7AA: 84, + 0x7AB: 84, + 0x7AC: 84, + 0x7AD: 84, + 0x7AE: 84, + 0x7AF: 84, + 0x7B0: 84, + 0x7CA: 68, + 0x7CB: 68, + 0x7CC: 68, + 0x7CD: 68, + 0x7CE: 68, + 0x7CF: 68, + 0x7D0: 68, + 0x7D1: 68, + 0x7D2: 68, + 0x7D3: 68, + 0x7D4: 68, + 0x7D5: 68, + 0x7D6: 68, + 0x7D7: 68, + 0x7D8: 68, + 0x7D9: 68, + 0x7DA: 68, + 0x7DB: 68, + 0x7DC: 68, + 0x7DD: 68, + 0x7DE: 68, + 0x7DF: 68, + 0x7E0: 68, + 0x7E1: 68, + 0x7E2: 68, + 0x7E3: 68, + 0x7E4: 68, + 0x7E5: 68, + 0x7E6: 68, + 0x7E7: 68, + 0x7E8: 68, + 0x7E9: 68, + 0x7EA: 68, + 0x7EB: 84, + 0x7EC: 84, + 0x7ED: 84, + 0x7EE: 84, + 0x7EF: 84, + 0x7F0: 84, + 0x7F1: 84, + 0x7F2: 84, + 0x7F3: 84, + 0x7FA: 67, + 0x7FD: 84, + 0x816: 84, + 0x817: 84, + 0x818: 84, + 0x819: 84, + 0x81B: 84, + 0x81C: 84, + 0x81D: 84, + 0x81E: 84, + 0x81F: 84, + 0x820: 84, + 0x821: 84, + 0x822: 84, + 0x823: 84, + 0x825: 84, + 0x826: 84, + 0x827: 84, + 0x829: 84, + 0x82A: 84, + 0x82B: 84, + 0x82C: 84, + 0x82D: 84, + 0x840: 82, + 0x841: 68, + 0x842: 68, + 0x843: 68, + 0x844: 68, + 0x845: 68, + 0x846: 82, + 0x847: 82, + 0x848: 68, + 0x849: 82, + 0x84A: 68, + 0x84B: 68, + 0x84C: 68, + 0x84D: 68, + 0x84E: 68, + 0x84F: 68, + 0x850: 68, + 0x851: 68, + 0x852: 68, + 0x853: 68, + 0x854: 82, + 0x855: 68, + 0x856: 82, + 0x857: 82, + 0x858: 82, + 0x859: 84, + 0x85A: 84, + 0x85B: 84, + 0x860: 68, + 0x862: 68, + 0x863: 68, + 0x864: 68, + 0x865: 68, + 0x867: 82, + 0x868: 68, + 0x869: 82, + 0x86A: 82, + 0x870: 82, + 0x871: 82, + 0x872: 82, + 0x873: 82, + 0x874: 82, + 0x875: 82, + 0x876: 82, + 0x877: 82, + 0x878: 82, + 0x879: 82, + 0x87A: 82, + 0x87B: 82, + 0x87C: 82, + 0x87D: 82, + 0x87E: 82, + 0x87F: 82, + 0x880: 82, + 0x881: 82, + 0x882: 82, + 0x883: 67, + 0x884: 67, + 0x885: 67, + 0x886: 68, + 0x889: 68, + 0x88A: 68, + 0x88B: 68, + 0x88C: 68, + 0x88D: 68, + 0x88E: 82, + 0x898: 84, + 0x899: 84, + 0x89A: 84, + 0x89B: 84, + 0x89C: 84, + 0x89D: 84, + 0x89E: 84, + 0x89F: 84, + 0x8A0: 68, + 0x8A1: 68, + 0x8A2: 68, + 0x8A3: 68, + 0x8A4: 68, + 0x8A5: 68, + 0x8A6: 68, + 0x8A7: 68, + 0x8A8: 68, + 0x8A9: 68, + 0x8AA: 82, + 0x8AB: 82, + 0x8AC: 82, + 0x8AE: 82, + 0x8AF: 68, + 0x8B0: 68, + 0x8B1: 82, + 0x8B2: 82, + 0x8B3: 68, + 0x8B4: 68, + 0x8B5: 68, + 0x8B6: 68, + 0x8B7: 68, + 0x8B8: 68, + 0x8B9: 82, + 0x8BA: 68, + 0x8BB: 68, + 0x8BC: 68, + 0x8BD: 68, + 0x8BE: 68, + 0x8BF: 68, + 0x8C0: 68, + 0x8C1: 68, + 0x8C2: 68, + 0x8C3: 68, + 0x8C4: 68, + 0x8C5: 68, + 0x8C6: 68, + 0x8C7: 68, + 0x8C8: 68, + 0x8CA: 84, + 0x8CB: 84, + 0x8CC: 84, + 0x8CD: 84, + 0x8CE: 84, + 0x8CF: 84, + 0x8D0: 84, + 0x8D1: 84, + 0x8D2: 84, + 0x8D3: 84, + 0x8D4: 84, + 0x8D5: 84, + 0x8D6: 84, + 0x8D7: 84, + 0x8D8: 84, + 0x8D9: 84, + 0x8DA: 84, + 0x8DB: 84, + 0x8DC: 84, + 0x8DD: 84, + 0x8DE: 84, + 0x8DF: 84, + 0x8E0: 84, + 0x8E1: 84, + 0x8E3: 84, + 0x8E4: 84, + 0x8E5: 84, + 0x8E6: 84, + 0x8E7: 84, + 0x8E8: 84, + 0x8E9: 84, + 0x8EA: 84, + 0x8EB: 84, + 0x8EC: 84, + 0x8ED: 84, + 0x8EE: 84, + 0x8EF: 84, + 0x8F0: 84, + 0x8F1: 84, + 0x8F2: 84, + 0x8F3: 84, + 0x8F4: 84, + 0x8F5: 84, + 0x8F6: 84, + 0x8F7: 84, + 0x8F8: 84, + 0x8F9: 84, + 0x8FA: 84, + 0x8FB: 84, + 0x8FC: 84, + 0x8FD: 84, + 0x8FE: 84, + 0x8FF: 84, + 0x900: 84, + 0x901: 84, + 0x902: 84, + 0x93A: 84, + 0x93C: 84, + 0x941: 84, + 0x942: 84, + 0x943: 84, + 0x944: 84, + 0x945: 84, + 0x946: 84, + 0x947: 84, + 0x948: 84, + 0x94D: 84, + 0x951: 84, + 0x952: 84, + 0x953: 84, + 0x954: 84, + 0x955: 84, + 0x956: 84, + 0x957: 84, + 0x962: 84, + 0x963: 84, + 0x981: 84, + 0x9BC: 84, + 0x9C1: 84, + 0x9C2: 84, + 0x9C3: 84, + 0x9C4: 84, + 0x9CD: 84, + 0x9E2: 84, + 0x9E3: 84, + 0x9FE: 84, + 0xA01: 84, + 0xA02: 84, + 0xA3C: 84, + 0xA41: 84, + 0xA42: 84, + 0xA47: 84, + 0xA48: 84, + 0xA4B: 84, + 0xA4C: 84, + 0xA4D: 84, + 0xA51: 84, + 0xA70: 84, + 0xA71: 84, + 0xA75: 84, + 0xA81: 84, + 0xA82: 84, + 0xABC: 84, + 0xAC1: 84, + 0xAC2: 84, + 0xAC3: 84, + 0xAC4: 84, + 0xAC5: 84, + 0xAC7: 84, + 0xAC8: 84, + 0xACD: 84, + 0xAE2: 84, + 0xAE3: 84, + 0xAFA: 84, + 0xAFB: 84, + 0xAFC: 84, + 0xAFD: 84, + 0xAFE: 84, + 0xAFF: 84, + 0xB01: 84, + 0xB3C: 84, + 0xB3F: 84, + 0xB41: 84, + 0xB42: 84, + 0xB43: 84, + 0xB44: 84, + 0xB4D: 84, + 0xB55: 84, + 0xB56: 84, + 0xB62: 84, + 0xB63: 84, + 0xB82: 84, + 0xBC0: 84, + 0xBCD: 84, + 0xC00: 84, + 0xC04: 84, + 0xC3C: 84, + 0xC3E: 84, + 0xC3F: 84, + 0xC40: 84, + 0xC46: 84, + 0xC47: 84, + 0xC48: 84, + 0xC4A: 84, + 0xC4B: 84, + 0xC4C: 84, + 0xC4D: 84, + 0xC55: 84, + 0xC56: 84, + 0xC62: 84, + 0xC63: 84, + 0xC81: 84, + 0xCBC: 84, + 0xCBF: 84, + 0xCC6: 84, + 0xCCC: 84, + 0xCCD: 84, + 0xCE2: 84, + 0xCE3: 84, + 0xD00: 84, + 0xD01: 84, + 0xD3B: 84, + 0xD3C: 84, + 0xD41: 84, + 0xD42: 84, + 0xD43: 84, + 0xD44: 84, + 0xD4D: 84, + 0xD62: 84, + 0xD63: 84, + 0xD81: 84, + 0xDCA: 84, + 0xDD2: 84, + 0xDD3: 84, + 0xDD4: 84, + 0xDD6: 84, + 0xE31: 84, + 0xE34: 84, + 0xE35: 84, + 0xE36: 84, + 0xE37: 84, + 0xE38: 84, + 0xE39: 84, + 0xE3A: 84, + 0xE47: 84, + 0xE48: 84, + 0xE49: 84, + 0xE4A: 84, + 0xE4B: 84, + 0xE4C: 84, + 0xE4D: 84, + 0xE4E: 84, + 0xEB1: 84, + 0xEB4: 84, + 0xEB5: 84, + 0xEB6: 84, + 0xEB7: 84, + 0xEB8: 84, + 0xEB9: 84, + 0xEBA: 84, + 0xEBB: 84, + 0xEBC: 84, + 0xEC8: 84, + 0xEC9: 84, + 0xECA: 84, + 0xECB: 84, + 0xECC: 84, + 0xECD: 84, + 0xECE: 84, + 0xF18: 84, + 0xF19: 84, + 0xF35: 84, + 0xF37: 84, + 0xF39: 84, + 0xF71: 84, + 0xF72: 84, + 0xF73: 84, + 0xF74: 84, + 0xF75: 84, + 0xF76: 84, + 0xF77: 84, + 0xF78: 84, + 0xF79: 84, + 0xF7A: 84, + 0xF7B: 84, + 0xF7C: 84, + 0xF7D: 84, + 0xF7E: 84, + 0xF80: 84, + 0xF81: 84, + 0xF82: 84, + 0xF83: 84, + 0xF84: 84, + 0xF86: 84, + 0xF87: 84, + 0xF8D: 84, + 0xF8E: 84, + 0xF8F: 84, + 0xF90: 84, + 0xF91: 84, + 0xF92: 84, + 0xF93: 84, + 0xF94: 84, + 0xF95: 84, + 0xF96: 84, + 0xF97: 84, + 0xF99: 84, + 0xF9A: 84, + 0xF9B: 84, + 0xF9C: 84, + 0xF9D: 84, + 0xF9E: 84, + 0xF9F: 84, + 0xFA0: 84, + 0xFA1: 84, + 0xFA2: 84, + 0xFA3: 84, + 0xFA4: 84, + 0xFA5: 84, + 0xFA6: 84, + 0xFA7: 84, + 0xFA8: 84, + 0xFA9: 84, + 0xFAA: 84, + 0xFAB: 84, + 0xFAC: 84, + 0xFAD: 84, + 0xFAE: 84, + 0xFAF: 84, + 0xFB0: 84, + 0xFB1: 84, + 0xFB2: 84, + 0xFB3: 84, + 0xFB4: 84, + 0xFB5: 84, + 0xFB6: 84, + 0xFB7: 84, + 0xFB8: 84, + 0xFB9: 84, + 0xFBA: 84, + 0xFBB: 84, + 0xFBC: 84, + 0xFC6: 84, + 0x102D: 84, + 0x102E: 84, + 0x102F: 84, + 0x1030: 84, + 0x1032: 84, + 0x1033: 84, + 0x1034: 84, + 0x1035: 84, + 0x1036: 84, + 0x1037: 84, + 0x1039: 84, + 0x103A: 84, + 0x103D: 84, + 0x103E: 84, + 0x1058: 84, + 0x1059: 84, + 0x105E: 84, + 0x105F: 84, + 0x1060: 84, + 0x1071: 84, + 0x1072: 84, + 0x1073: 84, + 0x1074: 84, + 0x1082: 84, + 0x1085: 84, + 0x1086: 84, + 0x108D: 84, + 0x109D: 84, + 0x135D: 84, + 0x135E: 84, + 0x135F: 84, + 0x1712: 84, + 0x1713: 84, + 0x1714: 84, + 0x1732: 84, + 0x1733: 84, + 0x1752: 84, + 0x1753: 84, + 0x1772: 84, + 0x1773: 84, + 0x17B4: 84, + 0x17B5: 84, + 0x17B7: 84, + 0x17B8: 84, + 0x17B9: 84, + 0x17BA: 84, + 0x17BB: 84, + 0x17BC: 84, + 0x17BD: 84, + 0x17C6: 84, + 0x17C9: 84, + 0x17CA: 84, + 0x17CB: 84, + 0x17CC: 84, + 0x17CD: 84, + 0x17CE: 84, + 0x17CF: 84, + 0x17D0: 84, + 0x17D1: 84, + 0x17D2: 84, + 0x17D3: 84, + 0x17DD: 84, + 0x1807: 68, + 0x180A: 67, + 0x180B: 84, + 0x180C: 84, + 0x180D: 84, + 0x180F: 84, + 0x1820: 68, + 0x1821: 68, + 0x1822: 68, + 0x1823: 68, + 0x1824: 68, + 0x1825: 68, + 0x1826: 68, + 0x1827: 68, + 0x1828: 68, + 0x1829: 68, + 0x182A: 68, + 0x182B: 68, + 0x182C: 68, + 0x182D: 68, + 0x182E: 68, + 0x182F: 68, + 0x1830: 68, + 0x1831: 68, + 0x1832: 68, + 0x1833: 68, + 0x1834: 68, + 0x1835: 68, + 0x1836: 68, + 0x1837: 68, + 0x1838: 68, + 0x1839: 68, + 0x183A: 68, + 0x183B: 68, + 0x183C: 68, + 0x183D: 68, + 0x183E: 68, + 0x183F: 68, + 0x1840: 68, + 0x1841: 68, + 0x1842: 68, + 0x1843: 68, + 0x1844: 68, + 0x1845: 68, + 0x1846: 68, + 0x1847: 68, + 0x1848: 68, + 0x1849: 68, + 0x184A: 68, + 0x184B: 68, + 0x184C: 68, + 0x184D: 68, + 0x184E: 68, + 0x184F: 68, + 0x1850: 68, + 0x1851: 68, + 0x1852: 68, + 0x1853: 68, + 0x1854: 68, + 0x1855: 68, + 0x1856: 68, + 0x1857: 68, + 0x1858: 68, + 0x1859: 68, + 0x185A: 68, + 0x185B: 68, + 0x185C: 68, + 0x185D: 68, + 0x185E: 68, + 0x185F: 68, + 0x1860: 68, + 0x1861: 68, + 0x1862: 68, + 0x1863: 68, + 0x1864: 68, + 0x1865: 68, + 0x1866: 68, + 0x1867: 68, + 0x1868: 68, + 0x1869: 68, + 0x186A: 68, + 0x186B: 68, + 0x186C: 68, + 0x186D: 68, + 0x186E: 68, + 0x186F: 68, + 0x1870: 68, + 0x1871: 68, + 0x1872: 68, + 0x1873: 68, + 0x1874: 68, + 0x1875: 68, + 0x1876: 68, + 0x1877: 68, + 0x1878: 68, + 0x1885: 84, + 0x1886: 84, + 0x1887: 68, + 0x1888: 68, + 0x1889: 68, + 0x188A: 68, + 0x188B: 68, + 0x188C: 68, + 0x188D: 68, + 0x188E: 68, + 0x188F: 68, + 0x1890: 68, + 0x1891: 68, + 0x1892: 68, + 0x1893: 68, + 0x1894: 68, + 0x1895: 68, + 0x1896: 68, + 0x1897: 68, + 0x1898: 68, + 0x1899: 68, + 0x189A: 68, + 0x189B: 68, + 0x189C: 68, + 0x189D: 68, + 0x189E: 68, + 0x189F: 68, + 0x18A0: 68, + 0x18A1: 68, + 0x18A2: 68, + 0x18A3: 68, + 0x18A4: 68, + 0x18A5: 68, + 0x18A6: 68, + 0x18A7: 68, + 0x18A8: 68, + 0x18A9: 84, + 0x18AA: 68, + 0x1920: 84, + 0x1921: 84, + 0x1922: 84, + 0x1927: 84, + 0x1928: 84, + 0x1932: 84, + 0x1939: 84, + 0x193A: 84, + 0x193B: 84, + 0x1A17: 84, + 0x1A18: 84, + 0x1A1B: 84, + 0x1A56: 84, + 0x1A58: 84, + 0x1A59: 84, + 0x1A5A: 84, + 0x1A5B: 84, + 0x1A5C: 84, + 0x1A5D: 84, + 0x1A5E: 84, + 0x1A60: 84, + 0x1A62: 84, + 0x1A65: 84, + 0x1A66: 84, + 0x1A67: 84, + 0x1A68: 84, + 0x1A69: 84, + 0x1A6A: 84, + 0x1A6B: 84, + 0x1A6C: 84, + 0x1A73: 84, + 0x1A74: 84, + 0x1A75: 84, + 0x1A76: 84, + 0x1A77: 84, + 0x1A78: 84, + 0x1A79: 84, + 0x1A7A: 84, + 0x1A7B: 84, + 0x1A7C: 84, + 0x1A7F: 84, + 0x1AB0: 84, + 0x1AB1: 84, + 0x1AB2: 84, + 0x1AB3: 84, + 0x1AB4: 84, + 0x1AB5: 84, + 0x1AB6: 84, + 0x1AB7: 84, + 0x1AB8: 84, + 0x1AB9: 84, + 0x1ABA: 84, + 0x1ABB: 84, + 0x1ABC: 84, + 0x1ABD: 84, + 0x1ABE: 84, + 0x1ABF: 84, + 0x1AC0: 84, + 0x1AC1: 84, + 0x1AC2: 84, + 0x1AC3: 84, + 0x1AC4: 84, + 0x1AC5: 84, + 0x1AC6: 84, + 0x1AC7: 84, + 0x1AC8: 84, + 0x1AC9: 84, + 0x1ACA: 84, + 0x1ACB: 84, + 0x1ACC: 84, + 0x1ACD: 84, + 0x1ACE: 84, + 0x1B00: 84, + 0x1B01: 84, + 0x1B02: 84, + 0x1B03: 84, + 0x1B34: 84, + 0x1B36: 84, + 0x1B37: 84, + 0x1B38: 84, + 0x1B39: 84, + 0x1B3A: 84, + 0x1B3C: 84, + 0x1B42: 84, + 0x1B6B: 84, + 0x1B6C: 84, + 0x1B6D: 84, + 0x1B6E: 84, + 0x1B6F: 84, + 0x1B70: 84, + 0x1B71: 84, + 0x1B72: 84, + 0x1B73: 84, + 0x1B80: 84, + 0x1B81: 84, + 0x1BA2: 84, + 0x1BA3: 84, + 0x1BA4: 84, + 0x1BA5: 84, + 0x1BA8: 84, + 0x1BA9: 84, + 0x1BAB: 84, + 0x1BAC: 84, + 0x1BAD: 84, + 0x1BE6: 84, + 0x1BE8: 84, + 0x1BE9: 84, + 0x1BED: 84, + 0x1BEF: 84, + 0x1BF0: 84, + 0x1BF1: 84, + 0x1C2C: 84, + 0x1C2D: 84, + 0x1C2E: 84, + 0x1C2F: 84, + 0x1C30: 84, + 0x1C31: 84, + 0x1C32: 84, + 0x1C33: 84, + 0x1C36: 84, + 0x1C37: 84, + 0x1CD0: 84, + 0x1CD1: 84, + 0x1CD2: 84, + 0x1CD4: 84, + 0x1CD5: 84, + 0x1CD6: 84, + 0x1CD7: 84, + 0x1CD8: 84, + 0x1CD9: 84, + 0x1CDA: 84, + 0x1CDB: 84, + 0x1CDC: 84, + 0x1CDD: 84, + 0x1CDE: 84, + 0x1CDF: 84, + 0x1CE0: 84, + 0x1CE2: 84, + 0x1CE3: 84, + 0x1CE4: 84, + 0x1CE5: 84, + 0x1CE6: 84, + 0x1CE7: 84, + 0x1CE8: 84, + 0x1CED: 84, + 0x1CF4: 84, + 0x1CF8: 84, + 0x1CF9: 84, + 0x1DC0: 84, + 0x1DC1: 84, + 0x1DC2: 84, + 0x1DC3: 84, + 0x1DC4: 84, + 0x1DC5: 84, + 0x1DC6: 84, + 0x1DC7: 84, + 0x1DC8: 84, + 0x1DC9: 84, + 0x1DCA: 84, + 0x1DCB: 84, + 0x1DCC: 84, + 0x1DCD: 84, + 0x1DCE: 84, + 0x1DCF: 84, + 0x1DD0: 84, + 0x1DD1: 84, + 0x1DD2: 84, + 0x1DD3: 84, + 0x1DD4: 84, + 0x1DD5: 84, + 0x1DD6: 84, + 0x1DD7: 84, + 0x1DD8: 84, + 0x1DD9: 84, + 0x1DDA: 84, + 0x1DDB: 84, + 0x1DDC: 84, + 0x1DDD: 84, + 0x1DDE: 84, + 0x1DDF: 84, + 0x1DE0: 84, + 0x1DE1: 84, + 0x1DE2: 84, + 0x1DE3: 84, + 0x1DE4: 84, + 0x1DE5: 84, + 0x1DE6: 84, + 0x1DE7: 84, + 0x1DE8: 84, + 0x1DE9: 84, + 0x1DEA: 84, + 0x1DEB: 84, + 0x1DEC: 84, + 0x1DED: 84, + 0x1DEE: 84, + 0x1DEF: 84, + 0x1DF0: 84, + 0x1DF1: 84, + 0x1DF2: 84, + 0x1DF3: 84, + 0x1DF4: 84, + 0x1DF5: 84, + 0x1DF6: 84, + 0x1DF7: 84, + 0x1DF8: 84, + 0x1DF9: 84, + 0x1DFA: 84, + 0x1DFB: 84, + 0x1DFC: 84, + 0x1DFD: 84, + 0x1DFE: 84, + 0x1DFF: 84, + 0x200B: 84, + 0x200D: 67, + 0x200E: 84, + 0x200F: 84, + 0x202A: 84, + 0x202B: 84, + 0x202C: 84, + 0x202D: 84, + 0x202E: 84, + 0x2060: 84, + 0x2061: 84, + 0x2062: 84, + 0x2063: 84, + 0x2064: 84, + 0x206A: 84, + 0x206B: 84, + 0x206C: 84, + 0x206D: 84, + 0x206E: 84, + 0x206F: 84, + 0x20D0: 84, + 0x20D1: 84, + 0x20D2: 84, + 0x20D3: 84, + 0x20D4: 84, + 0x20D5: 84, + 0x20D6: 84, + 0x20D7: 84, + 0x20D8: 84, + 0x20D9: 84, + 0x20DA: 84, + 0x20DB: 84, + 0x20DC: 84, + 0x20DD: 84, + 0x20DE: 84, + 0x20DF: 84, + 0x20E0: 84, + 0x20E1: 84, + 0x20E2: 84, + 0x20E3: 84, + 0x20E4: 84, + 0x20E5: 84, + 0x20E6: 84, + 0x20E7: 84, + 0x20E8: 84, + 0x20E9: 84, + 0x20EA: 84, + 0x20EB: 84, + 0x20EC: 84, + 0x20ED: 84, + 0x20EE: 84, + 0x20EF: 84, + 0x20F0: 84, + 0x2CEF: 84, + 0x2CF0: 84, + 0x2CF1: 84, + 0x2D7F: 84, + 0x2DE0: 84, + 0x2DE1: 84, + 0x2DE2: 84, + 0x2DE3: 84, + 0x2DE4: 84, + 0x2DE5: 84, + 0x2DE6: 84, + 0x2DE7: 84, + 0x2DE8: 84, + 0x2DE9: 84, + 0x2DEA: 84, + 0x2DEB: 84, + 0x2DEC: 84, + 0x2DED: 84, + 0x2DEE: 84, + 0x2DEF: 84, + 0x2DF0: 84, + 0x2DF1: 84, + 0x2DF2: 84, + 0x2DF3: 84, + 0x2DF4: 84, + 0x2DF5: 84, + 0x2DF6: 84, + 0x2DF7: 84, + 0x2DF8: 84, + 0x2DF9: 84, + 0x2DFA: 84, + 0x2DFB: 84, + 0x2DFC: 84, + 0x2DFD: 84, + 0x2DFE: 84, + 0x2DFF: 84, + 0x302A: 84, + 0x302B: 84, + 0x302C: 84, + 0x302D: 84, + 0x3099: 84, + 0x309A: 84, + 0xA66F: 84, + 0xA670: 84, + 0xA671: 84, + 0xA672: 84, + 0xA674: 84, + 0xA675: 84, + 0xA676: 84, + 0xA677: 84, + 0xA678: 84, + 0xA679: 84, + 0xA67A: 84, + 0xA67B: 84, + 0xA67C: 84, + 0xA67D: 84, + 0xA69E: 84, + 0xA69F: 84, + 0xA6F0: 84, + 0xA6F1: 84, + 0xA802: 84, + 0xA806: 84, + 0xA80B: 84, + 0xA825: 84, + 0xA826: 84, + 0xA82C: 84, + 0xA840: 68, + 0xA841: 68, + 0xA842: 68, + 0xA843: 68, + 0xA844: 68, + 0xA845: 68, + 0xA846: 68, + 0xA847: 68, + 0xA848: 68, + 0xA849: 68, + 0xA84A: 68, + 0xA84B: 68, + 0xA84C: 68, + 0xA84D: 68, + 0xA84E: 68, + 0xA84F: 68, + 0xA850: 68, + 0xA851: 68, + 0xA852: 68, + 0xA853: 68, + 0xA854: 68, + 0xA855: 68, + 0xA856: 68, + 0xA857: 68, + 0xA858: 68, + 0xA859: 68, + 0xA85A: 68, + 0xA85B: 68, + 0xA85C: 68, + 0xA85D: 68, + 0xA85E: 68, + 0xA85F: 68, + 0xA860: 68, + 0xA861: 68, + 0xA862: 68, + 0xA863: 68, + 0xA864: 68, + 0xA865: 68, + 0xA866: 68, + 0xA867: 68, + 0xA868: 68, + 0xA869: 68, + 0xA86A: 68, + 0xA86B: 68, + 0xA86C: 68, + 0xA86D: 68, + 0xA86E: 68, + 0xA86F: 68, + 0xA870: 68, + 0xA871: 68, + 0xA872: 76, + 0xA8C4: 84, + 0xA8C5: 84, + 0xA8E0: 84, + 0xA8E1: 84, + 0xA8E2: 84, + 0xA8E3: 84, + 0xA8E4: 84, + 0xA8E5: 84, + 0xA8E6: 84, + 0xA8E7: 84, + 0xA8E8: 84, + 0xA8E9: 84, + 0xA8EA: 84, + 0xA8EB: 84, + 0xA8EC: 84, + 0xA8ED: 84, + 0xA8EE: 84, + 0xA8EF: 84, + 0xA8F0: 84, + 0xA8F1: 84, + 0xA8FF: 84, + 0xA926: 84, + 0xA927: 84, + 0xA928: 84, + 0xA929: 84, + 0xA92A: 84, + 0xA92B: 84, + 0xA92C: 84, + 0xA92D: 84, + 0xA947: 84, + 0xA948: 84, + 0xA949: 84, + 0xA94A: 84, + 0xA94B: 84, + 0xA94C: 84, + 0xA94D: 84, + 0xA94E: 84, + 0xA94F: 84, + 0xA950: 84, + 0xA951: 84, + 0xA980: 84, + 0xA981: 84, + 0xA982: 84, + 0xA9B3: 84, + 0xA9B6: 84, + 0xA9B7: 84, + 0xA9B8: 84, + 0xA9B9: 84, + 0xA9BC: 84, + 0xA9BD: 84, + 0xA9E5: 84, + 0xAA29: 84, + 0xAA2A: 84, + 0xAA2B: 84, + 0xAA2C: 84, + 0xAA2D: 84, + 0xAA2E: 84, + 0xAA31: 84, + 0xAA32: 84, + 0xAA35: 84, + 0xAA36: 84, + 0xAA43: 84, + 0xAA4C: 84, + 0xAA7C: 84, + 0xAAB0: 84, + 0xAAB2: 84, + 0xAAB3: 84, + 0xAAB4: 84, + 0xAAB7: 84, + 0xAAB8: 84, + 0xAABE: 84, + 0xAABF: 84, + 0xAAC1: 84, + 0xAAEC: 84, + 0xAAED: 84, + 0xAAF6: 84, + 0xABE5: 84, + 0xABE8: 84, + 0xABED: 84, + 0xFB1E: 84, + 0xFE00: 84, + 0xFE01: 84, + 0xFE02: 84, + 0xFE03: 84, + 0xFE04: 84, + 0xFE05: 84, + 0xFE06: 84, + 0xFE07: 84, + 0xFE08: 84, + 0xFE09: 84, + 0xFE0A: 84, + 0xFE0B: 84, + 0xFE0C: 84, + 0xFE0D: 84, + 0xFE0E: 84, + 0xFE0F: 84, + 0xFE20: 84, + 0xFE21: 84, + 0xFE22: 84, + 0xFE23: 84, + 0xFE24: 84, + 0xFE25: 84, + 0xFE26: 84, + 0xFE27: 84, + 0xFE28: 84, + 0xFE29: 84, + 0xFE2A: 84, + 0xFE2B: 84, + 0xFE2C: 84, + 0xFE2D: 84, + 0xFE2E: 84, + 0xFE2F: 84, + 0xFEFF: 84, + 0xFFF9: 84, + 0xFFFA: 84, + 0xFFFB: 84, + 0x101FD: 84, + 0x102E0: 84, + 0x10376: 84, + 0x10377: 84, + 0x10378: 84, + 0x10379: 84, + 0x1037A: 84, + 0x10A01: 84, + 0x10A02: 84, + 0x10A03: 84, + 0x10A05: 84, + 0x10A06: 84, + 0x10A0C: 84, + 0x10A0D: 84, + 0x10A0E: 84, + 0x10A0F: 84, + 0x10A38: 84, + 0x10A39: 84, + 0x10A3A: 84, + 0x10A3F: 84, + 0x10AC0: 68, + 0x10AC1: 68, + 0x10AC2: 68, + 0x10AC3: 68, + 0x10AC4: 68, + 0x10AC5: 82, + 0x10AC7: 82, + 0x10AC9: 82, + 0x10ACA: 82, + 0x10ACD: 76, + 0x10ACE: 82, + 0x10ACF: 82, + 0x10AD0: 82, + 0x10AD1: 82, + 0x10AD2: 82, + 0x10AD3: 68, + 0x10AD4: 68, + 0x10AD5: 68, + 0x10AD6: 68, + 0x10AD7: 76, + 0x10AD8: 68, + 0x10AD9: 68, + 0x10ADA: 68, + 0x10ADB: 68, + 0x10ADC: 68, + 0x10ADD: 82, + 0x10ADE: 68, + 0x10ADF: 68, + 0x10AE0: 68, + 0x10AE1: 82, + 0x10AE4: 82, + 0x10AE5: 84, + 0x10AE6: 84, + 0x10AEB: 68, + 0x10AEC: 68, + 0x10AED: 68, + 0x10AEE: 68, + 0x10AEF: 82, + 0x10B80: 68, + 0x10B81: 82, + 0x10B82: 68, + 0x10B83: 82, + 0x10B84: 82, + 0x10B85: 82, + 0x10B86: 68, + 0x10B87: 68, + 0x10B88: 68, + 0x10B89: 82, + 0x10B8A: 68, + 0x10B8B: 68, + 0x10B8C: 82, + 0x10B8D: 68, + 0x10B8E: 82, + 0x10B8F: 82, + 0x10B90: 68, + 0x10B91: 82, + 0x10BA9: 82, + 0x10BAA: 82, + 0x10BAB: 82, + 0x10BAC: 82, + 0x10BAD: 68, + 0x10BAE: 68, + 0x10D00: 76, + 0x10D01: 68, + 0x10D02: 68, + 0x10D03: 68, + 0x10D04: 68, + 0x10D05: 68, + 0x10D06: 68, + 0x10D07: 68, + 0x10D08: 68, + 0x10D09: 68, + 0x10D0A: 68, + 0x10D0B: 68, + 0x10D0C: 68, + 0x10D0D: 68, + 0x10D0E: 68, + 0x10D0F: 68, + 0x10D10: 68, + 0x10D11: 68, + 0x10D12: 68, + 0x10D13: 68, + 0x10D14: 68, + 0x10D15: 68, + 0x10D16: 68, + 0x10D17: 68, + 0x10D18: 68, + 0x10D19: 68, + 0x10D1A: 68, + 0x10D1B: 68, + 0x10D1C: 68, + 0x10D1D: 68, + 0x10D1E: 68, + 0x10D1F: 68, + 0x10D20: 68, + 0x10D21: 68, + 0x10D22: 82, + 0x10D23: 68, + 0x10D24: 84, + 0x10D25: 84, + 0x10D26: 84, + 0x10D27: 84, + 0x10EAB: 84, + 0x10EAC: 84, + 0x10EFD: 84, + 0x10EFE: 84, + 0x10EFF: 84, + 0x10F30: 68, + 0x10F31: 68, + 0x10F32: 68, + 0x10F33: 82, + 0x10F34: 68, + 0x10F35: 68, + 0x10F36: 68, + 0x10F37: 68, + 0x10F38: 68, + 0x10F39: 68, + 0x10F3A: 68, + 0x10F3B: 68, + 0x10F3C: 68, + 0x10F3D: 68, + 0x10F3E: 68, + 0x10F3F: 68, + 0x10F40: 68, + 0x10F41: 68, + 0x10F42: 68, + 0x10F43: 68, + 0x10F44: 68, + 0x10F46: 84, + 0x10F47: 84, + 0x10F48: 84, + 0x10F49: 84, + 0x10F4A: 84, + 0x10F4B: 84, + 0x10F4C: 84, + 0x10F4D: 84, + 0x10F4E: 84, + 0x10F4F: 84, + 0x10F50: 84, + 0x10F51: 68, + 0x10F52: 68, + 0x10F53: 68, + 0x10F54: 82, + 0x10F70: 68, + 0x10F71: 68, + 0x10F72: 68, + 0x10F73: 68, + 0x10F74: 82, + 0x10F75: 82, + 0x10F76: 68, + 0x10F77: 68, + 0x10F78: 68, + 0x10F79: 68, + 0x10F7A: 68, + 0x10F7B: 68, + 0x10F7C: 68, + 0x10F7D: 68, + 0x10F7E: 68, + 0x10F7F: 68, + 0x10F80: 68, + 0x10F81: 68, + 0x10F82: 84, + 0x10F83: 84, + 0x10F84: 84, + 0x10F85: 84, + 0x10FB0: 68, + 0x10FB2: 68, + 0x10FB3: 68, + 0x10FB4: 82, + 0x10FB5: 82, + 0x10FB6: 82, + 0x10FB8: 68, + 0x10FB9: 82, + 0x10FBA: 82, + 0x10FBB: 68, + 0x10FBC: 68, + 0x10FBD: 82, + 0x10FBE: 68, + 0x10FBF: 68, + 0x10FC1: 68, + 0x10FC2: 82, + 0x10FC3: 82, + 0x10FC4: 68, + 0x10FC9: 82, + 0x10FCA: 68, + 0x10FCB: 76, + 0x11001: 84, + 0x11038: 84, + 0x11039: 84, + 0x1103A: 84, + 0x1103B: 84, + 0x1103C: 84, + 0x1103D: 84, + 0x1103E: 84, + 0x1103F: 84, + 0x11040: 84, + 0x11041: 84, + 0x11042: 84, + 0x11043: 84, + 0x11044: 84, + 0x11045: 84, + 0x11046: 84, + 0x11070: 84, + 0x11073: 84, + 0x11074: 84, + 0x1107F: 84, + 0x11080: 84, + 0x11081: 84, + 0x110B3: 84, + 0x110B4: 84, + 0x110B5: 84, + 0x110B6: 84, + 0x110B9: 84, + 0x110BA: 84, + 0x110C2: 84, + 0x11100: 84, + 0x11101: 84, + 0x11102: 84, + 0x11127: 84, + 0x11128: 84, + 0x11129: 84, + 0x1112A: 84, + 0x1112B: 84, + 0x1112D: 84, + 0x1112E: 84, + 0x1112F: 84, + 0x11130: 84, + 0x11131: 84, + 0x11132: 84, + 0x11133: 84, + 0x11134: 84, + 0x11173: 84, + 0x11180: 84, + 0x11181: 84, + 0x111B6: 84, + 0x111B7: 84, + 0x111B8: 84, + 0x111B9: 84, + 0x111BA: 84, + 0x111BB: 84, + 0x111BC: 84, + 0x111BD: 84, + 0x111BE: 84, + 0x111C9: 84, + 0x111CA: 84, + 0x111CB: 84, + 0x111CC: 84, + 0x111CF: 84, + 0x1122F: 84, + 0x11230: 84, + 0x11231: 84, + 0x11234: 84, + 0x11236: 84, + 0x11237: 84, + 0x1123E: 84, + 0x11241: 84, + 0x112DF: 84, + 0x112E3: 84, + 0x112E4: 84, + 0x112E5: 84, + 0x112E6: 84, + 0x112E7: 84, + 0x112E8: 84, + 0x112E9: 84, + 0x112EA: 84, + 0x11300: 84, + 0x11301: 84, + 0x1133B: 84, + 0x1133C: 84, + 0x11340: 84, + 0x11366: 84, + 0x11367: 84, + 0x11368: 84, + 0x11369: 84, + 0x1136A: 84, + 0x1136B: 84, + 0x1136C: 84, + 0x11370: 84, + 0x11371: 84, + 0x11372: 84, + 0x11373: 84, + 0x11374: 84, + 0x11438: 84, + 0x11439: 84, + 0x1143A: 84, + 0x1143B: 84, + 0x1143C: 84, + 0x1143D: 84, + 0x1143E: 84, + 0x1143F: 84, + 0x11442: 84, + 0x11443: 84, + 0x11444: 84, + 0x11446: 84, + 0x1145E: 84, + 0x114B3: 84, + 0x114B4: 84, + 0x114B5: 84, + 0x114B6: 84, + 0x114B7: 84, + 0x114B8: 84, + 0x114BA: 84, + 0x114BF: 84, + 0x114C0: 84, + 0x114C2: 84, + 0x114C3: 84, + 0x115B2: 84, + 0x115B3: 84, + 0x115B4: 84, + 0x115B5: 84, + 0x115BC: 84, + 0x115BD: 84, + 0x115BF: 84, + 0x115C0: 84, + 0x115DC: 84, + 0x115DD: 84, + 0x11633: 84, + 0x11634: 84, + 0x11635: 84, + 0x11636: 84, + 0x11637: 84, + 0x11638: 84, + 0x11639: 84, + 0x1163A: 84, + 0x1163D: 84, + 0x1163F: 84, + 0x11640: 84, + 0x116AB: 84, + 0x116AD: 84, + 0x116B0: 84, + 0x116B1: 84, + 0x116B2: 84, + 0x116B3: 84, + 0x116B4: 84, + 0x116B5: 84, + 0x116B7: 84, + 0x1171D: 84, + 0x1171E: 84, + 0x1171F: 84, + 0x11722: 84, + 0x11723: 84, + 0x11724: 84, + 0x11725: 84, + 0x11727: 84, + 0x11728: 84, + 0x11729: 84, + 0x1172A: 84, + 0x1172B: 84, + 0x1182F: 84, + 0x11830: 84, + 0x11831: 84, + 0x11832: 84, + 0x11833: 84, + 0x11834: 84, + 0x11835: 84, + 0x11836: 84, + 0x11837: 84, + 0x11839: 84, + 0x1183A: 84, + 0x1193B: 84, + 0x1193C: 84, + 0x1193E: 84, + 0x11943: 84, + 0x119D4: 84, + 0x119D5: 84, + 0x119D6: 84, + 0x119D7: 84, + 0x119DA: 84, + 0x119DB: 84, + 0x119E0: 84, + 0x11A01: 84, + 0x11A02: 84, + 0x11A03: 84, + 0x11A04: 84, + 0x11A05: 84, + 0x11A06: 84, + 0x11A07: 84, + 0x11A08: 84, + 0x11A09: 84, + 0x11A0A: 84, + 0x11A33: 84, + 0x11A34: 84, + 0x11A35: 84, + 0x11A36: 84, + 0x11A37: 84, + 0x11A38: 84, + 0x11A3B: 84, + 0x11A3C: 84, + 0x11A3D: 84, + 0x11A3E: 84, + 0x11A47: 84, + 0x11A51: 84, + 0x11A52: 84, + 0x11A53: 84, + 0x11A54: 84, + 0x11A55: 84, + 0x11A56: 84, + 0x11A59: 84, + 0x11A5A: 84, + 0x11A5B: 84, + 0x11A8A: 84, + 0x11A8B: 84, + 0x11A8C: 84, + 0x11A8D: 84, + 0x11A8E: 84, + 0x11A8F: 84, + 0x11A90: 84, + 0x11A91: 84, + 0x11A92: 84, + 0x11A93: 84, + 0x11A94: 84, + 0x11A95: 84, + 0x11A96: 84, + 0x11A98: 84, + 0x11A99: 84, + 0x11C30: 84, + 0x11C31: 84, + 0x11C32: 84, + 0x11C33: 84, + 0x11C34: 84, + 0x11C35: 84, + 0x11C36: 84, + 0x11C38: 84, + 0x11C39: 84, + 0x11C3A: 84, + 0x11C3B: 84, + 0x11C3C: 84, + 0x11C3D: 84, + 0x11C3F: 84, + 0x11C92: 84, + 0x11C93: 84, + 0x11C94: 84, + 0x11C95: 84, + 0x11C96: 84, + 0x11C97: 84, + 0x11C98: 84, + 0x11C99: 84, + 0x11C9A: 84, + 0x11C9B: 84, + 0x11C9C: 84, + 0x11C9D: 84, + 0x11C9E: 84, + 0x11C9F: 84, + 0x11CA0: 84, + 0x11CA1: 84, + 0x11CA2: 84, + 0x11CA3: 84, + 0x11CA4: 84, + 0x11CA5: 84, + 0x11CA6: 84, + 0x11CA7: 84, + 0x11CAA: 84, + 0x11CAB: 84, + 0x11CAC: 84, + 0x11CAD: 84, + 0x11CAE: 84, + 0x11CAF: 84, + 0x11CB0: 84, + 0x11CB2: 84, + 0x11CB3: 84, + 0x11CB5: 84, + 0x11CB6: 84, + 0x11D31: 84, + 0x11D32: 84, + 0x11D33: 84, + 0x11D34: 84, + 0x11D35: 84, + 0x11D36: 84, + 0x11D3A: 84, + 0x11D3C: 84, + 0x11D3D: 84, + 0x11D3F: 84, + 0x11D40: 84, + 0x11D41: 84, + 0x11D42: 84, + 0x11D43: 84, + 0x11D44: 84, + 0x11D45: 84, + 0x11D47: 84, + 0x11D90: 84, + 0x11D91: 84, + 0x11D95: 84, + 0x11D97: 84, + 0x11EF3: 84, + 0x11EF4: 84, + 0x11F00: 84, + 0x11F01: 84, + 0x11F36: 84, + 0x11F37: 84, + 0x11F38: 84, + 0x11F39: 84, + 0x11F3A: 84, + 0x11F40: 84, + 0x11F42: 84, + 0x13430: 84, + 0x13431: 84, + 0x13432: 84, + 0x13433: 84, + 0x13434: 84, + 0x13435: 84, + 0x13436: 84, + 0x13437: 84, + 0x13438: 84, + 0x13439: 84, + 0x1343A: 84, + 0x1343B: 84, + 0x1343C: 84, + 0x1343D: 84, + 0x1343E: 84, + 0x1343F: 84, + 0x13440: 84, + 0x13447: 84, + 0x13448: 84, + 0x13449: 84, + 0x1344A: 84, + 0x1344B: 84, + 0x1344C: 84, + 0x1344D: 84, + 0x1344E: 84, + 0x1344F: 84, + 0x13450: 84, + 0x13451: 84, + 0x13452: 84, + 0x13453: 84, + 0x13454: 84, + 0x13455: 84, + 0x16AF0: 84, + 0x16AF1: 84, + 0x16AF2: 84, + 0x16AF3: 84, + 0x16AF4: 84, + 0x16B30: 84, + 0x16B31: 84, + 0x16B32: 84, + 0x16B33: 84, + 0x16B34: 84, + 0x16B35: 84, + 0x16B36: 84, + 0x16F4F: 84, + 0x16F8F: 84, + 0x16F90: 84, + 0x16F91: 84, + 0x16F92: 84, + 0x16FE4: 84, + 0x1BC9D: 84, + 0x1BC9E: 84, + 0x1BCA0: 84, + 0x1BCA1: 84, + 0x1BCA2: 84, + 0x1BCA3: 84, + 0x1CF00: 84, + 0x1CF01: 84, + 0x1CF02: 84, + 0x1CF03: 84, + 0x1CF04: 84, + 0x1CF05: 84, + 0x1CF06: 84, + 0x1CF07: 84, + 0x1CF08: 84, + 0x1CF09: 84, + 0x1CF0A: 84, + 0x1CF0B: 84, + 0x1CF0C: 84, + 0x1CF0D: 84, + 0x1CF0E: 84, + 0x1CF0F: 84, + 0x1CF10: 84, + 0x1CF11: 84, + 0x1CF12: 84, + 0x1CF13: 84, + 0x1CF14: 84, + 0x1CF15: 84, + 0x1CF16: 84, + 0x1CF17: 84, + 0x1CF18: 84, + 0x1CF19: 84, + 0x1CF1A: 84, + 0x1CF1B: 84, + 0x1CF1C: 84, + 0x1CF1D: 84, + 0x1CF1E: 84, + 0x1CF1F: 84, + 0x1CF20: 84, + 0x1CF21: 84, + 0x1CF22: 84, + 0x1CF23: 84, + 0x1CF24: 84, + 0x1CF25: 84, + 0x1CF26: 84, + 0x1CF27: 84, + 0x1CF28: 84, + 0x1CF29: 84, + 0x1CF2A: 84, + 0x1CF2B: 84, + 0x1CF2C: 84, + 0x1CF2D: 84, + 0x1CF30: 84, + 0x1CF31: 84, + 0x1CF32: 84, + 0x1CF33: 84, + 0x1CF34: 84, + 0x1CF35: 84, + 0x1CF36: 84, + 0x1CF37: 84, + 0x1CF38: 84, + 0x1CF39: 84, + 0x1CF3A: 84, + 0x1CF3B: 84, + 0x1CF3C: 84, + 0x1CF3D: 84, + 0x1CF3E: 84, + 0x1CF3F: 84, + 0x1CF40: 84, + 0x1CF41: 84, + 0x1CF42: 84, + 0x1CF43: 84, + 0x1CF44: 84, + 0x1CF45: 84, + 0x1CF46: 84, + 0x1D167: 84, + 0x1D168: 84, + 0x1D169: 84, + 0x1D173: 84, + 0x1D174: 84, + 0x1D175: 84, + 0x1D176: 84, + 0x1D177: 84, + 0x1D178: 84, + 0x1D179: 84, + 0x1D17A: 84, + 0x1D17B: 84, + 0x1D17C: 84, + 0x1D17D: 84, + 0x1D17E: 84, + 0x1D17F: 84, + 0x1D180: 84, + 0x1D181: 84, + 0x1D182: 84, + 0x1D185: 84, + 0x1D186: 84, + 0x1D187: 84, + 0x1D188: 84, + 0x1D189: 84, + 0x1D18A: 84, + 0x1D18B: 84, + 0x1D1AA: 84, + 0x1D1AB: 84, + 0x1D1AC: 84, + 0x1D1AD: 84, + 0x1D242: 84, + 0x1D243: 84, + 0x1D244: 84, + 0x1DA00: 84, + 0x1DA01: 84, + 0x1DA02: 84, + 0x1DA03: 84, + 0x1DA04: 84, + 0x1DA05: 84, + 0x1DA06: 84, + 0x1DA07: 84, + 0x1DA08: 84, + 0x1DA09: 84, + 0x1DA0A: 84, + 0x1DA0B: 84, + 0x1DA0C: 84, + 0x1DA0D: 84, + 0x1DA0E: 84, + 0x1DA0F: 84, + 0x1DA10: 84, + 0x1DA11: 84, + 0x1DA12: 84, + 0x1DA13: 84, + 0x1DA14: 84, + 0x1DA15: 84, + 0x1DA16: 84, + 0x1DA17: 84, + 0x1DA18: 84, + 0x1DA19: 84, + 0x1DA1A: 84, + 0x1DA1B: 84, + 0x1DA1C: 84, + 0x1DA1D: 84, + 0x1DA1E: 84, + 0x1DA1F: 84, + 0x1DA20: 84, + 0x1DA21: 84, + 0x1DA22: 84, + 0x1DA23: 84, + 0x1DA24: 84, + 0x1DA25: 84, + 0x1DA26: 84, + 0x1DA27: 84, + 0x1DA28: 84, + 0x1DA29: 84, + 0x1DA2A: 84, + 0x1DA2B: 84, + 0x1DA2C: 84, + 0x1DA2D: 84, + 0x1DA2E: 84, + 0x1DA2F: 84, + 0x1DA30: 84, + 0x1DA31: 84, + 0x1DA32: 84, + 0x1DA33: 84, + 0x1DA34: 84, + 0x1DA35: 84, + 0x1DA36: 84, + 0x1DA3B: 84, + 0x1DA3C: 84, + 0x1DA3D: 84, + 0x1DA3E: 84, + 0x1DA3F: 84, + 0x1DA40: 84, + 0x1DA41: 84, + 0x1DA42: 84, + 0x1DA43: 84, + 0x1DA44: 84, + 0x1DA45: 84, + 0x1DA46: 84, + 0x1DA47: 84, + 0x1DA48: 84, + 0x1DA49: 84, + 0x1DA4A: 84, + 0x1DA4B: 84, + 0x1DA4C: 84, + 0x1DA4D: 84, + 0x1DA4E: 84, + 0x1DA4F: 84, + 0x1DA50: 84, + 0x1DA51: 84, + 0x1DA52: 84, + 0x1DA53: 84, + 0x1DA54: 84, + 0x1DA55: 84, + 0x1DA56: 84, + 0x1DA57: 84, + 0x1DA58: 84, + 0x1DA59: 84, + 0x1DA5A: 84, + 0x1DA5B: 84, + 0x1DA5C: 84, + 0x1DA5D: 84, + 0x1DA5E: 84, + 0x1DA5F: 84, + 0x1DA60: 84, + 0x1DA61: 84, + 0x1DA62: 84, + 0x1DA63: 84, + 0x1DA64: 84, + 0x1DA65: 84, + 0x1DA66: 84, + 0x1DA67: 84, + 0x1DA68: 84, + 0x1DA69: 84, + 0x1DA6A: 84, + 0x1DA6B: 84, + 0x1DA6C: 84, + 0x1DA75: 84, + 0x1DA84: 84, + 0x1DA9B: 84, + 0x1DA9C: 84, + 0x1DA9D: 84, + 0x1DA9E: 84, + 0x1DA9F: 84, + 0x1DAA1: 84, + 0x1DAA2: 84, + 0x1DAA3: 84, + 0x1DAA4: 84, + 0x1DAA5: 84, + 0x1DAA6: 84, + 0x1DAA7: 84, + 0x1DAA8: 84, + 0x1DAA9: 84, + 0x1DAAA: 84, + 0x1DAAB: 84, + 0x1DAAC: 84, + 0x1DAAD: 84, + 0x1DAAE: 84, + 0x1DAAF: 84, + 0x1E000: 84, + 0x1E001: 84, + 0x1E002: 84, + 0x1E003: 84, + 0x1E004: 84, + 0x1E005: 84, + 0x1E006: 84, + 0x1E008: 84, + 0x1E009: 84, + 0x1E00A: 84, + 0x1E00B: 84, + 0x1E00C: 84, + 0x1E00D: 84, + 0x1E00E: 84, + 0x1E00F: 84, + 0x1E010: 84, + 0x1E011: 84, + 0x1E012: 84, + 0x1E013: 84, + 0x1E014: 84, + 0x1E015: 84, + 0x1E016: 84, + 0x1E017: 84, + 0x1E018: 84, + 0x1E01B: 84, + 0x1E01C: 84, + 0x1E01D: 84, + 0x1E01E: 84, + 0x1E01F: 84, + 0x1E020: 84, + 0x1E021: 84, + 0x1E023: 84, + 0x1E024: 84, + 0x1E026: 84, + 0x1E027: 84, + 0x1E028: 84, + 0x1E029: 84, + 0x1E02A: 84, + 0x1E08F: 84, + 0x1E130: 84, + 0x1E131: 84, + 0x1E132: 84, + 0x1E133: 84, + 0x1E134: 84, + 0x1E135: 84, + 0x1E136: 84, + 0x1E2AE: 84, + 0x1E2EC: 84, + 0x1E2ED: 84, + 0x1E2EE: 84, + 0x1E2EF: 84, + 0x1E4EC: 84, + 0x1E4ED: 84, + 0x1E4EE: 84, + 0x1E4EF: 84, + 0x1E8D0: 84, + 0x1E8D1: 84, + 0x1E8D2: 84, + 0x1E8D3: 84, + 0x1E8D4: 84, + 0x1E8D5: 84, + 0x1E8D6: 84, + 0x1E900: 68, + 0x1E901: 68, + 0x1E902: 68, + 0x1E903: 68, + 0x1E904: 68, + 0x1E905: 68, + 0x1E906: 68, + 0x1E907: 68, + 0x1E908: 68, + 0x1E909: 68, + 0x1E90A: 68, + 0x1E90B: 68, + 0x1E90C: 68, + 0x1E90D: 68, + 0x1E90E: 68, + 0x1E90F: 68, + 0x1E910: 68, + 0x1E911: 68, + 0x1E912: 68, + 0x1E913: 68, + 0x1E914: 68, + 0x1E915: 68, + 0x1E916: 68, + 0x1E917: 68, + 0x1E918: 68, + 0x1E919: 68, + 0x1E91A: 68, + 0x1E91B: 68, + 0x1E91C: 68, + 0x1E91D: 68, + 0x1E91E: 68, + 0x1E91F: 68, + 0x1E920: 68, + 0x1E921: 68, + 0x1E922: 68, + 0x1E923: 68, + 0x1E924: 68, + 0x1E925: 68, + 0x1E926: 68, + 0x1E927: 68, + 0x1E928: 68, + 0x1E929: 68, + 0x1E92A: 68, + 0x1E92B: 68, + 0x1E92C: 68, + 0x1E92D: 68, + 0x1E92E: 68, + 0x1E92F: 68, + 0x1E930: 68, + 0x1E931: 68, + 0x1E932: 68, + 0x1E933: 68, + 0x1E934: 68, + 0x1E935: 68, + 0x1E936: 68, + 0x1E937: 68, + 0x1E938: 68, + 0x1E939: 68, + 0x1E93A: 68, + 0x1E93B: 68, + 0x1E93C: 68, + 0x1E93D: 68, + 0x1E93E: 68, + 0x1E93F: 68, + 0x1E940: 68, + 0x1E941: 68, + 0x1E942: 68, + 0x1E943: 68, + 0x1E944: 84, + 0x1E945: 84, + 0x1E946: 84, + 0x1E947: 84, + 0x1E948: 84, + 0x1E949: 84, + 0x1E94A: 84, + 0x1E94B: 84, + 0xE0001: 84, + 0xE0020: 84, + 0xE0021: 84, + 0xE0022: 84, + 0xE0023: 84, + 0xE0024: 84, + 0xE0025: 84, + 0xE0026: 84, + 0xE0027: 84, + 0xE0028: 84, + 0xE0029: 84, + 0xE002A: 84, + 0xE002B: 84, + 0xE002C: 84, + 0xE002D: 84, + 0xE002E: 84, + 0xE002F: 84, + 0xE0030: 84, + 0xE0031: 84, + 0xE0032: 84, + 0xE0033: 84, + 0xE0034: 84, + 0xE0035: 84, + 0xE0036: 84, + 0xE0037: 84, + 0xE0038: 84, + 0xE0039: 84, + 0xE003A: 84, + 0xE003B: 84, + 0xE003C: 84, + 0xE003D: 84, + 0xE003E: 84, + 0xE003F: 84, + 0xE0040: 84, + 0xE0041: 84, + 0xE0042: 84, + 0xE0043: 84, + 0xE0044: 84, + 0xE0045: 84, + 0xE0046: 84, + 0xE0047: 84, + 0xE0048: 84, + 0xE0049: 84, + 0xE004A: 84, + 0xE004B: 84, + 0xE004C: 84, + 0xE004D: 84, + 0xE004E: 84, + 0xE004F: 84, + 0xE0050: 84, + 0xE0051: 84, + 0xE0052: 84, + 0xE0053: 84, + 0xE0054: 84, + 0xE0055: 84, + 0xE0056: 84, + 0xE0057: 84, + 0xE0058: 84, + 0xE0059: 84, + 0xE005A: 84, + 0xE005B: 84, + 0xE005C: 84, + 0xE005D: 84, + 0xE005E: 84, + 0xE005F: 84, + 0xE0060: 84, + 0xE0061: 84, + 0xE0062: 84, + 0xE0063: 84, + 0xE0064: 84, + 0xE0065: 84, + 0xE0066: 84, + 0xE0067: 84, + 0xE0068: 84, + 0xE0069: 84, + 0xE006A: 84, + 0xE006B: 84, + 0xE006C: 84, + 0xE006D: 84, + 0xE006E: 84, + 0xE006F: 84, + 0xE0070: 84, + 0xE0071: 84, + 0xE0072: 84, + 0xE0073: 84, + 0xE0074: 84, + 0xE0075: 84, + 0xE0076: 84, + 0xE0077: 84, + 0xE0078: 84, + 0xE0079: 84, + 0xE007A: 84, + 0xE007B: 84, + 0xE007C: 84, + 0xE007D: 84, + 0xE007E: 84, + 0xE007F: 84, + 0xE0100: 84, + 0xE0101: 84, + 0xE0102: 84, + 0xE0103: 84, + 0xE0104: 84, + 0xE0105: 84, + 0xE0106: 84, + 0xE0107: 84, + 0xE0108: 84, + 0xE0109: 84, + 0xE010A: 84, + 0xE010B: 84, + 0xE010C: 84, + 0xE010D: 84, + 0xE010E: 84, + 0xE010F: 84, + 0xE0110: 84, + 0xE0111: 84, + 0xE0112: 84, + 0xE0113: 84, + 0xE0114: 84, + 0xE0115: 84, + 0xE0116: 84, + 0xE0117: 84, + 0xE0118: 84, + 0xE0119: 84, + 0xE011A: 84, + 0xE011B: 84, + 0xE011C: 84, + 0xE011D: 84, + 0xE011E: 84, + 0xE011F: 84, + 0xE0120: 84, + 0xE0121: 84, + 0xE0122: 84, + 0xE0123: 84, + 0xE0124: 84, + 0xE0125: 84, + 0xE0126: 84, + 0xE0127: 84, + 0xE0128: 84, + 0xE0129: 84, + 0xE012A: 84, + 0xE012B: 84, + 0xE012C: 84, + 0xE012D: 84, + 0xE012E: 84, + 0xE012F: 84, + 0xE0130: 84, + 0xE0131: 84, + 0xE0132: 84, + 0xE0133: 84, + 0xE0134: 84, + 0xE0135: 84, + 0xE0136: 84, + 0xE0137: 84, + 0xE0138: 84, + 0xE0139: 84, + 0xE013A: 84, + 0xE013B: 84, + 0xE013C: 84, + 0xE013D: 84, + 0xE013E: 84, + 0xE013F: 84, + 0xE0140: 84, + 0xE0141: 84, + 0xE0142: 84, + 0xE0143: 84, + 0xE0144: 84, + 0xE0145: 84, + 0xE0146: 84, + 0xE0147: 84, + 0xE0148: 84, + 0xE0149: 84, + 0xE014A: 84, + 0xE014B: 84, + 0xE014C: 84, + 0xE014D: 84, + 0xE014E: 84, + 0xE014F: 84, + 0xE0150: 84, + 0xE0151: 84, + 0xE0152: 84, + 0xE0153: 84, + 0xE0154: 84, + 0xE0155: 84, + 0xE0156: 84, + 0xE0157: 84, + 0xE0158: 84, + 0xE0159: 84, + 0xE015A: 84, + 0xE015B: 84, + 0xE015C: 84, + 0xE015D: 84, + 0xE015E: 84, + 0xE015F: 84, + 0xE0160: 84, + 0xE0161: 84, + 0xE0162: 84, + 0xE0163: 84, + 0xE0164: 84, + 0xE0165: 84, + 0xE0166: 84, + 0xE0167: 84, + 0xE0168: 84, + 0xE0169: 84, + 0xE016A: 84, + 0xE016B: 84, + 0xE016C: 84, + 0xE016D: 84, + 0xE016E: 84, + 0xE016F: 84, + 0xE0170: 84, + 0xE0171: 84, + 0xE0172: 84, + 0xE0173: 84, + 0xE0174: 84, + 0xE0175: 84, + 0xE0176: 84, + 0xE0177: 84, + 0xE0178: 84, + 0xE0179: 84, + 0xE017A: 84, + 0xE017B: 84, + 0xE017C: 84, + 0xE017D: 84, + 0xE017E: 84, + 0xE017F: 84, + 0xE0180: 84, + 0xE0181: 84, + 0xE0182: 84, + 0xE0183: 84, + 0xE0184: 84, + 0xE0185: 84, + 0xE0186: 84, + 0xE0187: 84, + 0xE0188: 84, + 0xE0189: 84, + 0xE018A: 84, + 0xE018B: 84, + 0xE018C: 84, + 0xE018D: 84, + 0xE018E: 84, + 0xE018F: 84, + 0xE0190: 84, + 0xE0191: 84, + 0xE0192: 84, + 0xE0193: 84, + 0xE0194: 84, + 0xE0195: 84, + 0xE0196: 84, + 0xE0197: 84, + 0xE0198: 84, + 0xE0199: 84, + 0xE019A: 84, + 0xE019B: 84, + 0xE019C: 84, + 0xE019D: 84, + 0xE019E: 84, + 0xE019F: 84, + 0xE01A0: 84, + 0xE01A1: 84, + 0xE01A2: 84, + 0xE01A3: 84, + 0xE01A4: 84, + 0xE01A5: 84, + 0xE01A6: 84, + 0xE01A7: 84, + 0xE01A8: 84, + 0xE01A9: 84, + 0xE01AA: 84, + 0xE01AB: 84, + 0xE01AC: 84, + 0xE01AD: 84, + 0xE01AE: 84, + 0xE01AF: 84, + 0xE01B0: 84, + 0xE01B1: 84, + 0xE01B2: 84, + 0xE01B3: 84, + 0xE01B4: 84, + 0xE01B5: 84, + 0xE01B6: 84, + 0xE01B7: 84, + 0xE01B8: 84, + 0xE01B9: 84, + 0xE01BA: 84, + 0xE01BB: 84, + 0xE01BC: 84, + 0xE01BD: 84, + 0xE01BE: 84, + 0xE01BF: 84, + 0xE01C0: 84, + 0xE01C1: 84, + 0xE01C2: 84, + 0xE01C3: 84, + 0xE01C4: 84, + 0xE01C5: 84, + 0xE01C6: 84, + 0xE01C7: 84, + 0xE01C8: 84, + 0xE01C9: 84, + 0xE01CA: 84, + 0xE01CB: 84, + 0xE01CC: 84, + 0xE01CD: 84, + 0xE01CE: 84, + 0xE01CF: 84, + 0xE01D0: 84, + 0xE01D1: 84, + 0xE01D2: 84, + 0xE01D3: 84, + 0xE01D4: 84, + 0xE01D5: 84, + 0xE01D6: 84, + 0xE01D7: 84, + 0xE01D8: 84, + 0xE01D9: 84, + 0xE01DA: 84, + 0xE01DB: 84, + 0xE01DC: 84, + 0xE01DD: 84, + 0xE01DE: 84, + 0xE01DF: 84, + 0xE01E0: 84, + 0xE01E1: 84, + 0xE01E2: 84, + 0xE01E3: 84, + 0xE01E4: 84, + 0xE01E5: 84, + 0xE01E6: 84, + 0xE01E7: 84, + 0xE01E8: 84, + 0xE01E9: 84, + 0xE01EA: 84, + 0xE01EB: 84, + 0xE01EC: 84, + 0xE01ED: 84, + 0xE01EE: 84, + 0xE01EF: 84, +} +codepoint_classes = { + "PVALID": ( + 0x2D0000002E, + 0x300000003A, + 0x610000007B, + 0xDF000000F7, + 0xF800000100, + 0x10100000102, + 0x10300000104, + 0x10500000106, + 0x10700000108, + 0x1090000010A, + 0x10B0000010C, + 0x10D0000010E, + 0x10F00000110, + 0x11100000112, + 0x11300000114, + 0x11500000116, + 0x11700000118, + 0x1190000011A, + 0x11B0000011C, + 0x11D0000011E, + 0x11F00000120, + 0x12100000122, + 0x12300000124, + 0x12500000126, + 0x12700000128, + 0x1290000012A, + 0x12B0000012C, + 0x12D0000012E, + 0x12F00000130, + 0x13100000132, + 0x13500000136, + 0x13700000139, + 0x13A0000013B, + 0x13C0000013D, + 0x13E0000013F, + 0x14200000143, + 0x14400000145, + 0x14600000147, + 0x14800000149, + 0x14B0000014C, + 0x14D0000014E, + 0x14F00000150, + 0x15100000152, + 0x15300000154, + 0x15500000156, + 0x15700000158, + 0x1590000015A, + 0x15B0000015C, + 0x15D0000015E, + 0x15F00000160, + 0x16100000162, + 0x16300000164, + 0x16500000166, + 0x16700000168, + 0x1690000016A, + 0x16B0000016C, + 0x16D0000016E, + 0x16F00000170, + 0x17100000172, + 0x17300000174, + 0x17500000176, + 0x17700000178, + 0x17A0000017B, + 0x17C0000017D, + 0x17E0000017F, + 0x18000000181, + 0x18300000184, + 0x18500000186, + 0x18800000189, + 0x18C0000018E, + 0x19200000193, + 0x19500000196, + 0x1990000019C, + 0x19E0000019F, + 0x1A1000001A2, + 0x1A3000001A4, + 0x1A5000001A6, + 0x1A8000001A9, + 0x1AA000001AC, + 0x1AD000001AE, + 0x1B0000001B1, + 0x1B4000001B5, + 0x1B6000001B7, + 0x1B9000001BC, + 0x1BD000001C4, + 0x1CE000001CF, + 0x1D0000001D1, + 0x1D2000001D3, + 0x1D4000001D5, + 0x1D6000001D7, + 0x1D8000001D9, + 0x1DA000001DB, + 0x1DC000001DE, + 0x1DF000001E0, + 0x1E1000001E2, + 0x1E3000001E4, + 0x1E5000001E6, + 0x1E7000001E8, + 0x1E9000001EA, + 0x1EB000001EC, + 0x1ED000001EE, + 0x1EF000001F1, + 0x1F5000001F6, + 0x1F9000001FA, + 0x1FB000001FC, + 0x1FD000001FE, + 0x1FF00000200, + 0x20100000202, + 0x20300000204, + 0x20500000206, + 0x20700000208, + 0x2090000020A, + 0x20B0000020C, + 0x20D0000020E, + 0x20F00000210, + 0x21100000212, + 0x21300000214, + 0x21500000216, + 0x21700000218, + 0x2190000021A, + 0x21B0000021C, + 0x21D0000021E, + 0x21F00000220, + 0x22100000222, + 0x22300000224, + 0x22500000226, + 0x22700000228, + 0x2290000022A, + 0x22B0000022C, + 0x22D0000022E, + 0x22F00000230, + 0x23100000232, + 0x2330000023A, + 0x23C0000023D, + 0x23F00000241, + 0x24200000243, + 0x24700000248, + 0x2490000024A, + 0x24B0000024C, + 0x24D0000024E, + 0x24F000002B0, + 0x2B9000002C2, + 0x2C6000002D2, + 0x2EC000002ED, + 0x2EE000002EF, + 0x30000000340, + 0x34200000343, + 0x3460000034F, + 0x35000000370, + 0x37100000372, + 0x37300000374, + 0x37700000378, + 0x37B0000037E, + 0x39000000391, + 0x3AC000003CF, + 0x3D7000003D8, + 0x3D9000003DA, + 0x3DB000003DC, + 0x3DD000003DE, + 0x3DF000003E0, + 0x3E1000003E2, + 0x3E3000003E4, + 0x3E5000003E6, + 0x3E7000003E8, + 0x3E9000003EA, + 0x3EB000003EC, + 0x3ED000003EE, + 0x3EF000003F0, + 0x3F3000003F4, + 0x3F8000003F9, + 0x3FB000003FD, + 0x43000000460, + 0x46100000462, + 0x46300000464, + 0x46500000466, + 0x46700000468, + 0x4690000046A, + 0x46B0000046C, + 0x46D0000046E, + 0x46F00000470, + 0x47100000472, + 0x47300000474, + 0x47500000476, + 0x47700000478, + 0x4790000047A, + 0x47B0000047C, + 0x47D0000047E, + 0x47F00000480, + 0x48100000482, + 0x48300000488, + 0x48B0000048C, + 0x48D0000048E, + 0x48F00000490, + 0x49100000492, + 0x49300000494, + 0x49500000496, + 0x49700000498, + 0x4990000049A, + 0x49B0000049C, + 0x49D0000049E, + 0x49F000004A0, + 0x4A1000004A2, + 0x4A3000004A4, + 0x4A5000004A6, + 0x4A7000004A8, + 0x4A9000004AA, + 0x4AB000004AC, + 0x4AD000004AE, + 0x4AF000004B0, + 0x4B1000004B2, + 0x4B3000004B4, + 0x4B5000004B6, + 0x4B7000004B8, + 0x4B9000004BA, + 0x4BB000004BC, + 0x4BD000004BE, + 0x4BF000004C0, + 0x4C2000004C3, + 0x4C4000004C5, + 0x4C6000004C7, + 0x4C8000004C9, + 0x4CA000004CB, + 0x4CC000004CD, + 0x4CE000004D0, + 0x4D1000004D2, + 0x4D3000004D4, + 0x4D5000004D6, + 0x4D7000004D8, + 0x4D9000004DA, + 0x4DB000004DC, + 0x4DD000004DE, + 0x4DF000004E0, + 0x4E1000004E2, + 0x4E3000004E4, + 0x4E5000004E6, + 0x4E7000004E8, + 0x4E9000004EA, + 0x4EB000004EC, + 0x4ED000004EE, + 0x4EF000004F0, + 0x4F1000004F2, + 0x4F3000004F4, + 0x4F5000004F6, + 0x4F7000004F8, + 0x4F9000004FA, + 0x4FB000004FC, + 0x4FD000004FE, + 0x4FF00000500, + 0x50100000502, + 0x50300000504, + 0x50500000506, + 0x50700000508, + 0x5090000050A, + 0x50B0000050C, + 0x50D0000050E, + 0x50F00000510, + 0x51100000512, + 0x51300000514, + 0x51500000516, + 0x51700000518, + 0x5190000051A, + 0x51B0000051C, + 0x51D0000051E, + 0x51F00000520, + 0x52100000522, + 0x52300000524, + 0x52500000526, + 0x52700000528, + 0x5290000052A, + 0x52B0000052C, + 0x52D0000052E, + 0x52F00000530, + 0x5590000055A, + 0x56000000587, + 0x58800000589, + 0x591000005BE, + 0x5BF000005C0, + 0x5C1000005C3, + 0x5C4000005C6, + 0x5C7000005C8, + 0x5D0000005EB, + 0x5EF000005F3, + 0x6100000061B, + 0x62000000640, + 0x64100000660, + 0x66E00000675, + 0x679000006D4, + 0x6D5000006DD, + 0x6DF000006E9, + 0x6EA000006F0, + 0x6FA00000700, + 0x7100000074B, + 0x74D000007B2, + 0x7C0000007F6, + 0x7FD000007FE, + 0x8000000082E, + 0x8400000085C, + 0x8600000086B, + 0x87000000888, + 0x8890000088F, + 0x898000008E2, + 0x8E300000958, + 0x96000000964, + 0x96600000970, + 0x97100000984, + 0x9850000098D, + 0x98F00000991, + 0x993000009A9, + 0x9AA000009B1, + 0x9B2000009B3, + 0x9B6000009BA, + 0x9BC000009C5, + 0x9C7000009C9, + 0x9CB000009CF, + 0x9D7000009D8, + 0x9E0000009E4, + 0x9E6000009F2, + 0x9FC000009FD, + 0x9FE000009FF, + 0xA0100000A04, + 0xA0500000A0B, + 0xA0F00000A11, + 0xA1300000A29, + 0xA2A00000A31, + 0xA3200000A33, + 0xA3500000A36, + 0xA3800000A3A, + 0xA3C00000A3D, + 0xA3E00000A43, + 0xA4700000A49, + 0xA4B00000A4E, + 0xA5100000A52, + 0xA5C00000A5D, + 0xA6600000A76, + 0xA8100000A84, + 0xA8500000A8E, + 0xA8F00000A92, + 0xA9300000AA9, + 0xAAA00000AB1, + 0xAB200000AB4, + 0xAB500000ABA, + 0xABC00000AC6, + 0xAC700000ACA, + 0xACB00000ACE, + 0xAD000000AD1, + 0xAE000000AE4, + 0xAE600000AF0, + 0xAF900000B00, + 0xB0100000B04, + 0xB0500000B0D, + 0xB0F00000B11, + 0xB1300000B29, + 0xB2A00000B31, + 0xB3200000B34, + 0xB3500000B3A, + 0xB3C00000B45, + 0xB4700000B49, + 0xB4B00000B4E, + 0xB5500000B58, + 0xB5F00000B64, + 0xB6600000B70, + 0xB7100000B72, + 0xB8200000B84, + 0xB8500000B8B, + 0xB8E00000B91, + 0xB9200000B96, + 0xB9900000B9B, + 0xB9C00000B9D, + 0xB9E00000BA0, + 0xBA300000BA5, + 0xBA800000BAB, + 0xBAE00000BBA, + 0xBBE00000BC3, + 0xBC600000BC9, + 0xBCA00000BCE, + 0xBD000000BD1, + 0xBD700000BD8, + 0xBE600000BF0, + 0xC0000000C0D, + 0xC0E00000C11, + 0xC1200000C29, + 0xC2A00000C3A, + 0xC3C00000C45, + 0xC4600000C49, + 0xC4A00000C4E, + 0xC5500000C57, + 0xC5800000C5B, + 0xC5D00000C5E, + 0xC6000000C64, + 0xC6600000C70, + 0xC8000000C84, + 0xC8500000C8D, + 0xC8E00000C91, + 0xC9200000CA9, + 0xCAA00000CB4, + 0xCB500000CBA, + 0xCBC00000CC5, + 0xCC600000CC9, + 0xCCA00000CCE, + 0xCD500000CD7, + 0xCDD00000CDF, + 0xCE000000CE4, + 0xCE600000CF0, + 0xCF100000CF4, + 0xD0000000D0D, + 0xD0E00000D11, + 0xD1200000D45, + 0xD4600000D49, + 0xD4A00000D4F, + 0xD5400000D58, + 0xD5F00000D64, + 0xD6600000D70, + 0xD7A00000D80, + 0xD8100000D84, + 0xD8500000D97, + 0xD9A00000DB2, + 0xDB300000DBC, + 0xDBD00000DBE, + 0xDC000000DC7, + 0xDCA00000DCB, + 0xDCF00000DD5, + 0xDD600000DD7, + 0xDD800000DE0, + 0xDE600000DF0, + 0xDF200000DF4, + 0xE0100000E33, + 0xE3400000E3B, + 0xE4000000E4F, + 0xE5000000E5A, + 0xE8100000E83, + 0xE8400000E85, + 0xE8600000E8B, + 0xE8C00000EA4, + 0xEA500000EA6, + 0xEA700000EB3, + 0xEB400000EBE, + 0xEC000000EC5, + 0xEC600000EC7, + 0xEC800000ECF, + 0xED000000EDA, + 0xEDE00000EE0, + 0xF0000000F01, + 0xF0B00000F0C, + 0xF1800000F1A, + 0xF2000000F2A, + 0xF3500000F36, + 0xF3700000F38, + 0xF3900000F3A, + 0xF3E00000F43, + 0xF4400000F48, + 0xF4900000F4D, + 0xF4E00000F52, + 0xF5300000F57, + 0xF5800000F5C, + 0xF5D00000F69, + 0xF6A00000F6D, + 0xF7100000F73, + 0xF7400000F75, + 0xF7A00000F81, + 0xF8200000F85, + 0xF8600000F93, + 0xF9400000F98, + 0xF9900000F9D, + 0xF9E00000FA2, + 0xFA300000FA7, + 0xFA800000FAC, + 0xFAD00000FB9, + 0xFBA00000FBD, + 0xFC600000FC7, + 0x10000000104A, + 0x10500000109E, + 0x10D0000010FB, + 0x10FD00001100, + 0x120000001249, + 0x124A0000124E, + 0x125000001257, + 0x125800001259, + 0x125A0000125E, + 0x126000001289, + 0x128A0000128E, + 0x1290000012B1, + 0x12B2000012B6, + 0x12B8000012BF, + 0x12C0000012C1, + 0x12C2000012C6, + 0x12C8000012D7, + 0x12D800001311, + 0x131200001316, + 0x13180000135B, + 0x135D00001360, + 0x138000001390, + 0x13A0000013F6, + 0x14010000166D, + 0x166F00001680, + 0x16810000169B, + 0x16A0000016EB, + 0x16F1000016F9, + 0x170000001716, + 0x171F00001735, + 0x174000001754, + 0x17600000176D, + 0x176E00001771, + 0x177200001774, + 0x1780000017B4, + 0x17B6000017D4, + 0x17D7000017D8, + 0x17DC000017DE, + 0x17E0000017EA, + 0x18100000181A, + 0x182000001879, + 0x1880000018AB, + 0x18B0000018F6, + 0x19000000191F, + 0x19200000192C, + 0x19300000193C, + 0x19460000196E, + 0x197000001975, + 0x1980000019AC, + 0x19B0000019CA, + 0x19D0000019DA, + 0x1A0000001A1C, + 0x1A2000001A5F, + 0x1A6000001A7D, + 0x1A7F00001A8A, + 0x1A9000001A9A, + 0x1AA700001AA8, + 0x1AB000001ABE, + 0x1ABF00001ACF, + 0x1B0000001B4D, + 0x1B5000001B5A, + 0x1B6B00001B74, + 0x1B8000001BF4, + 0x1C0000001C38, + 0x1C4000001C4A, + 0x1C4D00001C7E, + 0x1CD000001CD3, + 0x1CD400001CFB, + 0x1D0000001D2C, + 0x1D2F00001D30, + 0x1D3B00001D3C, + 0x1D4E00001D4F, + 0x1D6B00001D78, + 0x1D7900001D9B, + 0x1DC000001E00, + 0x1E0100001E02, + 0x1E0300001E04, + 0x1E0500001E06, + 0x1E0700001E08, + 0x1E0900001E0A, + 0x1E0B00001E0C, + 0x1E0D00001E0E, + 0x1E0F00001E10, + 0x1E1100001E12, + 0x1E1300001E14, + 0x1E1500001E16, + 0x1E1700001E18, + 0x1E1900001E1A, + 0x1E1B00001E1C, + 0x1E1D00001E1E, + 0x1E1F00001E20, + 0x1E2100001E22, + 0x1E2300001E24, + 0x1E2500001E26, + 0x1E2700001E28, + 0x1E2900001E2A, + 0x1E2B00001E2C, + 0x1E2D00001E2E, + 0x1E2F00001E30, + 0x1E3100001E32, + 0x1E3300001E34, + 0x1E3500001E36, + 0x1E3700001E38, + 0x1E3900001E3A, + 0x1E3B00001E3C, + 0x1E3D00001E3E, + 0x1E3F00001E40, + 0x1E4100001E42, + 0x1E4300001E44, + 0x1E4500001E46, + 0x1E4700001E48, + 0x1E4900001E4A, + 0x1E4B00001E4C, + 0x1E4D00001E4E, + 0x1E4F00001E50, + 0x1E5100001E52, + 0x1E5300001E54, + 0x1E5500001E56, + 0x1E5700001E58, + 0x1E5900001E5A, + 0x1E5B00001E5C, + 0x1E5D00001E5E, + 0x1E5F00001E60, + 0x1E6100001E62, + 0x1E6300001E64, + 0x1E6500001E66, + 0x1E6700001E68, + 0x1E6900001E6A, + 0x1E6B00001E6C, + 0x1E6D00001E6E, + 0x1E6F00001E70, + 0x1E7100001E72, + 0x1E7300001E74, + 0x1E7500001E76, + 0x1E7700001E78, + 0x1E7900001E7A, + 0x1E7B00001E7C, + 0x1E7D00001E7E, + 0x1E7F00001E80, + 0x1E8100001E82, + 0x1E8300001E84, + 0x1E8500001E86, + 0x1E8700001E88, + 0x1E8900001E8A, + 0x1E8B00001E8C, + 0x1E8D00001E8E, + 0x1E8F00001E90, + 0x1E9100001E92, + 0x1E9300001E94, + 0x1E9500001E9A, + 0x1E9C00001E9E, + 0x1E9F00001EA0, + 0x1EA100001EA2, + 0x1EA300001EA4, + 0x1EA500001EA6, + 0x1EA700001EA8, + 0x1EA900001EAA, + 0x1EAB00001EAC, + 0x1EAD00001EAE, + 0x1EAF00001EB0, + 0x1EB100001EB2, + 0x1EB300001EB4, + 0x1EB500001EB6, + 0x1EB700001EB8, + 0x1EB900001EBA, + 0x1EBB00001EBC, + 0x1EBD00001EBE, + 0x1EBF00001EC0, + 0x1EC100001EC2, + 0x1EC300001EC4, + 0x1EC500001EC6, + 0x1EC700001EC8, + 0x1EC900001ECA, + 0x1ECB00001ECC, + 0x1ECD00001ECE, + 0x1ECF00001ED0, + 0x1ED100001ED2, + 0x1ED300001ED4, + 0x1ED500001ED6, + 0x1ED700001ED8, + 0x1ED900001EDA, + 0x1EDB00001EDC, + 0x1EDD00001EDE, + 0x1EDF00001EE0, + 0x1EE100001EE2, + 0x1EE300001EE4, + 0x1EE500001EE6, + 0x1EE700001EE8, + 0x1EE900001EEA, + 0x1EEB00001EEC, + 0x1EED00001EEE, + 0x1EEF00001EF0, + 0x1EF100001EF2, + 0x1EF300001EF4, + 0x1EF500001EF6, + 0x1EF700001EF8, + 0x1EF900001EFA, + 0x1EFB00001EFC, + 0x1EFD00001EFE, + 0x1EFF00001F08, + 0x1F1000001F16, + 0x1F2000001F28, + 0x1F3000001F38, + 0x1F4000001F46, + 0x1F5000001F58, + 0x1F6000001F68, + 0x1F7000001F71, + 0x1F7200001F73, + 0x1F7400001F75, + 0x1F7600001F77, + 0x1F7800001F79, + 0x1F7A00001F7B, + 0x1F7C00001F7D, + 0x1FB000001FB2, + 0x1FB600001FB7, + 0x1FC600001FC7, + 0x1FD000001FD3, + 0x1FD600001FD8, + 0x1FE000001FE3, + 0x1FE400001FE8, + 0x1FF600001FF7, + 0x214E0000214F, + 0x218400002185, + 0x2C3000002C60, + 0x2C6100002C62, + 0x2C6500002C67, + 0x2C6800002C69, + 0x2C6A00002C6B, + 0x2C6C00002C6D, + 0x2C7100002C72, + 0x2C7300002C75, + 0x2C7600002C7C, + 0x2C8100002C82, + 0x2C8300002C84, + 0x2C8500002C86, + 0x2C8700002C88, + 0x2C8900002C8A, + 0x2C8B00002C8C, + 0x2C8D00002C8E, + 0x2C8F00002C90, + 0x2C9100002C92, + 0x2C9300002C94, + 0x2C9500002C96, + 0x2C9700002C98, + 0x2C9900002C9A, + 0x2C9B00002C9C, + 0x2C9D00002C9E, + 0x2C9F00002CA0, + 0x2CA100002CA2, + 0x2CA300002CA4, + 0x2CA500002CA6, + 0x2CA700002CA8, + 0x2CA900002CAA, + 0x2CAB00002CAC, + 0x2CAD00002CAE, + 0x2CAF00002CB0, + 0x2CB100002CB2, + 0x2CB300002CB4, + 0x2CB500002CB6, + 0x2CB700002CB8, + 0x2CB900002CBA, + 0x2CBB00002CBC, + 0x2CBD00002CBE, + 0x2CBF00002CC0, + 0x2CC100002CC2, + 0x2CC300002CC4, + 0x2CC500002CC6, + 0x2CC700002CC8, + 0x2CC900002CCA, + 0x2CCB00002CCC, + 0x2CCD00002CCE, + 0x2CCF00002CD0, + 0x2CD100002CD2, + 0x2CD300002CD4, + 0x2CD500002CD6, + 0x2CD700002CD8, + 0x2CD900002CDA, + 0x2CDB00002CDC, + 0x2CDD00002CDE, + 0x2CDF00002CE0, + 0x2CE100002CE2, + 0x2CE300002CE5, + 0x2CEC00002CED, + 0x2CEE00002CF2, + 0x2CF300002CF4, + 0x2D0000002D26, + 0x2D2700002D28, + 0x2D2D00002D2E, + 0x2D3000002D68, + 0x2D7F00002D97, + 0x2DA000002DA7, + 0x2DA800002DAF, + 0x2DB000002DB7, + 0x2DB800002DBF, + 0x2DC000002DC7, + 0x2DC800002DCF, + 0x2DD000002DD7, + 0x2DD800002DDF, + 0x2DE000002E00, + 0x2E2F00002E30, + 0x300500003008, + 0x302A0000302E, + 0x303C0000303D, + 0x304100003097, + 0x30990000309B, + 0x309D0000309F, + 0x30A1000030FB, + 0x30FC000030FF, + 0x310500003130, + 0x31A0000031C0, + 0x31F000003200, + 0x340000004DC0, + 0x4E000000A48D, + 0xA4D00000A4FE, + 0xA5000000A60D, + 0xA6100000A62C, + 0xA6410000A642, + 0xA6430000A644, + 0xA6450000A646, + 0xA6470000A648, + 0xA6490000A64A, + 0xA64B0000A64C, + 0xA64D0000A64E, + 0xA64F0000A650, + 0xA6510000A652, + 0xA6530000A654, + 0xA6550000A656, + 0xA6570000A658, + 0xA6590000A65A, + 0xA65B0000A65C, + 0xA65D0000A65E, + 0xA65F0000A660, + 0xA6610000A662, + 0xA6630000A664, + 0xA6650000A666, + 0xA6670000A668, + 0xA6690000A66A, + 0xA66B0000A66C, + 0xA66D0000A670, + 0xA6740000A67E, + 0xA67F0000A680, + 0xA6810000A682, + 0xA6830000A684, + 0xA6850000A686, + 0xA6870000A688, + 0xA6890000A68A, + 0xA68B0000A68C, + 0xA68D0000A68E, + 0xA68F0000A690, + 0xA6910000A692, + 0xA6930000A694, + 0xA6950000A696, + 0xA6970000A698, + 0xA6990000A69A, + 0xA69B0000A69C, + 0xA69E0000A6E6, + 0xA6F00000A6F2, + 0xA7170000A720, + 0xA7230000A724, + 0xA7250000A726, + 0xA7270000A728, + 0xA7290000A72A, + 0xA72B0000A72C, + 0xA72D0000A72E, + 0xA72F0000A732, + 0xA7330000A734, + 0xA7350000A736, + 0xA7370000A738, + 0xA7390000A73A, + 0xA73B0000A73C, + 0xA73D0000A73E, + 0xA73F0000A740, + 0xA7410000A742, + 0xA7430000A744, + 0xA7450000A746, + 0xA7470000A748, + 0xA7490000A74A, + 0xA74B0000A74C, + 0xA74D0000A74E, + 0xA74F0000A750, + 0xA7510000A752, + 0xA7530000A754, + 0xA7550000A756, + 0xA7570000A758, + 0xA7590000A75A, + 0xA75B0000A75C, + 0xA75D0000A75E, + 0xA75F0000A760, + 0xA7610000A762, + 0xA7630000A764, + 0xA7650000A766, + 0xA7670000A768, + 0xA7690000A76A, + 0xA76B0000A76C, + 0xA76D0000A76E, + 0xA76F0000A770, + 0xA7710000A779, + 0xA77A0000A77B, + 0xA77C0000A77D, + 0xA77F0000A780, + 0xA7810000A782, + 0xA7830000A784, + 0xA7850000A786, + 0xA7870000A789, + 0xA78C0000A78D, + 0xA78E0000A790, + 0xA7910000A792, + 0xA7930000A796, + 0xA7970000A798, + 0xA7990000A79A, + 0xA79B0000A79C, + 0xA79D0000A79E, + 0xA79F0000A7A0, + 0xA7A10000A7A2, + 0xA7A30000A7A4, + 0xA7A50000A7A6, + 0xA7A70000A7A8, + 0xA7A90000A7AA, + 0xA7AF0000A7B0, + 0xA7B50000A7B6, + 0xA7B70000A7B8, + 0xA7B90000A7BA, + 0xA7BB0000A7BC, + 0xA7BD0000A7BE, + 0xA7BF0000A7C0, + 0xA7C10000A7C2, + 0xA7C30000A7C4, + 0xA7C80000A7C9, + 0xA7CA0000A7CB, + 0xA7D10000A7D2, + 0xA7D30000A7D4, + 0xA7D50000A7D6, + 0xA7D70000A7D8, + 0xA7D90000A7DA, + 0xA7F60000A7F8, + 0xA7FA0000A828, + 0xA82C0000A82D, + 0xA8400000A874, + 0xA8800000A8C6, + 0xA8D00000A8DA, + 0xA8E00000A8F8, + 0xA8FB0000A8FC, + 0xA8FD0000A92E, + 0xA9300000A954, + 0xA9800000A9C1, + 0xA9CF0000A9DA, + 0xA9E00000A9FF, + 0xAA000000AA37, + 0xAA400000AA4E, + 0xAA500000AA5A, + 0xAA600000AA77, + 0xAA7A0000AAC3, + 0xAADB0000AADE, + 0xAAE00000AAF0, + 0xAAF20000AAF7, + 0xAB010000AB07, + 0xAB090000AB0F, + 0xAB110000AB17, + 0xAB200000AB27, + 0xAB280000AB2F, + 0xAB300000AB5B, + 0xAB600000AB69, + 0xABC00000ABEB, + 0xABEC0000ABEE, + 0xABF00000ABFA, + 0xAC000000D7A4, + 0xFA0E0000FA10, + 0xFA110000FA12, + 0xFA130000FA15, + 0xFA1F0000FA20, + 0xFA210000FA22, + 0xFA230000FA25, + 0xFA270000FA2A, + 0xFB1E0000FB1F, + 0xFE200000FE30, + 0xFE730000FE74, + 0x100000001000C, + 0x1000D00010027, + 0x100280001003B, + 0x1003C0001003E, + 0x1003F0001004E, + 0x100500001005E, + 0x10080000100FB, + 0x101FD000101FE, + 0x102800001029D, + 0x102A0000102D1, + 0x102E0000102E1, + 0x1030000010320, + 0x1032D00010341, + 0x103420001034A, + 0x103500001037B, + 0x103800001039E, + 0x103A0000103C4, + 0x103C8000103D0, + 0x104280001049E, + 0x104A0000104AA, + 0x104D8000104FC, + 0x1050000010528, + 0x1053000010564, + 0x10597000105A2, + 0x105A3000105B2, + 0x105B3000105BA, + 0x105BB000105BD, + 0x1060000010737, + 0x1074000010756, + 0x1076000010768, + 0x1078000010781, + 0x1080000010806, + 0x1080800010809, + 0x1080A00010836, + 0x1083700010839, + 0x1083C0001083D, + 0x1083F00010856, + 0x1086000010877, + 0x108800001089F, + 0x108E0000108F3, + 0x108F4000108F6, + 0x1090000010916, + 0x109200001093A, + 0x10980000109B8, + 0x109BE000109C0, + 0x10A0000010A04, + 0x10A0500010A07, + 0x10A0C00010A14, + 0x10A1500010A18, + 0x10A1900010A36, + 0x10A3800010A3B, + 0x10A3F00010A40, + 0x10A6000010A7D, + 0x10A8000010A9D, + 0x10AC000010AC8, + 0x10AC900010AE7, + 0x10B0000010B36, + 0x10B4000010B56, + 0x10B6000010B73, + 0x10B8000010B92, + 0x10C0000010C49, + 0x10CC000010CF3, + 0x10D0000010D28, + 0x10D3000010D3A, + 0x10E8000010EAA, + 0x10EAB00010EAD, + 0x10EB000010EB2, + 0x10EFD00010F1D, + 0x10F2700010F28, + 0x10F3000010F51, + 0x10F7000010F86, + 0x10FB000010FC5, + 0x10FE000010FF7, + 0x1100000011047, + 0x1106600011076, + 0x1107F000110BB, + 0x110C2000110C3, + 0x110D0000110E9, + 0x110F0000110FA, + 0x1110000011135, + 0x1113600011140, + 0x1114400011148, + 0x1115000011174, + 0x1117600011177, + 0x11180000111C5, + 0x111C9000111CD, + 0x111CE000111DB, + 0x111DC000111DD, + 0x1120000011212, + 0x1121300011238, + 0x1123E00011242, + 0x1128000011287, + 0x1128800011289, + 0x1128A0001128E, + 0x1128F0001129E, + 0x1129F000112A9, + 0x112B0000112EB, + 0x112F0000112FA, + 0x1130000011304, + 0x113050001130D, + 0x1130F00011311, + 0x1131300011329, + 0x1132A00011331, + 0x1133200011334, + 0x113350001133A, + 0x1133B00011345, + 0x1134700011349, + 0x1134B0001134E, + 0x1135000011351, + 0x1135700011358, + 0x1135D00011364, + 0x113660001136D, + 0x1137000011375, + 0x114000001144B, + 0x114500001145A, + 0x1145E00011462, + 0x11480000114C6, + 0x114C7000114C8, + 0x114D0000114DA, + 0x11580000115B6, + 0x115B8000115C1, + 0x115D8000115DE, + 0x1160000011641, + 0x1164400011645, + 0x116500001165A, + 0x11680000116B9, + 0x116C0000116CA, + 0x117000001171B, + 0x1171D0001172C, + 0x117300001173A, + 0x1174000011747, + 0x118000001183B, + 0x118C0000118EA, + 0x118FF00011907, + 0x119090001190A, + 0x1190C00011914, + 0x1191500011917, + 0x1191800011936, + 0x1193700011939, + 0x1193B00011944, + 0x119500001195A, + 0x119A0000119A8, + 0x119AA000119D8, + 0x119DA000119E2, + 0x119E3000119E5, + 0x11A0000011A3F, + 0x11A4700011A48, + 0x11A5000011A9A, + 0x11A9D00011A9E, + 0x11AB000011AF9, + 0x11C0000011C09, + 0x11C0A00011C37, + 0x11C3800011C41, + 0x11C5000011C5A, + 0x11C7200011C90, + 0x11C9200011CA8, + 0x11CA900011CB7, + 0x11D0000011D07, + 0x11D0800011D0A, + 0x11D0B00011D37, + 0x11D3A00011D3B, + 0x11D3C00011D3E, + 0x11D3F00011D48, + 0x11D5000011D5A, + 0x11D6000011D66, + 0x11D6700011D69, + 0x11D6A00011D8F, + 0x11D9000011D92, + 0x11D9300011D99, + 0x11DA000011DAA, + 0x11EE000011EF7, + 0x11F0000011F11, + 0x11F1200011F3B, + 0x11F3E00011F43, + 0x11F5000011F5A, + 0x11FB000011FB1, + 0x120000001239A, + 0x1248000012544, + 0x12F9000012FF1, + 0x1300000013430, + 0x1344000013456, + 0x1440000014647, + 0x1680000016A39, + 0x16A4000016A5F, + 0x16A6000016A6A, + 0x16A7000016ABF, + 0x16AC000016ACA, + 0x16AD000016AEE, + 0x16AF000016AF5, + 0x16B0000016B37, + 0x16B4000016B44, + 0x16B5000016B5A, + 0x16B6300016B78, + 0x16B7D00016B90, + 0x16E6000016E80, + 0x16F0000016F4B, + 0x16F4F00016F88, + 0x16F8F00016FA0, + 0x16FE000016FE2, + 0x16FE300016FE5, + 0x16FF000016FF2, + 0x17000000187F8, + 0x1880000018CD6, + 0x18D0000018D09, + 0x1AFF00001AFF4, + 0x1AFF50001AFFC, + 0x1AFFD0001AFFF, + 0x1B0000001B123, + 0x1B1320001B133, + 0x1B1500001B153, + 0x1B1550001B156, + 0x1B1640001B168, + 0x1B1700001B2FC, + 0x1BC000001BC6B, + 0x1BC700001BC7D, + 0x1BC800001BC89, + 0x1BC900001BC9A, + 0x1BC9D0001BC9F, + 0x1CF000001CF2E, + 0x1CF300001CF47, + 0x1DA000001DA37, + 0x1DA3B0001DA6D, + 0x1DA750001DA76, + 0x1DA840001DA85, + 0x1DA9B0001DAA0, + 0x1DAA10001DAB0, + 0x1DF000001DF1F, + 0x1DF250001DF2B, + 0x1E0000001E007, + 0x1E0080001E019, + 0x1E01B0001E022, + 0x1E0230001E025, + 0x1E0260001E02B, + 0x1E08F0001E090, + 0x1E1000001E12D, + 0x1E1300001E13E, + 0x1E1400001E14A, + 0x1E14E0001E14F, + 0x1E2900001E2AF, + 0x1E2C00001E2FA, + 0x1E4D00001E4FA, + 0x1E7E00001E7E7, + 0x1E7E80001E7EC, + 0x1E7ED0001E7EF, + 0x1E7F00001E7FF, + 0x1E8000001E8C5, + 0x1E8D00001E8D7, + 0x1E9220001E94C, + 0x1E9500001E95A, + 0x200000002A6E0, + 0x2A7000002B73A, + 0x2B7400002B81E, + 0x2B8200002CEA2, + 0x2CEB00002EBE1, + 0x2EBF00002EE5E, + 0x300000003134B, + 0x31350000323B0, + ), + "CONTEXTJ": (0x200C0000200E,), + "CONTEXTO": ( + 0xB7000000B8, + 0x37500000376, + 0x5F3000005F5, + 0x6600000066A, + 0x6F0000006FA, + 0x30FB000030FC, + ), +} diff --git a/python_embeded/Lib/site-packages/idna/intranges.py b/python_embeded/Lib/site-packages/idna/intranges.py new file mode 100644 index 0000000000000000000000000000000000000000..7bfaa8d80d7dc471d572db0f949460901126e8bd --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/intranges.py @@ -0,0 +1,57 @@ +""" +Given a list of integers, made up of (hopefully) a small number of long runs +of consecutive integers, compute a representation of the form +((start1, end1), (start2, end2) ...). Then answer the question "was x present +in the original list?" in time O(log(# runs)). +""" + +import bisect +from typing import List, Tuple + + +def intranges_from_list(list_: List[int]) -> Tuple[int, ...]: + """Represent a list of integers as a sequence of ranges: + ((start_0, end_0), (start_1, end_1), ...), such that the original + integers are exactly those x such that start_i <= x < end_i for some i. + + Ranges are encoded as single integers (start << 32 | end), not as tuples. + """ + + sorted_list = sorted(list_) + ranges = [] + last_write = -1 + for i in range(len(sorted_list)): + if i + 1 < len(sorted_list): + if sorted_list[i] == sorted_list[i + 1] - 1: + continue + current_range = sorted_list[last_write + 1 : i + 1] + ranges.append(_encode_range(current_range[0], current_range[-1] + 1)) + last_write = i + + return tuple(ranges) + + +def _encode_range(start: int, end: int) -> int: + return (start << 32) | end + + +def _decode_range(r: int) -> Tuple[int, int]: + return (r >> 32), (r & ((1 << 32) - 1)) + + +def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool: + """Determine if `int_` falls into one of the ranges in `ranges`.""" + tuple_ = _encode_range(int_, 0) + pos = bisect.bisect_left(ranges, tuple_) + # we could be immediately ahead of a tuple (start, end) + # with start < int_ <= end + if pos > 0: + left, right = _decode_range(ranges[pos - 1]) + if left <= int_ < right: + return True + # or we could be immediately behind a tuple (int_, end) + if pos < len(ranges): + left, _ = _decode_range(ranges[pos]) + if left == int_: + return True + return False diff --git a/python_embeded/Lib/site-packages/idna/package_data.py b/python_embeded/Lib/site-packages/idna/package_data.py new file mode 100644 index 0000000000000000000000000000000000000000..514ff7e2e68b65f309d30a0b06e6b290d2c353a8 --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/package_data.py @@ -0,0 +1 @@ +__version__ = "3.10" diff --git a/python_embeded/Lib/site-packages/idna/py.typed b/python_embeded/Lib/site-packages/idna/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/idna/uts46data.py b/python_embeded/Lib/site-packages/idna/uts46data.py new file mode 100644 index 0000000000000000000000000000000000000000..eb894327410debecb64ddf40eddc3131cf8344de --- /dev/null +++ b/python_embeded/Lib/site-packages/idna/uts46data.py @@ -0,0 +1,8681 @@ +# This file is automatically generated by tools/idna-data +# vim: set fileencoding=utf-8 : + +from typing import List, Tuple, Union + +"""IDNA Mapping Table from UTS46.""" + + +__version__ = "15.1.0" + + +def _seg_0() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x0, "3"), + (0x1, "3"), + (0x2, "3"), + (0x3, "3"), + (0x4, "3"), + (0x5, "3"), + (0x6, "3"), + (0x7, "3"), + (0x8, "3"), + (0x9, "3"), + (0xA, "3"), + (0xB, "3"), + (0xC, "3"), + (0xD, "3"), + (0xE, "3"), + (0xF, "3"), + (0x10, "3"), + (0x11, "3"), + (0x12, "3"), + (0x13, "3"), + (0x14, "3"), + (0x15, "3"), + (0x16, "3"), + (0x17, "3"), + (0x18, "3"), + (0x19, "3"), + (0x1A, "3"), + (0x1B, "3"), + (0x1C, "3"), + (0x1D, "3"), + (0x1E, "3"), + (0x1F, "3"), + (0x20, "3"), + (0x21, "3"), + (0x22, "3"), + (0x23, "3"), + (0x24, "3"), + (0x25, "3"), + (0x26, "3"), + (0x27, "3"), + (0x28, "3"), + (0x29, "3"), + (0x2A, "3"), + (0x2B, "3"), + (0x2C, "3"), + (0x2D, "V"), + (0x2E, "V"), + (0x2F, "3"), + (0x30, "V"), + (0x31, "V"), + (0x32, "V"), + (0x33, "V"), + (0x34, "V"), + (0x35, "V"), + (0x36, "V"), + (0x37, "V"), + (0x38, "V"), + (0x39, "V"), + (0x3A, "3"), + (0x3B, "3"), + (0x3C, "3"), + (0x3D, "3"), + (0x3E, "3"), + (0x3F, "3"), + (0x40, "3"), + (0x41, "M", "a"), + (0x42, "M", "b"), + (0x43, "M", "c"), + (0x44, "M", "d"), + (0x45, "M", "e"), + (0x46, "M", "f"), + (0x47, "M", "g"), + (0x48, "M", "h"), + (0x49, "M", "i"), + (0x4A, "M", "j"), + (0x4B, "M", "k"), + (0x4C, "M", "l"), + (0x4D, "M", "m"), + (0x4E, "M", "n"), + (0x4F, "M", "o"), + (0x50, "M", "p"), + (0x51, "M", "q"), + (0x52, "M", "r"), + (0x53, "M", "s"), + (0x54, "M", "t"), + (0x55, "M", "u"), + (0x56, "M", "v"), + (0x57, "M", "w"), + (0x58, "M", "x"), + (0x59, "M", "y"), + (0x5A, "M", "z"), + (0x5B, "3"), + (0x5C, "3"), + (0x5D, "3"), + (0x5E, "3"), + (0x5F, "3"), + (0x60, "3"), + (0x61, "V"), + (0x62, "V"), + (0x63, "V"), + ] + + +def _seg_1() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x64, "V"), + (0x65, "V"), + (0x66, "V"), + (0x67, "V"), + (0x68, "V"), + (0x69, "V"), + (0x6A, "V"), + (0x6B, "V"), + (0x6C, "V"), + (0x6D, "V"), + (0x6E, "V"), + (0x6F, "V"), + (0x70, "V"), + (0x71, "V"), + (0x72, "V"), + (0x73, "V"), + (0x74, "V"), + (0x75, "V"), + (0x76, "V"), + (0x77, "V"), + (0x78, "V"), + (0x79, "V"), + (0x7A, "V"), + (0x7B, "3"), + (0x7C, "3"), + (0x7D, "3"), + (0x7E, "3"), + (0x7F, "3"), + (0x80, "X"), + (0x81, "X"), + (0x82, "X"), + (0x83, "X"), + (0x84, "X"), + (0x85, "X"), + (0x86, "X"), + (0x87, "X"), + (0x88, "X"), + (0x89, "X"), + (0x8A, "X"), + (0x8B, "X"), + (0x8C, "X"), + (0x8D, "X"), + (0x8E, "X"), + (0x8F, "X"), + (0x90, "X"), + (0x91, "X"), + (0x92, "X"), + (0x93, "X"), + (0x94, "X"), + (0x95, "X"), + (0x96, "X"), + (0x97, "X"), + (0x98, "X"), + (0x99, "X"), + (0x9A, "X"), + (0x9B, "X"), + (0x9C, "X"), + (0x9D, "X"), + (0x9E, "X"), + (0x9F, "X"), + (0xA0, "3", " "), + (0xA1, "V"), + (0xA2, "V"), + (0xA3, "V"), + (0xA4, "V"), + (0xA5, "V"), + (0xA6, "V"), + (0xA7, "V"), + (0xA8, "3", " ̈"), + (0xA9, "V"), + (0xAA, "M", "a"), + (0xAB, "V"), + (0xAC, "V"), + (0xAD, "I"), + (0xAE, "V"), + (0xAF, "3", " ̄"), + (0xB0, "V"), + (0xB1, "V"), + (0xB2, "M", "2"), + (0xB3, "M", "3"), + (0xB4, "3", " ́"), + (0xB5, "M", "μ"), + (0xB6, "V"), + (0xB7, "V"), + (0xB8, "3", " ̧"), + (0xB9, "M", "1"), + (0xBA, "M", "o"), + (0xBB, "V"), + (0xBC, "M", "1⁄4"), + (0xBD, "M", "1⁄2"), + (0xBE, "M", "3⁄4"), + (0xBF, "V"), + (0xC0, "M", "à"), + (0xC1, "M", "á"), + (0xC2, "M", "â"), + (0xC3, "M", "ã"), + (0xC4, "M", "ä"), + (0xC5, "M", "å"), + (0xC6, "M", "æ"), + (0xC7, "M", "ç"), + ] + + +def _seg_2() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xC8, "M", "è"), + (0xC9, "M", "é"), + (0xCA, "M", "ê"), + (0xCB, "M", "ë"), + (0xCC, "M", "ì"), + (0xCD, "M", "í"), + (0xCE, "M", "î"), + (0xCF, "M", "ï"), + (0xD0, "M", "ð"), + (0xD1, "M", "ñ"), + (0xD2, "M", "ò"), + (0xD3, "M", "ó"), + (0xD4, "M", "ô"), + (0xD5, "M", "õ"), + (0xD6, "M", "ö"), + (0xD7, "V"), + (0xD8, "M", "ø"), + (0xD9, "M", "ù"), + (0xDA, "M", "ú"), + (0xDB, "M", "û"), + (0xDC, "M", "ü"), + (0xDD, "M", "ý"), + (0xDE, "M", "þ"), + (0xDF, "D", "ss"), + (0xE0, "V"), + (0xE1, "V"), + (0xE2, "V"), + (0xE3, "V"), + (0xE4, "V"), + (0xE5, "V"), + (0xE6, "V"), + (0xE7, "V"), + (0xE8, "V"), + (0xE9, "V"), + (0xEA, "V"), + (0xEB, "V"), + (0xEC, "V"), + (0xED, "V"), + (0xEE, "V"), + (0xEF, "V"), + (0xF0, "V"), + (0xF1, "V"), + (0xF2, "V"), + (0xF3, "V"), + (0xF4, "V"), + (0xF5, "V"), + (0xF6, "V"), + (0xF7, "V"), + (0xF8, "V"), + (0xF9, "V"), + (0xFA, "V"), + (0xFB, "V"), + (0xFC, "V"), + (0xFD, "V"), + (0xFE, "V"), + (0xFF, "V"), + (0x100, "M", "ā"), + (0x101, "V"), + (0x102, "M", "ă"), + (0x103, "V"), + (0x104, "M", "ą"), + (0x105, "V"), + (0x106, "M", "ć"), + (0x107, "V"), + (0x108, "M", "ĉ"), + (0x109, "V"), + (0x10A, "M", "ċ"), + (0x10B, "V"), + (0x10C, "M", "č"), + (0x10D, "V"), + (0x10E, "M", "ď"), + (0x10F, "V"), + (0x110, "M", "đ"), + (0x111, "V"), + (0x112, "M", "ē"), + (0x113, "V"), + (0x114, "M", "ĕ"), + (0x115, "V"), + (0x116, "M", "ė"), + (0x117, "V"), + (0x118, "M", "ę"), + (0x119, "V"), + (0x11A, "M", "ě"), + (0x11B, "V"), + (0x11C, "M", "ĝ"), + (0x11D, "V"), + (0x11E, "M", "ğ"), + (0x11F, "V"), + (0x120, "M", "ġ"), + (0x121, "V"), + (0x122, "M", "ģ"), + (0x123, "V"), + (0x124, "M", "ĥ"), + (0x125, "V"), + (0x126, "M", "ħ"), + (0x127, "V"), + (0x128, "M", "ĩ"), + (0x129, "V"), + (0x12A, "M", "ī"), + (0x12B, "V"), + ] + + +def _seg_3() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x12C, "M", "ĭ"), + (0x12D, "V"), + (0x12E, "M", "į"), + (0x12F, "V"), + (0x130, "M", "i̇"), + (0x131, "V"), + (0x132, "M", "ij"), + (0x134, "M", "ĵ"), + (0x135, "V"), + (0x136, "M", "ķ"), + (0x137, "V"), + (0x139, "M", "ĺ"), + (0x13A, "V"), + (0x13B, "M", "ļ"), + (0x13C, "V"), + (0x13D, "M", "ľ"), + (0x13E, "V"), + (0x13F, "M", "l·"), + (0x141, "M", "ł"), + (0x142, "V"), + (0x143, "M", "ń"), + (0x144, "V"), + (0x145, "M", "ņ"), + (0x146, "V"), + (0x147, "M", "ň"), + (0x148, "V"), + (0x149, "M", "ʼn"), + (0x14A, "M", "ŋ"), + (0x14B, "V"), + (0x14C, "M", "ō"), + (0x14D, "V"), + (0x14E, "M", "ŏ"), + (0x14F, "V"), + (0x150, "M", "ő"), + (0x151, "V"), + (0x152, "M", "œ"), + (0x153, "V"), + (0x154, "M", "ŕ"), + (0x155, "V"), + (0x156, "M", "ŗ"), + (0x157, "V"), + (0x158, "M", "ř"), + (0x159, "V"), + (0x15A, "M", "ś"), + (0x15B, "V"), + (0x15C, "M", "ŝ"), + (0x15D, "V"), + (0x15E, "M", "ş"), + (0x15F, "V"), + (0x160, "M", "š"), + (0x161, "V"), + (0x162, "M", "ţ"), + (0x163, "V"), + (0x164, "M", "ť"), + (0x165, "V"), + (0x166, "M", "ŧ"), + (0x167, "V"), + (0x168, "M", "ũ"), + (0x169, "V"), + (0x16A, "M", "ū"), + (0x16B, "V"), + (0x16C, "M", "ŭ"), + (0x16D, "V"), + (0x16E, "M", "ů"), + (0x16F, "V"), + (0x170, "M", "ű"), + (0x171, "V"), + (0x172, "M", "ų"), + (0x173, "V"), + (0x174, "M", "ŵ"), + (0x175, "V"), + (0x176, "M", "ŷ"), + (0x177, "V"), + (0x178, "M", "ÿ"), + (0x179, "M", "ź"), + (0x17A, "V"), + (0x17B, "M", "ż"), + (0x17C, "V"), + (0x17D, "M", "ž"), + (0x17E, "V"), + (0x17F, "M", "s"), + (0x180, "V"), + (0x181, "M", "ɓ"), + (0x182, "M", "ƃ"), + (0x183, "V"), + (0x184, "M", "ƅ"), + (0x185, "V"), + (0x186, "M", "ɔ"), + (0x187, "M", "ƈ"), + (0x188, "V"), + (0x189, "M", "ɖ"), + (0x18A, "M", "ɗ"), + (0x18B, "M", "ƌ"), + (0x18C, "V"), + (0x18E, "M", "ǝ"), + (0x18F, "M", "ə"), + (0x190, "M", "ɛ"), + (0x191, "M", "ƒ"), + (0x192, "V"), + (0x193, "M", "ɠ"), + ] + + +def _seg_4() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x194, "M", "ɣ"), + (0x195, "V"), + (0x196, "M", "ɩ"), + (0x197, "M", "ɨ"), + (0x198, "M", "ƙ"), + (0x199, "V"), + (0x19C, "M", "ɯ"), + (0x19D, "M", "ɲ"), + (0x19E, "V"), + (0x19F, "M", "ɵ"), + (0x1A0, "M", "ơ"), + (0x1A1, "V"), + (0x1A2, "M", "ƣ"), + (0x1A3, "V"), + (0x1A4, "M", "ƥ"), + (0x1A5, "V"), + (0x1A6, "M", "ʀ"), + (0x1A7, "M", "ƨ"), + (0x1A8, "V"), + (0x1A9, "M", "ʃ"), + (0x1AA, "V"), + (0x1AC, "M", "ƭ"), + (0x1AD, "V"), + (0x1AE, "M", "ʈ"), + (0x1AF, "M", "ư"), + (0x1B0, "V"), + (0x1B1, "M", "ʊ"), + (0x1B2, "M", "ʋ"), + (0x1B3, "M", "ƴ"), + (0x1B4, "V"), + (0x1B5, "M", "ƶ"), + (0x1B6, "V"), + (0x1B7, "M", "ʒ"), + (0x1B8, "M", "ƹ"), + (0x1B9, "V"), + (0x1BC, "M", "ƽ"), + (0x1BD, "V"), + (0x1C4, "M", "dž"), + (0x1C7, "M", "lj"), + (0x1CA, "M", "nj"), + (0x1CD, "M", "ǎ"), + (0x1CE, "V"), + (0x1CF, "M", "ǐ"), + (0x1D0, "V"), + (0x1D1, "M", "ǒ"), + (0x1D2, "V"), + (0x1D3, "M", "ǔ"), + (0x1D4, "V"), + (0x1D5, "M", "ǖ"), + (0x1D6, "V"), + (0x1D7, "M", "ǘ"), + (0x1D8, "V"), + (0x1D9, "M", "ǚ"), + (0x1DA, "V"), + (0x1DB, "M", "ǜ"), + (0x1DC, "V"), + (0x1DE, "M", "ǟ"), + (0x1DF, "V"), + (0x1E0, "M", "ǡ"), + (0x1E1, "V"), + (0x1E2, "M", "ǣ"), + (0x1E3, "V"), + (0x1E4, "M", "ǥ"), + (0x1E5, "V"), + (0x1E6, "M", "ǧ"), + (0x1E7, "V"), + (0x1E8, "M", "ǩ"), + (0x1E9, "V"), + (0x1EA, "M", "ǫ"), + (0x1EB, "V"), + (0x1EC, "M", "ǭ"), + (0x1ED, "V"), + (0x1EE, "M", "ǯ"), + (0x1EF, "V"), + (0x1F1, "M", "dz"), + (0x1F4, "M", "ǵ"), + (0x1F5, "V"), + (0x1F6, "M", "ƕ"), + (0x1F7, "M", "ƿ"), + (0x1F8, "M", "ǹ"), + (0x1F9, "V"), + (0x1FA, "M", "ǻ"), + (0x1FB, "V"), + (0x1FC, "M", "ǽ"), + (0x1FD, "V"), + (0x1FE, "M", "ǿ"), + (0x1FF, "V"), + (0x200, "M", "ȁ"), + (0x201, "V"), + (0x202, "M", "ȃ"), + (0x203, "V"), + (0x204, "M", "ȅ"), + (0x205, "V"), + (0x206, "M", "ȇ"), + (0x207, "V"), + (0x208, "M", "ȉ"), + (0x209, "V"), + (0x20A, "M", "ȋ"), + (0x20B, "V"), + (0x20C, "M", "ȍ"), + ] + + +def _seg_5() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x20D, "V"), + (0x20E, "M", "ȏ"), + (0x20F, "V"), + (0x210, "M", "ȑ"), + (0x211, "V"), + (0x212, "M", "ȓ"), + (0x213, "V"), + (0x214, "M", "ȕ"), + (0x215, "V"), + (0x216, "M", "ȗ"), + (0x217, "V"), + (0x218, "M", "ș"), + (0x219, "V"), + (0x21A, "M", "ț"), + (0x21B, "V"), + (0x21C, "M", "ȝ"), + (0x21D, "V"), + (0x21E, "M", "ȟ"), + (0x21F, "V"), + (0x220, "M", "ƞ"), + (0x221, "V"), + (0x222, "M", "ȣ"), + (0x223, "V"), + (0x224, "M", "ȥ"), + (0x225, "V"), + (0x226, "M", "ȧ"), + (0x227, "V"), + (0x228, "M", "ȩ"), + (0x229, "V"), + (0x22A, "M", "ȫ"), + (0x22B, "V"), + (0x22C, "M", "ȭ"), + (0x22D, "V"), + (0x22E, "M", "ȯ"), + (0x22F, "V"), + (0x230, "M", "ȱ"), + (0x231, "V"), + (0x232, "M", "ȳ"), + (0x233, "V"), + (0x23A, "M", "ⱥ"), + (0x23B, "M", "ȼ"), + (0x23C, "V"), + (0x23D, "M", "ƚ"), + (0x23E, "M", "ⱦ"), + (0x23F, "V"), + (0x241, "M", "ɂ"), + (0x242, "V"), + (0x243, "M", "ƀ"), + (0x244, "M", "ʉ"), + (0x245, "M", "ʌ"), + (0x246, "M", "ɇ"), + (0x247, "V"), + (0x248, "M", "ɉ"), + (0x249, "V"), + (0x24A, "M", "ɋ"), + (0x24B, "V"), + (0x24C, "M", "ɍ"), + (0x24D, "V"), + (0x24E, "M", "ɏ"), + (0x24F, "V"), + (0x2B0, "M", "h"), + (0x2B1, "M", "ɦ"), + (0x2B2, "M", "j"), + (0x2B3, "M", "r"), + (0x2B4, "M", "ɹ"), + (0x2B5, "M", "ɻ"), + (0x2B6, "M", "ʁ"), + (0x2B7, "M", "w"), + (0x2B8, "M", "y"), + (0x2B9, "V"), + (0x2D8, "3", " ̆"), + (0x2D9, "3", " ̇"), + (0x2DA, "3", " ̊"), + (0x2DB, "3", " ̨"), + (0x2DC, "3", " ̃"), + (0x2DD, "3", " ̋"), + (0x2DE, "V"), + (0x2E0, "M", "ɣ"), + (0x2E1, "M", "l"), + (0x2E2, "M", "s"), + (0x2E3, "M", "x"), + (0x2E4, "M", "ʕ"), + (0x2E5, "V"), + (0x340, "M", "̀"), + (0x341, "M", "́"), + (0x342, "V"), + (0x343, "M", "̓"), + (0x344, "M", "̈́"), + (0x345, "M", "ι"), + (0x346, "V"), + (0x34F, "I"), + (0x350, "V"), + (0x370, "M", "ͱ"), + (0x371, "V"), + (0x372, "M", "ͳ"), + (0x373, "V"), + (0x374, "M", "ʹ"), + (0x375, "V"), + (0x376, "M", "ͷ"), + (0x377, "V"), + ] + + +def _seg_6() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x378, "X"), + (0x37A, "3", " ι"), + (0x37B, "V"), + (0x37E, "3", ";"), + (0x37F, "M", "ϳ"), + (0x380, "X"), + (0x384, "3", " ́"), + (0x385, "3", " ̈́"), + (0x386, "M", "ά"), + (0x387, "M", "·"), + (0x388, "M", "έ"), + (0x389, "M", "ή"), + (0x38A, "M", "ί"), + (0x38B, "X"), + (0x38C, "M", "ό"), + (0x38D, "X"), + (0x38E, "M", "ύ"), + (0x38F, "M", "ώ"), + (0x390, "V"), + (0x391, "M", "α"), + (0x392, "M", "β"), + (0x393, "M", "γ"), + (0x394, "M", "δ"), + (0x395, "M", "ε"), + (0x396, "M", "ζ"), + (0x397, "M", "η"), + (0x398, "M", "θ"), + (0x399, "M", "ι"), + (0x39A, "M", "κ"), + (0x39B, "M", "λ"), + (0x39C, "M", "μ"), + (0x39D, "M", "ν"), + (0x39E, "M", "ξ"), + (0x39F, "M", "ο"), + (0x3A0, "M", "π"), + (0x3A1, "M", "ρ"), + (0x3A2, "X"), + (0x3A3, "M", "σ"), + (0x3A4, "M", "τ"), + (0x3A5, "M", "υ"), + (0x3A6, "M", "φ"), + (0x3A7, "M", "χ"), + (0x3A8, "M", "ψ"), + (0x3A9, "M", "ω"), + (0x3AA, "M", "ϊ"), + (0x3AB, "M", "ϋ"), + (0x3AC, "V"), + (0x3C2, "D", "σ"), + (0x3C3, "V"), + (0x3CF, "M", "ϗ"), + (0x3D0, "M", "β"), + (0x3D1, "M", "θ"), + (0x3D2, "M", "υ"), + (0x3D3, "M", "ύ"), + (0x3D4, "M", "ϋ"), + (0x3D5, "M", "φ"), + (0x3D6, "M", "π"), + (0x3D7, "V"), + (0x3D8, "M", "ϙ"), + (0x3D9, "V"), + (0x3DA, "M", "ϛ"), + (0x3DB, "V"), + (0x3DC, "M", "ϝ"), + (0x3DD, "V"), + (0x3DE, "M", "ϟ"), + (0x3DF, "V"), + (0x3E0, "M", "ϡ"), + (0x3E1, "V"), + (0x3E2, "M", "ϣ"), + (0x3E3, "V"), + (0x3E4, "M", "ϥ"), + (0x3E5, "V"), + (0x3E6, "M", "ϧ"), + (0x3E7, "V"), + (0x3E8, "M", "ϩ"), + (0x3E9, "V"), + (0x3EA, "M", "ϫ"), + (0x3EB, "V"), + (0x3EC, "M", "ϭ"), + (0x3ED, "V"), + (0x3EE, "M", "ϯ"), + (0x3EF, "V"), + (0x3F0, "M", "κ"), + (0x3F1, "M", "ρ"), + (0x3F2, "M", "σ"), + (0x3F3, "V"), + (0x3F4, "M", "θ"), + (0x3F5, "M", "ε"), + (0x3F6, "V"), + (0x3F7, "M", "ϸ"), + (0x3F8, "V"), + (0x3F9, "M", "σ"), + (0x3FA, "M", "ϻ"), + (0x3FB, "V"), + (0x3FD, "M", "ͻ"), + (0x3FE, "M", "ͼ"), + (0x3FF, "M", "ͽ"), + (0x400, "M", "ѐ"), + (0x401, "M", "ё"), + (0x402, "M", "ђ"), + ] + + +def _seg_7() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x403, "M", "ѓ"), + (0x404, "M", "є"), + (0x405, "M", "ѕ"), + (0x406, "M", "і"), + (0x407, "M", "ї"), + (0x408, "M", "ј"), + (0x409, "M", "љ"), + (0x40A, "M", "њ"), + (0x40B, "M", "ћ"), + (0x40C, "M", "ќ"), + (0x40D, "M", "ѝ"), + (0x40E, "M", "ў"), + (0x40F, "M", "џ"), + (0x410, "M", "а"), + (0x411, "M", "б"), + (0x412, "M", "в"), + (0x413, "M", "г"), + (0x414, "M", "д"), + (0x415, "M", "е"), + (0x416, "M", "ж"), + (0x417, "M", "з"), + (0x418, "M", "и"), + (0x419, "M", "й"), + (0x41A, "M", "к"), + (0x41B, "M", "л"), + (0x41C, "M", "м"), + (0x41D, "M", "н"), + (0x41E, "M", "о"), + (0x41F, "M", "п"), + (0x420, "M", "р"), + (0x421, "M", "с"), + (0x422, "M", "т"), + (0x423, "M", "у"), + (0x424, "M", "ф"), + (0x425, "M", "х"), + (0x426, "M", "ц"), + (0x427, "M", "ч"), + (0x428, "M", "ш"), + (0x429, "M", "щ"), + (0x42A, "M", "ъ"), + (0x42B, "M", "ы"), + (0x42C, "M", "ь"), + (0x42D, "M", "э"), + (0x42E, "M", "ю"), + (0x42F, "M", "я"), + (0x430, "V"), + (0x460, "M", "ѡ"), + (0x461, "V"), + (0x462, "M", "ѣ"), + (0x463, "V"), + (0x464, "M", "ѥ"), + (0x465, "V"), + (0x466, "M", "ѧ"), + (0x467, "V"), + (0x468, "M", "ѩ"), + (0x469, "V"), + (0x46A, "M", "ѫ"), + (0x46B, "V"), + (0x46C, "M", "ѭ"), + (0x46D, "V"), + (0x46E, "M", "ѯ"), + (0x46F, "V"), + (0x470, "M", "ѱ"), + (0x471, "V"), + (0x472, "M", "ѳ"), + (0x473, "V"), + (0x474, "M", "ѵ"), + (0x475, "V"), + (0x476, "M", "ѷ"), + (0x477, "V"), + (0x478, "M", "ѹ"), + (0x479, "V"), + (0x47A, "M", "ѻ"), + (0x47B, "V"), + (0x47C, "M", "ѽ"), + (0x47D, "V"), + (0x47E, "M", "ѿ"), + (0x47F, "V"), + (0x480, "M", "ҁ"), + (0x481, "V"), + (0x48A, "M", "ҋ"), + (0x48B, "V"), + (0x48C, "M", "ҍ"), + (0x48D, "V"), + (0x48E, "M", "ҏ"), + (0x48F, "V"), + (0x490, "M", "ґ"), + (0x491, "V"), + (0x492, "M", "ғ"), + (0x493, "V"), + (0x494, "M", "ҕ"), + (0x495, "V"), + (0x496, "M", "җ"), + (0x497, "V"), + (0x498, "M", "ҙ"), + (0x499, "V"), + (0x49A, "M", "қ"), + (0x49B, "V"), + (0x49C, "M", "ҝ"), + (0x49D, "V"), + ] + + +def _seg_8() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x49E, "M", "ҟ"), + (0x49F, "V"), + (0x4A0, "M", "ҡ"), + (0x4A1, "V"), + (0x4A2, "M", "ң"), + (0x4A3, "V"), + (0x4A4, "M", "ҥ"), + (0x4A5, "V"), + (0x4A6, "M", "ҧ"), + (0x4A7, "V"), + (0x4A8, "M", "ҩ"), + (0x4A9, "V"), + (0x4AA, "M", "ҫ"), + (0x4AB, "V"), + (0x4AC, "M", "ҭ"), + (0x4AD, "V"), + (0x4AE, "M", "ү"), + (0x4AF, "V"), + (0x4B0, "M", "ұ"), + (0x4B1, "V"), + (0x4B2, "M", "ҳ"), + (0x4B3, "V"), + (0x4B4, "M", "ҵ"), + (0x4B5, "V"), + (0x4B6, "M", "ҷ"), + (0x4B7, "V"), + (0x4B8, "M", "ҹ"), + (0x4B9, "V"), + (0x4BA, "M", "һ"), + (0x4BB, "V"), + (0x4BC, "M", "ҽ"), + (0x4BD, "V"), + (0x4BE, "M", "ҿ"), + (0x4BF, "V"), + (0x4C0, "X"), + (0x4C1, "M", "ӂ"), + (0x4C2, "V"), + (0x4C3, "M", "ӄ"), + (0x4C4, "V"), + (0x4C5, "M", "ӆ"), + (0x4C6, "V"), + (0x4C7, "M", "ӈ"), + (0x4C8, "V"), + (0x4C9, "M", "ӊ"), + (0x4CA, "V"), + (0x4CB, "M", "ӌ"), + (0x4CC, "V"), + (0x4CD, "M", "ӎ"), + (0x4CE, "V"), + (0x4D0, "M", "ӑ"), + (0x4D1, "V"), + (0x4D2, "M", "ӓ"), + (0x4D3, "V"), + (0x4D4, "M", "ӕ"), + (0x4D5, "V"), + (0x4D6, "M", "ӗ"), + (0x4D7, "V"), + (0x4D8, "M", "ә"), + (0x4D9, "V"), + (0x4DA, "M", "ӛ"), + (0x4DB, "V"), + (0x4DC, "M", "ӝ"), + (0x4DD, "V"), + (0x4DE, "M", "ӟ"), + (0x4DF, "V"), + (0x4E0, "M", "ӡ"), + (0x4E1, "V"), + (0x4E2, "M", "ӣ"), + (0x4E3, "V"), + (0x4E4, "M", "ӥ"), + (0x4E5, "V"), + (0x4E6, "M", "ӧ"), + (0x4E7, "V"), + (0x4E8, "M", "ө"), + (0x4E9, "V"), + (0x4EA, "M", "ӫ"), + (0x4EB, "V"), + (0x4EC, "M", "ӭ"), + (0x4ED, "V"), + (0x4EE, "M", "ӯ"), + (0x4EF, "V"), + (0x4F0, "M", "ӱ"), + (0x4F1, "V"), + (0x4F2, "M", "ӳ"), + (0x4F3, "V"), + (0x4F4, "M", "ӵ"), + (0x4F5, "V"), + (0x4F6, "M", "ӷ"), + (0x4F7, "V"), + (0x4F8, "M", "ӹ"), + (0x4F9, "V"), + (0x4FA, "M", "ӻ"), + (0x4FB, "V"), + (0x4FC, "M", "ӽ"), + (0x4FD, "V"), + (0x4FE, "M", "ӿ"), + (0x4FF, "V"), + (0x500, "M", "ԁ"), + (0x501, "V"), + (0x502, "M", "ԃ"), + ] + + +def _seg_9() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x503, "V"), + (0x504, "M", "ԅ"), + (0x505, "V"), + (0x506, "M", "ԇ"), + (0x507, "V"), + (0x508, "M", "ԉ"), + (0x509, "V"), + (0x50A, "M", "ԋ"), + (0x50B, "V"), + (0x50C, "M", "ԍ"), + (0x50D, "V"), + (0x50E, "M", "ԏ"), + (0x50F, "V"), + (0x510, "M", "ԑ"), + (0x511, "V"), + (0x512, "M", "ԓ"), + (0x513, "V"), + (0x514, "M", "ԕ"), + (0x515, "V"), + (0x516, "M", "ԗ"), + (0x517, "V"), + (0x518, "M", "ԙ"), + (0x519, "V"), + (0x51A, "M", "ԛ"), + (0x51B, "V"), + (0x51C, "M", "ԝ"), + (0x51D, "V"), + (0x51E, "M", "ԟ"), + (0x51F, "V"), + (0x520, "M", "ԡ"), + (0x521, "V"), + (0x522, "M", "ԣ"), + (0x523, "V"), + (0x524, "M", "ԥ"), + (0x525, "V"), + (0x526, "M", "ԧ"), + (0x527, "V"), + (0x528, "M", "ԩ"), + (0x529, "V"), + (0x52A, "M", "ԫ"), + (0x52B, "V"), + (0x52C, "M", "ԭ"), + (0x52D, "V"), + (0x52E, "M", "ԯ"), + (0x52F, "V"), + (0x530, "X"), + (0x531, "M", "ա"), + (0x532, "M", "բ"), + (0x533, "M", "գ"), + (0x534, "M", "դ"), + (0x535, "M", "ե"), + (0x536, "M", "զ"), + (0x537, "M", "է"), + (0x538, "M", "ը"), + (0x539, "M", "թ"), + (0x53A, "M", "ժ"), + (0x53B, "M", "ի"), + (0x53C, "M", "լ"), + (0x53D, "M", "խ"), + (0x53E, "M", "ծ"), + (0x53F, "M", "կ"), + (0x540, "M", "հ"), + (0x541, "M", "ձ"), + (0x542, "M", "ղ"), + (0x543, "M", "ճ"), + (0x544, "M", "մ"), + (0x545, "M", "յ"), + (0x546, "M", "ն"), + (0x547, "M", "շ"), + (0x548, "M", "ո"), + (0x549, "M", "չ"), + (0x54A, "M", "պ"), + (0x54B, "M", "ջ"), + (0x54C, "M", "ռ"), + (0x54D, "M", "ս"), + (0x54E, "M", "վ"), + (0x54F, "M", "տ"), + (0x550, "M", "ր"), + (0x551, "M", "ց"), + (0x552, "M", "ւ"), + (0x553, "M", "փ"), + (0x554, "M", "ք"), + (0x555, "M", "օ"), + (0x556, "M", "ֆ"), + (0x557, "X"), + (0x559, "V"), + (0x587, "M", "եւ"), + (0x588, "V"), + (0x58B, "X"), + (0x58D, "V"), + (0x590, "X"), + (0x591, "V"), + (0x5C8, "X"), + (0x5D0, "V"), + (0x5EB, "X"), + (0x5EF, "V"), + (0x5F5, "X"), + (0x606, "V"), + (0x61C, "X"), + (0x61D, "V"), + ] + + +def _seg_10() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x675, "M", "اٴ"), + (0x676, "M", "وٴ"), + (0x677, "M", "ۇٴ"), + (0x678, "M", "يٴ"), + (0x679, "V"), + (0x6DD, "X"), + (0x6DE, "V"), + (0x70E, "X"), + (0x710, "V"), + (0x74B, "X"), + (0x74D, "V"), + (0x7B2, "X"), + (0x7C0, "V"), + (0x7FB, "X"), + (0x7FD, "V"), + (0x82E, "X"), + (0x830, "V"), + (0x83F, "X"), + (0x840, "V"), + (0x85C, "X"), + (0x85E, "V"), + (0x85F, "X"), + (0x860, "V"), + (0x86B, "X"), + (0x870, "V"), + (0x88F, "X"), + (0x898, "V"), + (0x8E2, "X"), + (0x8E3, "V"), + (0x958, "M", "क़"), + (0x959, "M", "ख़"), + (0x95A, "M", "ग़"), + (0x95B, "M", "ज़"), + (0x95C, "M", "ड़"), + (0x95D, "M", "ढ़"), + (0x95E, "M", "फ़"), + (0x95F, "M", "य़"), + (0x960, "V"), + (0x984, "X"), + (0x985, "V"), + (0x98D, "X"), + (0x98F, "V"), + (0x991, "X"), + (0x993, "V"), + (0x9A9, "X"), + (0x9AA, "V"), + (0x9B1, "X"), + (0x9B2, "V"), + (0x9B3, "X"), + (0x9B6, "V"), + (0x9BA, "X"), + (0x9BC, "V"), + (0x9C5, "X"), + (0x9C7, "V"), + (0x9C9, "X"), + (0x9CB, "V"), + (0x9CF, "X"), + (0x9D7, "V"), + (0x9D8, "X"), + (0x9DC, "M", "ড়"), + (0x9DD, "M", "ঢ়"), + (0x9DE, "X"), + (0x9DF, "M", "য়"), + (0x9E0, "V"), + (0x9E4, "X"), + (0x9E6, "V"), + (0x9FF, "X"), + (0xA01, "V"), + (0xA04, "X"), + (0xA05, "V"), + (0xA0B, "X"), + (0xA0F, "V"), + (0xA11, "X"), + (0xA13, "V"), + (0xA29, "X"), + (0xA2A, "V"), + (0xA31, "X"), + (0xA32, "V"), + (0xA33, "M", "ਲ਼"), + (0xA34, "X"), + (0xA35, "V"), + (0xA36, "M", "ਸ਼"), + (0xA37, "X"), + (0xA38, "V"), + (0xA3A, "X"), + (0xA3C, "V"), + (0xA3D, "X"), + (0xA3E, "V"), + (0xA43, "X"), + (0xA47, "V"), + (0xA49, "X"), + (0xA4B, "V"), + (0xA4E, "X"), + (0xA51, "V"), + (0xA52, "X"), + (0xA59, "M", "ਖ਼"), + (0xA5A, "M", "ਗ਼"), + (0xA5B, "M", "ਜ਼"), + (0xA5C, "V"), + (0xA5D, "X"), + ] + + +def _seg_11() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA5E, "M", "ਫ਼"), + (0xA5F, "X"), + (0xA66, "V"), + (0xA77, "X"), + (0xA81, "V"), + (0xA84, "X"), + (0xA85, "V"), + (0xA8E, "X"), + (0xA8F, "V"), + (0xA92, "X"), + (0xA93, "V"), + (0xAA9, "X"), + (0xAAA, "V"), + (0xAB1, "X"), + (0xAB2, "V"), + (0xAB4, "X"), + (0xAB5, "V"), + (0xABA, "X"), + (0xABC, "V"), + (0xAC6, "X"), + (0xAC7, "V"), + (0xACA, "X"), + (0xACB, "V"), + (0xACE, "X"), + (0xAD0, "V"), + (0xAD1, "X"), + (0xAE0, "V"), + (0xAE4, "X"), + (0xAE6, "V"), + (0xAF2, "X"), + (0xAF9, "V"), + (0xB00, "X"), + (0xB01, "V"), + (0xB04, "X"), + (0xB05, "V"), + (0xB0D, "X"), + (0xB0F, "V"), + (0xB11, "X"), + (0xB13, "V"), + (0xB29, "X"), + (0xB2A, "V"), + (0xB31, "X"), + (0xB32, "V"), + (0xB34, "X"), + (0xB35, "V"), + (0xB3A, "X"), + (0xB3C, "V"), + (0xB45, "X"), + (0xB47, "V"), + (0xB49, "X"), + (0xB4B, "V"), + (0xB4E, "X"), + (0xB55, "V"), + (0xB58, "X"), + (0xB5C, "M", "ଡ଼"), + (0xB5D, "M", "ଢ଼"), + (0xB5E, "X"), + (0xB5F, "V"), + (0xB64, "X"), + (0xB66, "V"), + (0xB78, "X"), + (0xB82, "V"), + (0xB84, "X"), + (0xB85, "V"), + (0xB8B, "X"), + (0xB8E, "V"), + (0xB91, "X"), + (0xB92, "V"), + (0xB96, "X"), + (0xB99, "V"), + (0xB9B, "X"), + (0xB9C, "V"), + (0xB9D, "X"), + (0xB9E, "V"), + (0xBA0, "X"), + (0xBA3, "V"), + (0xBA5, "X"), + (0xBA8, "V"), + (0xBAB, "X"), + (0xBAE, "V"), + (0xBBA, "X"), + (0xBBE, "V"), + (0xBC3, "X"), + (0xBC6, "V"), + (0xBC9, "X"), + (0xBCA, "V"), + (0xBCE, "X"), + (0xBD0, "V"), + (0xBD1, "X"), + (0xBD7, "V"), + (0xBD8, "X"), + (0xBE6, "V"), + (0xBFB, "X"), + (0xC00, "V"), + (0xC0D, "X"), + (0xC0E, "V"), + (0xC11, "X"), + (0xC12, "V"), + (0xC29, "X"), + (0xC2A, "V"), + ] + + +def _seg_12() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xC3A, "X"), + (0xC3C, "V"), + (0xC45, "X"), + (0xC46, "V"), + (0xC49, "X"), + (0xC4A, "V"), + (0xC4E, "X"), + (0xC55, "V"), + (0xC57, "X"), + (0xC58, "V"), + (0xC5B, "X"), + (0xC5D, "V"), + (0xC5E, "X"), + (0xC60, "V"), + (0xC64, "X"), + (0xC66, "V"), + (0xC70, "X"), + (0xC77, "V"), + (0xC8D, "X"), + (0xC8E, "V"), + (0xC91, "X"), + (0xC92, "V"), + (0xCA9, "X"), + (0xCAA, "V"), + (0xCB4, "X"), + (0xCB5, "V"), + (0xCBA, "X"), + (0xCBC, "V"), + (0xCC5, "X"), + (0xCC6, "V"), + (0xCC9, "X"), + (0xCCA, "V"), + (0xCCE, "X"), + (0xCD5, "V"), + (0xCD7, "X"), + (0xCDD, "V"), + (0xCDF, "X"), + (0xCE0, "V"), + (0xCE4, "X"), + (0xCE6, "V"), + (0xCF0, "X"), + (0xCF1, "V"), + (0xCF4, "X"), + (0xD00, "V"), + (0xD0D, "X"), + (0xD0E, "V"), + (0xD11, "X"), + (0xD12, "V"), + (0xD45, "X"), + (0xD46, "V"), + (0xD49, "X"), + (0xD4A, "V"), + (0xD50, "X"), + (0xD54, "V"), + (0xD64, "X"), + (0xD66, "V"), + (0xD80, "X"), + (0xD81, "V"), + (0xD84, "X"), + (0xD85, "V"), + (0xD97, "X"), + (0xD9A, "V"), + (0xDB2, "X"), + (0xDB3, "V"), + (0xDBC, "X"), + (0xDBD, "V"), + (0xDBE, "X"), + (0xDC0, "V"), + (0xDC7, "X"), + (0xDCA, "V"), + (0xDCB, "X"), + (0xDCF, "V"), + (0xDD5, "X"), + (0xDD6, "V"), + (0xDD7, "X"), + (0xDD8, "V"), + (0xDE0, "X"), + (0xDE6, "V"), + (0xDF0, "X"), + (0xDF2, "V"), + (0xDF5, "X"), + (0xE01, "V"), + (0xE33, "M", "ํา"), + (0xE34, "V"), + (0xE3B, "X"), + (0xE3F, "V"), + (0xE5C, "X"), + (0xE81, "V"), + (0xE83, "X"), + (0xE84, "V"), + (0xE85, "X"), + (0xE86, "V"), + (0xE8B, "X"), + (0xE8C, "V"), + (0xEA4, "X"), + (0xEA5, "V"), + (0xEA6, "X"), + (0xEA7, "V"), + (0xEB3, "M", "ໍາ"), + (0xEB4, "V"), + ] + + +def _seg_13() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xEBE, "X"), + (0xEC0, "V"), + (0xEC5, "X"), + (0xEC6, "V"), + (0xEC7, "X"), + (0xEC8, "V"), + (0xECF, "X"), + (0xED0, "V"), + (0xEDA, "X"), + (0xEDC, "M", "ຫນ"), + (0xEDD, "M", "ຫມ"), + (0xEDE, "V"), + (0xEE0, "X"), + (0xF00, "V"), + (0xF0C, "M", "་"), + (0xF0D, "V"), + (0xF43, "M", "གྷ"), + (0xF44, "V"), + (0xF48, "X"), + (0xF49, "V"), + (0xF4D, "M", "ཌྷ"), + (0xF4E, "V"), + (0xF52, "M", "དྷ"), + (0xF53, "V"), + (0xF57, "M", "བྷ"), + (0xF58, "V"), + (0xF5C, "M", "ཛྷ"), + (0xF5D, "V"), + (0xF69, "M", "ཀྵ"), + (0xF6A, "V"), + (0xF6D, "X"), + (0xF71, "V"), + (0xF73, "M", "ཱི"), + (0xF74, "V"), + (0xF75, "M", "ཱུ"), + (0xF76, "M", "ྲྀ"), + (0xF77, "M", "ྲཱྀ"), + (0xF78, "M", "ླྀ"), + (0xF79, "M", "ླཱྀ"), + (0xF7A, "V"), + (0xF81, "M", "ཱྀ"), + (0xF82, "V"), + (0xF93, "M", "ྒྷ"), + (0xF94, "V"), + (0xF98, "X"), + (0xF99, "V"), + (0xF9D, "M", "ྜྷ"), + (0xF9E, "V"), + (0xFA2, "M", "ྡྷ"), + (0xFA3, "V"), + (0xFA7, "M", "ྦྷ"), + (0xFA8, "V"), + (0xFAC, "M", "ྫྷ"), + (0xFAD, "V"), + (0xFB9, "M", "ྐྵ"), + (0xFBA, "V"), + (0xFBD, "X"), + (0xFBE, "V"), + (0xFCD, "X"), + (0xFCE, "V"), + (0xFDB, "X"), + (0x1000, "V"), + (0x10A0, "X"), + (0x10C7, "M", "ⴧ"), + (0x10C8, "X"), + (0x10CD, "M", "ⴭ"), + (0x10CE, "X"), + (0x10D0, "V"), + (0x10FC, "M", "ნ"), + (0x10FD, "V"), + (0x115F, "X"), + (0x1161, "V"), + (0x1249, "X"), + (0x124A, "V"), + (0x124E, "X"), + (0x1250, "V"), + (0x1257, "X"), + (0x1258, "V"), + (0x1259, "X"), + (0x125A, "V"), + (0x125E, "X"), + (0x1260, "V"), + (0x1289, "X"), + (0x128A, "V"), + (0x128E, "X"), + (0x1290, "V"), + (0x12B1, "X"), + (0x12B2, "V"), + (0x12B6, "X"), + (0x12B8, "V"), + (0x12BF, "X"), + (0x12C0, "V"), + (0x12C1, "X"), + (0x12C2, "V"), + (0x12C6, "X"), + (0x12C8, "V"), + (0x12D7, "X"), + (0x12D8, "V"), + (0x1311, "X"), + (0x1312, "V"), + ] + + +def _seg_14() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1316, "X"), + (0x1318, "V"), + (0x135B, "X"), + (0x135D, "V"), + (0x137D, "X"), + (0x1380, "V"), + (0x139A, "X"), + (0x13A0, "V"), + (0x13F6, "X"), + (0x13F8, "M", "Ᏸ"), + (0x13F9, "M", "Ᏹ"), + (0x13FA, "M", "Ᏺ"), + (0x13FB, "M", "Ᏻ"), + (0x13FC, "M", "Ᏼ"), + (0x13FD, "M", "Ᏽ"), + (0x13FE, "X"), + (0x1400, "V"), + (0x1680, "X"), + (0x1681, "V"), + (0x169D, "X"), + (0x16A0, "V"), + (0x16F9, "X"), + (0x1700, "V"), + (0x1716, "X"), + (0x171F, "V"), + (0x1737, "X"), + (0x1740, "V"), + (0x1754, "X"), + (0x1760, "V"), + (0x176D, "X"), + (0x176E, "V"), + (0x1771, "X"), + (0x1772, "V"), + (0x1774, "X"), + (0x1780, "V"), + (0x17B4, "X"), + (0x17B6, "V"), + (0x17DE, "X"), + (0x17E0, "V"), + (0x17EA, "X"), + (0x17F0, "V"), + (0x17FA, "X"), + (0x1800, "V"), + (0x1806, "X"), + (0x1807, "V"), + (0x180B, "I"), + (0x180E, "X"), + (0x180F, "I"), + (0x1810, "V"), + (0x181A, "X"), + (0x1820, "V"), + (0x1879, "X"), + (0x1880, "V"), + (0x18AB, "X"), + (0x18B0, "V"), + (0x18F6, "X"), + (0x1900, "V"), + (0x191F, "X"), + (0x1920, "V"), + (0x192C, "X"), + (0x1930, "V"), + (0x193C, "X"), + (0x1940, "V"), + (0x1941, "X"), + (0x1944, "V"), + (0x196E, "X"), + (0x1970, "V"), + (0x1975, "X"), + (0x1980, "V"), + (0x19AC, "X"), + (0x19B0, "V"), + (0x19CA, "X"), + (0x19D0, "V"), + (0x19DB, "X"), + (0x19DE, "V"), + (0x1A1C, "X"), + (0x1A1E, "V"), + (0x1A5F, "X"), + (0x1A60, "V"), + (0x1A7D, "X"), + (0x1A7F, "V"), + (0x1A8A, "X"), + (0x1A90, "V"), + (0x1A9A, "X"), + (0x1AA0, "V"), + (0x1AAE, "X"), + (0x1AB0, "V"), + (0x1ACF, "X"), + (0x1B00, "V"), + (0x1B4D, "X"), + (0x1B50, "V"), + (0x1B7F, "X"), + (0x1B80, "V"), + (0x1BF4, "X"), + (0x1BFC, "V"), + (0x1C38, "X"), + (0x1C3B, "V"), + (0x1C4A, "X"), + (0x1C4D, "V"), + (0x1C80, "M", "в"), + ] + + +def _seg_15() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1C81, "M", "д"), + (0x1C82, "M", "о"), + (0x1C83, "M", "с"), + (0x1C84, "M", "т"), + (0x1C86, "M", "ъ"), + (0x1C87, "M", "ѣ"), + (0x1C88, "M", "ꙋ"), + (0x1C89, "X"), + (0x1C90, "M", "ა"), + (0x1C91, "M", "ბ"), + (0x1C92, "M", "გ"), + (0x1C93, "M", "დ"), + (0x1C94, "M", "ე"), + (0x1C95, "M", "ვ"), + (0x1C96, "M", "ზ"), + (0x1C97, "M", "თ"), + (0x1C98, "M", "ი"), + (0x1C99, "M", "კ"), + (0x1C9A, "M", "ლ"), + (0x1C9B, "M", "მ"), + (0x1C9C, "M", "ნ"), + (0x1C9D, "M", "ო"), + (0x1C9E, "M", "პ"), + (0x1C9F, "M", "ჟ"), + (0x1CA0, "M", "რ"), + (0x1CA1, "M", "ს"), + (0x1CA2, "M", "ტ"), + (0x1CA3, "M", "უ"), + (0x1CA4, "M", "ფ"), + (0x1CA5, "M", "ქ"), + (0x1CA6, "M", "ღ"), + (0x1CA7, "M", "ყ"), + (0x1CA8, "M", "შ"), + (0x1CA9, "M", "ჩ"), + (0x1CAA, "M", "ც"), + (0x1CAB, "M", "ძ"), + (0x1CAC, "M", "წ"), + (0x1CAD, "M", "ჭ"), + (0x1CAE, "M", "ხ"), + (0x1CAF, "M", "ჯ"), + (0x1CB0, "M", "ჰ"), + (0x1CB1, "M", "ჱ"), + (0x1CB2, "M", "ჲ"), + (0x1CB3, "M", "ჳ"), + (0x1CB4, "M", "ჴ"), + (0x1CB5, "M", "ჵ"), + (0x1CB6, "M", "ჶ"), + (0x1CB7, "M", "ჷ"), + (0x1CB8, "M", "ჸ"), + (0x1CB9, "M", "ჹ"), + (0x1CBA, "M", "ჺ"), + (0x1CBB, "X"), + (0x1CBD, "M", "ჽ"), + (0x1CBE, "M", "ჾ"), + (0x1CBF, "M", "ჿ"), + (0x1CC0, "V"), + (0x1CC8, "X"), + (0x1CD0, "V"), + (0x1CFB, "X"), + (0x1D00, "V"), + (0x1D2C, "M", "a"), + (0x1D2D, "M", "æ"), + (0x1D2E, "M", "b"), + (0x1D2F, "V"), + (0x1D30, "M", "d"), + (0x1D31, "M", "e"), + (0x1D32, "M", "ǝ"), + (0x1D33, "M", "g"), + (0x1D34, "M", "h"), + (0x1D35, "M", "i"), + (0x1D36, "M", "j"), + (0x1D37, "M", "k"), + (0x1D38, "M", "l"), + (0x1D39, "M", "m"), + (0x1D3A, "M", "n"), + (0x1D3B, "V"), + (0x1D3C, "M", "o"), + (0x1D3D, "M", "ȣ"), + (0x1D3E, "M", "p"), + (0x1D3F, "M", "r"), + (0x1D40, "M", "t"), + (0x1D41, "M", "u"), + (0x1D42, "M", "w"), + (0x1D43, "M", "a"), + (0x1D44, "M", "ɐ"), + (0x1D45, "M", "ɑ"), + (0x1D46, "M", "ᴂ"), + (0x1D47, "M", "b"), + (0x1D48, "M", "d"), + (0x1D49, "M", "e"), + (0x1D4A, "M", "ə"), + (0x1D4B, "M", "ɛ"), + (0x1D4C, "M", "ɜ"), + (0x1D4D, "M", "g"), + (0x1D4E, "V"), + (0x1D4F, "M", "k"), + (0x1D50, "M", "m"), + (0x1D51, "M", "ŋ"), + (0x1D52, "M", "o"), + (0x1D53, "M", "ɔ"), + ] + + +def _seg_16() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D54, "M", "ᴖ"), + (0x1D55, "M", "ᴗ"), + (0x1D56, "M", "p"), + (0x1D57, "M", "t"), + (0x1D58, "M", "u"), + (0x1D59, "M", "ᴝ"), + (0x1D5A, "M", "ɯ"), + (0x1D5B, "M", "v"), + (0x1D5C, "M", "ᴥ"), + (0x1D5D, "M", "β"), + (0x1D5E, "M", "γ"), + (0x1D5F, "M", "δ"), + (0x1D60, "M", "φ"), + (0x1D61, "M", "χ"), + (0x1D62, "M", "i"), + (0x1D63, "M", "r"), + (0x1D64, "M", "u"), + (0x1D65, "M", "v"), + (0x1D66, "M", "β"), + (0x1D67, "M", "γ"), + (0x1D68, "M", "ρ"), + (0x1D69, "M", "φ"), + (0x1D6A, "M", "χ"), + (0x1D6B, "V"), + (0x1D78, "M", "н"), + (0x1D79, "V"), + (0x1D9B, "M", "ɒ"), + (0x1D9C, "M", "c"), + (0x1D9D, "M", "ɕ"), + (0x1D9E, "M", "ð"), + (0x1D9F, "M", "ɜ"), + (0x1DA0, "M", "f"), + (0x1DA1, "M", "ɟ"), + (0x1DA2, "M", "ɡ"), + (0x1DA3, "M", "ɥ"), + (0x1DA4, "M", "ɨ"), + (0x1DA5, "M", "ɩ"), + (0x1DA6, "M", "ɪ"), + (0x1DA7, "M", "ᵻ"), + (0x1DA8, "M", "ʝ"), + (0x1DA9, "M", "ɭ"), + (0x1DAA, "M", "ᶅ"), + (0x1DAB, "M", "ʟ"), + (0x1DAC, "M", "ɱ"), + (0x1DAD, "M", "ɰ"), + (0x1DAE, "M", "ɲ"), + (0x1DAF, "M", "ɳ"), + (0x1DB0, "M", "ɴ"), + (0x1DB1, "M", "ɵ"), + (0x1DB2, "M", "ɸ"), + (0x1DB3, "M", "ʂ"), + (0x1DB4, "M", "ʃ"), + (0x1DB5, "M", "ƫ"), + (0x1DB6, "M", "ʉ"), + (0x1DB7, "M", "ʊ"), + (0x1DB8, "M", "ᴜ"), + (0x1DB9, "M", "ʋ"), + (0x1DBA, "M", "ʌ"), + (0x1DBB, "M", "z"), + (0x1DBC, "M", "ʐ"), + (0x1DBD, "M", "ʑ"), + (0x1DBE, "M", "ʒ"), + (0x1DBF, "M", "θ"), + (0x1DC0, "V"), + (0x1E00, "M", "ḁ"), + (0x1E01, "V"), + (0x1E02, "M", "ḃ"), + (0x1E03, "V"), + (0x1E04, "M", "ḅ"), + (0x1E05, "V"), + (0x1E06, "M", "ḇ"), + (0x1E07, "V"), + (0x1E08, "M", "ḉ"), + (0x1E09, "V"), + (0x1E0A, "M", "ḋ"), + (0x1E0B, "V"), + (0x1E0C, "M", "ḍ"), + (0x1E0D, "V"), + (0x1E0E, "M", "ḏ"), + (0x1E0F, "V"), + (0x1E10, "M", "ḑ"), + (0x1E11, "V"), + (0x1E12, "M", "ḓ"), + (0x1E13, "V"), + (0x1E14, "M", "ḕ"), + (0x1E15, "V"), + (0x1E16, "M", "ḗ"), + (0x1E17, "V"), + (0x1E18, "M", "ḙ"), + (0x1E19, "V"), + (0x1E1A, "M", "ḛ"), + (0x1E1B, "V"), + (0x1E1C, "M", "ḝ"), + (0x1E1D, "V"), + (0x1E1E, "M", "ḟ"), + (0x1E1F, "V"), + (0x1E20, "M", "ḡ"), + (0x1E21, "V"), + (0x1E22, "M", "ḣ"), + (0x1E23, "V"), + ] + + +def _seg_17() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1E24, "M", "ḥ"), + (0x1E25, "V"), + (0x1E26, "M", "ḧ"), + (0x1E27, "V"), + (0x1E28, "M", "ḩ"), + (0x1E29, "V"), + (0x1E2A, "M", "ḫ"), + (0x1E2B, "V"), + (0x1E2C, "M", "ḭ"), + (0x1E2D, "V"), + (0x1E2E, "M", "ḯ"), + (0x1E2F, "V"), + (0x1E30, "M", "ḱ"), + (0x1E31, "V"), + (0x1E32, "M", "ḳ"), + (0x1E33, "V"), + (0x1E34, "M", "ḵ"), + (0x1E35, "V"), + (0x1E36, "M", "ḷ"), + (0x1E37, "V"), + (0x1E38, "M", "ḹ"), + (0x1E39, "V"), + (0x1E3A, "M", "ḻ"), + (0x1E3B, "V"), + (0x1E3C, "M", "ḽ"), + (0x1E3D, "V"), + (0x1E3E, "M", "ḿ"), + (0x1E3F, "V"), + (0x1E40, "M", "ṁ"), + (0x1E41, "V"), + (0x1E42, "M", "ṃ"), + (0x1E43, "V"), + (0x1E44, "M", "ṅ"), + (0x1E45, "V"), + (0x1E46, "M", "ṇ"), + (0x1E47, "V"), + (0x1E48, "M", "ṉ"), + (0x1E49, "V"), + (0x1E4A, "M", "ṋ"), + (0x1E4B, "V"), + (0x1E4C, "M", "ṍ"), + (0x1E4D, "V"), + (0x1E4E, "M", "ṏ"), + (0x1E4F, "V"), + (0x1E50, "M", "ṑ"), + (0x1E51, "V"), + (0x1E52, "M", "ṓ"), + (0x1E53, "V"), + (0x1E54, "M", "ṕ"), + (0x1E55, "V"), + (0x1E56, "M", "ṗ"), + (0x1E57, "V"), + (0x1E58, "M", "ṙ"), + (0x1E59, "V"), + (0x1E5A, "M", "ṛ"), + (0x1E5B, "V"), + (0x1E5C, "M", "ṝ"), + (0x1E5D, "V"), + (0x1E5E, "M", "ṟ"), + (0x1E5F, "V"), + (0x1E60, "M", "ṡ"), + (0x1E61, "V"), + (0x1E62, "M", "ṣ"), + (0x1E63, "V"), + (0x1E64, "M", "ṥ"), + (0x1E65, "V"), + (0x1E66, "M", "ṧ"), + (0x1E67, "V"), + (0x1E68, "M", "ṩ"), + (0x1E69, "V"), + (0x1E6A, "M", "ṫ"), + (0x1E6B, "V"), + (0x1E6C, "M", "ṭ"), + (0x1E6D, "V"), + (0x1E6E, "M", "ṯ"), + (0x1E6F, "V"), + (0x1E70, "M", "ṱ"), + (0x1E71, "V"), + (0x1E72, "M", "ṳ"), + (0x1E73, "V"), + (0x1E74, "M", "ṵ"), + (0x1E75, "V"), + (0x1E76, "M", "ṷ"), + (0x1E77, "V"), + (0x1E78, "M", "ṹ"), + (0x1E79, "V"), + (0x1E7A, "M", "ṻ"), + (0x1E7B, "V"), + (0x1E7C, "M", "ṽ"), + (0x1E7D, "V"), + (0x1E7E, "M", "ṿ"), + (0x1E7F, "V"), + (0x1E80, "M", "ẁ"), + (0x1E81, "V"), + (0x1E82, "M", "ẃ"), + (0x1E83, "V"), + (0x1E84, "M", "ẅ"), + (0x1E85, "V"), + (0x1E86, "M", "ẇ"), + (0x1E87, "V"), + ] + + +def _seg_18() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1E88, "M", "ẉ"), + (0x1E89, "V"), + (0x1E8A, "M", "ẋ"), + (0x1E8B, "V"), + (0x1E8C, "M", "ẍ"), + (0x1E8D, "V"), + (0x1E8E, "M", "ẏ"), + (0x1E8F, "V"), + (0x1E90, "M", "ẑ"), + (0x1E91, "V"), + (0x1E92, "M", "ẓ"), + (0x1E93, "V"), + (0x1E94, "M", "ẕ"), + (0x1E95, "V"), + (0x1E9A, "M", "aʾ"), + (0x1E9B, "M", "ṡ"), + (0x1E9C, "V"), + (0x1E9E, "M", "ß"), + (0x1E9F, "V"), + (0x1EA0, "M", "ạ"), + (0x1EA1, "V"), + (0x1EA2, "M", "ả"), + (0x1EA3, "V"), + (0x1EA4, "M", "ấ"), + (0x1EA5, "V"), + (0x1EA6, "M", "ầ"), + (0x1EA7, "V"), + (0x1EA8, "M", "ẩ"), + (0x1EA9, "V"), + (0x1EAA, "M", "ẫ"), + (0x1EAB, "V"), + (0x1EAC, "M", "ậ"), + (0x1EAD, "V"), + (0x1EAE, "M", "ắ"), + (0x1EAF, "V"), + (0x1EB0, "M", "ằ"), + (0x1EB1, "V"), + (0x1EB2, "M", "ẳ"), + (0x1EB3, "V"), + (0x1EB4, "M", "ẵ"), + (0x1EB5, "V"), + (0x1EB6, "M", "ặ"), + (0x1EB7, "V"), + (0x1EB8, "M", "ẹ"), + (0x1EB9, "V"), + (0x1EBA, "M", "ẻ"), + (0x1EBB, "V"), + (0x1EBC, "M", "ẽ"), + (0x1EBD, "V"), + (0x1EBE, "M", "ế"), + (0x1EBF, "V"), + (0x1EC0, "M", "ề"), + (0x1EC1, "V"), + (0x1EC2, "M", "ể"), + (0x1EC3, "V"), + (0x1EC4, "M", "ễ"), + (0x1EC5, "V"), + (0x1EC6, "M", "ệ"), + (0x1EC7, "V"), + (0x1EC8, "M", "ỉ"), + (0x1EC9, "V"), + (0x1ECA, "M", "ị"), + (0x1ECB, "V"), + (0x1ECC, "M", "ọ"), + (0x1ECD, "V"), + (0x1ECE, "M", "ỏ"), + (0x1ECF, "V"), + (0x1ED0, "M", "ố"), + (0x1ED1, "V"), + (0x1ED2, "M", "ồ"), + (0x1ED3, "V"), + (0x1ED4, "M", "ổ"), + (0x1ED5, "V"), + (0x1ED6, "M", "ỗ"), + (0x1ED7, "V"), + (0x1ED8, "M", "ộ"), + (0x1ED9, "V"), + (0x1EDA, "M", "ớ"), + (0x1EDB, "V"), + (0x1EDC, "M", "ờ"), + (0x1EDD, "V"), + (0x1EDE, "M", "ở"), + (0x1EDF, "V"), + (0x1EE0, "M", "ỡ"), + (0x1EE1, "V"), + (0x1EE2, "M", "ợ"), + (0x1EE3, "V"), + (0x1EE4, "M", "ụ"), + (0x1EE5, "V"), + (0x1EE6, "M", "ủ"), + (0x1EE7, "V"), + (0x1EE8, "M", "ứ"), + (0x1EE9, "V"), + (0x1EEA, "M", "ừ"), + (0x1EEB, "V"), + (0x1EEC, "M", "ử"), + (0x1EED, "V"), + (0x1EEE, "M", "ữ"), + (0x1EEF, "V"), + (0x1EF0, "M", "ự"), + ] + + +def _seg_19() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1EF1, "V"), + (0x1EF2, "M", "ỳ"), + (0x1EF3, "V"), + (0x1EF4, "M", "ỵ"), + (0x1EF5, "V"), + (0x1EF6, "M", "ỷ"), + (0x1EF7, "V"), + (0x1EF8, "M", "ỹ"), + (0x1EF9, "V"), + (0x1EFA, "M", "ỻ"), + (0x1EFB, "V"), + (0x1EFC, "M", "ỽ"), + (0x1EFD, "V"), + (0x1EFE, "M", "ỿ"), + (0x1EFF, "V"), + (0x1F08, "M", "ἀ"), + (0x1F09, "M", "ἁ"), + (0x1F0A, "M", "ἂ"), + (0x1F0B, "M", "ἃ"), + (0x1F0C, "M", "ἄ"), + (0x1F0D, "M", "ἅ"), + (0x1F0E, "M", "ἆ"), + (0x1F0F, "M", "ἇ"), + (0x1F10, "V"), + (0x1F16, "X"), + (0x1F18, "M", "ἐ"), + (0x1F19, "M", "ἑ"), + (0x1F1A, "M", "ἒ"), + (0x1F1B, "M", "ἓ"), + (0x1F1C, "M", "ἔ"), + (0x1F1D, "M", "ἕ"), + (0x1F1E, "X"), + (0x1F20, "V"), + (0x1F28, "M", "ἠ"), + (0x1F29, "M", "ἡ"), + (0x1F2A, "M", "ἢ"), + (0x1F2B, "M", "ἣ"), + (0x1F2C, "M", "ἤ"), + (0x1F2D, "M", "ἥ"), + (0x1F2E, "M", "ἦ"), + (0x1F2F, "M", "ἧ"), + (0x1F30, "V"), + (0x1F38, "M", "ἰ"), + (0x1F39, "M", "ἱ"), + (0x1F3A, "M", "ἲ"), + (0x1F3B, "M", "ἳ"), + (0x1F3C, "M", "ἴ"), + (0x1F3D, "M", "ἵ"), + (0x1F3E, "M", "ἶ"), + (0x1F3F, "M", "ἷ"), + (0x1F40, "V"), + (0x1F46, "X"), + (0x1F48, "M", "ὀ"), + (0x1F49, "M", "ὁ"), + (0x1F4A, "M", "ὂ"), + (0x1F4B, "M", "ὃ"), + (0x1F4C, "M", "ὄ"), + (0x1F4D, "M", "ὅ"), + (0x1F4E, "X"), + (0x1F50, "V"), + (0x1F58, "X"), + (0x1F59, "M", "ὑ"), + (0x1F5A, "X"), + (0x1F5B, "M", "ὓ"), + (0x1F5C, "X"), + (0x1F5D, "M", "ὕ"), + (0x1F5E, "X"), + (0x1F5F, "M", "ὗ"), + (0x1F60, "V"), + (0x1F68, "M", "ὠ"), + (0x1F69, "M", "ὡ"), + (0x1F6A, "M", "ὢ"), + (0x1F6B, "M", "ὣ"), + (0x1F6C, "M", "ὤ"), + (0x1F6D, "M", "ὥ"), + (0x1F6E, "M", "ὦ"), + (0x1F6F, "M", "ὧ"), + (0x1F70, "V"), + (0x1F71, "M", "ά"), + (0x1F72, "V"), + (0x1F73, "M", "έ"), + (0x1F74, "V"), + (0x1F75, "M", "ή"), + (0x1F76, "V"), + (0x1F77, "M", "ί"), + (0x1F78, "V"), + (0x1F79, "M", "ό"), + (0x1F7A, "V"), + (0x1F7B, "M", "ύ"), + (0x1F7C, "V"), + (0x1F7D, "M", "ώ"), + (0x1F7E, "X"), + (0x1F80, "M", "ἀι"), + (0x1F81, "M", "ἁι"), + (0x1F82, "M", "ἂι"), + (0x1F83, "M", "ἃι"), + (0x1F84, "M", "ἄι"), + (0x1F85, "M", "ἅι"), + (0x1F86, "M", "ἆι"), + (0x1F87, "M", "ἇι"), + ] + + +def _seg_20() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1F88, "M", "ἀι"), + (0x1F89, "M", "ἁι"), + (0x1F8A, "M", "ἂι"), + (0x1F8B, "M", "ἃι"), + (0x1F8C, "M", "ἄι"), + (0x1F8D, "M", "ἅι"), + (0x1F8E, "M", "ἆι"), + (0x1F8F, "M", "ἇι"), + (0x1F90, "M", "ἠι"), + (0x1F91, "M", "ἡι"), + (0x1F92, "M", "ἢι"), + (0x1F93, "M", "ἣι"), + (0x1F94, "M", "ἤι"), + (0x1F95, "M", "ἥι"), + (0x1F96, "M", "ἦι"), + (0x1F97, "M", "ἧι"), + (0x1F98, "M", "ἠι"), + (0x1F99, "M", "ἡι"), + (0x1F9A, "M", "ἢι"), + (0x1F9B, "M", "ἣι"), + (0x1F9C, "M", "ἤι"), + (0x1F9D, "M", "ἥι"), + (0x1F9E, "M", "ἦι"), + (0x1F9F, "M", "ἧι"), + (0x1FA0, "M", "ὠι"), + (0x1FA1, "M", "ὡι"), + (0x1FA2, "M", "ὢι"), + (0x1FA3, "M", "ὣι"), + (0x1FA4, "M", "ὤι"), + (0x1FA5, "M", "ὥι"), + (0x1FA6, "M", "ὦι"), + (0x1FA7, "M", "ὧι"), + (0x1FA8, "M", "ὠι"), + (0x1FA9, "M", "ὡι"), + (0x1FAA, "M", "ὢι"), + (0x1FAB, "M", "ὣι"), + (0x1FAC, "M", "ὤι"), + (0x1FAD, "M", "ὥι"), + (0x1FAE, "M", "ὦι"), + (0x1FAF, "M", "ὧι"), + (0x1FB0, "V"), + (0x1FB2, "M", "ὰι"), + (0x1FB3, "M", "αι"), + (0x1FB4, "M", "άι"), + (0x1FB5, "X"), + (0x1FB6, "V"), + (0x1FB7, "M", "ᾶι"), + (0x1FB8, "M", "ᾰ"), + (0x1FB9, "M", "ᾱ"), + (0x1FBA, "M", "ὰ"), + (0x1FBB, "M", "ά"), + (0x1FBC, "M", "αι"), + (0x1FBD, "3", " ̓"), + (0x1FBE, "M", "ι"), + (0x1FBF, "3", " ̓"), + (0x1FC0, "3", " ͂"), + (0x1FC1, "3", " ̈͂"), + (0x1FC2, "M", "ὴι"), + (0x1FC3, "M", "ηι"), + (0x1FC4, "M", "ήι"), + (0x1FC5, "X"), + (0x1FC6, "V"), + (0x1FC7, "M", "ῆι"), + (0x1FC8, "M", "ὲ"), + (0x1FC9, "M", "έ"), + (0x1FCA, "M", "ὴ"), + (0x1FCB, "M", "ή"), + (0x1FCC, "M", "ηι"), + (0x1FCD, "3", " ̓̀"), + (0x1FCE, "3", " ̓́"), + (0x1FCF, "3", " ̓͂"), + (0x1FD0, "V"), + (0x1FD3, "M", "ΐ"), + (0x1FD4, "X"), + (0x1FD6, "V"), + (0x1FD8, "M", "ῐ"), + (0x1FD9, "M", "ῑ"), + (0x1FDA, "M", "ὶ"), + (0x1FDB, "M", "ί"), + (0x1FDC, "X"), + (0x1FDD, "3", " ̔̀"), + (0x1FDE, "3", " ̔́"), + (0x1FDF, "3", " ̔͂"), + (0x1FE0, "V"), + (0x1FE3, "M", "ΰ"), + (0x1FE4, "V"), + (0x1FE8, "M", "ῠ"), + (0x1FE9, "M", "ῡ"), + (0x1FEA, "M", "ὺ"), + (0x1FEB, "M", "ύ"), + (0x1FEC, "M", "ῥ"), + (0x1FED, "3", " ̈̀"), + (0x1FEE, "3", " ̈́"), + (0x1FEF, "3", "`"), + (0x1FF0, "X"), + (0x1FF2, "M", "ὼι"), + (0x1FF3, "M", "ωι"), + (0x1FF4, "M", "ώι"), + (0x1FF5, "X"), + (0x1FF6, "V"), + ] + + +def _seg_21() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1FF7, "M", "ῶι"), + (0x1FF8, "M", "ὸ"), + (0x1FF9, "M", "ό"), + (0x1FFA, "M", "ὼ"), + (0x1FFB, "M", "ώ"), + (0x1FFC, "M", "ωι"), + (0x1FFD, "3", " ́"), + (0x1FFE, "3", " ̔"), + (0x1FFF, "X"), + (0x2000, "3", " "), + (0x200B, "I"), + (0x200C, "D", ""), + (0x200E, "X"), + (0x2010, "V"), + (0x2011, "M", "‐"), + (0x2012, "V"), + (0x2017, "3", " ̳"), + (0x2018, "V"), + (0x2024, "X"), + (0x2027, "V"), + (0x2028, "X"), + (0x202F, "3", " "), + (0x2030, "V"), + (0x2033, "M", "′′"), + (0x2034, "M", "′′′"), + (0x2035, "V"), + (0x2036, "M", "‵‵"), + (0x2037, "M", "‵‵‵"), + (0x2038, "V"), + (0x203C, "3", "!!"), + (0x203D, "V"), + (0x203E, "3", " ̅"), + (0x203F, "V"), + (0x2047, "3", "??"), + (0x2048, "3", "?!"), + (0x2049, "3", "!?"), + (0x204A, "V"), + (0x2057, "M", "′′′′"), + (0x2058, "V"), + (0x205F, "3", " "), + (0x2060, "I"), + (0x2061, "X"), + (0x2064, "I"), + (0x2065, "X"), + (0x2070, "M", "0"), + (0x2071, "M", "i"), + (0x2072, "X"), + (0x2074, "M", "4"), + (0x2075, "M", "5"), + (0x2076, "M", "6"), + (0x2077, "M", "7"), + (0x2078, "M", "8"), + (0x2079, "M", "9"), + (0x207A, "3", "+"), + (0x207B, "M", "−"), + (0x207C, "3", "="), + (0x207D, "3", "("), + (0x207E, "3", ")"), + (0x207F, "M", "n"), + (0x2080, "M", "0"), + (0x2081, "M", "1"), + (0x2082, "M", "2"), + (0x2083, "M", "3"), + (0x2084, "M", "4"), + (0x2085, "M", "5"), + (0x2086, "M", "6"), + (0x2087, "M", "7"), + (0x2088, "M", "8"), + (0x2089, "M", "9"), + (0x208A, "3", "+"), + (0x208B, "M", "−"), + (0x208C, "3", "="), + (0x208D, "3", "("), + (0x208E, "3", ")"), + (0x208F, "X"), + (0x2090, "M", "a"), + (0x2091, "M", "e"), + (0x2092, "M", "o"), + (0x2093, "M", "x"), + (0x2094, "M", "ə"), + (0x2095, "M", "h"), + (0x2096, "M", "k"), + (0x2097, "M", "l"), + (0x2098, "M", "m"), + (0x2099, "M", "n"), + (0x209A, "M", "p"), + (0x209B, "M", "s"), + (0x209C, "M", "t"), + (0x209D, "X"), + (0x20A0, "V"), + (0x20A8, "M", "rs"), + (0x20A9, "V"), + (0x20C1, "X"), + (0x20D0, "V"), + (0x20F1, "X"), + (0x2100, "3", "a/c"), + (0x2101, "3", "a/s"), + (0x2102, "M", "c"), + (0x2103, "M", "°c"), + (0x2104, "V"), + ] + + +def _seg_22() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2105, "3", "c/o"), + (0x2106, "3", "c/u"), + (0x2107, "M", "ɛ"), + (0x2108, "V"), + (0x2109, "M", "°f"), + (0x210A, "M", "g"), + (0x210B, "M", "h"), + (0x210F, "M", "ħ"), + (0x2110, "M", "i"), + (0x2112, "M", "l"), + (0x2114, "V"), + (0x2115, "M", "n"), + (0x2116, "M", "no"), + (0x2117, "V"), + (0x2119, "M", "p"), + (0x211A, "M", "q"), + (0x211B, "M", "r"), + (0x211E, "V"), + (0x2120, "M", "sm"), + (0x2121, "M", "tel"), + (0x2122, "M", "tm"), + (0x2123, "V"), + (0x2124, "M", "z"), + (0x2125, "V"), + (0x2126, "M", "ω"), + (0x2127, "V"), + (0x2128, "M", "z"), + (0x2129, "V"), + (0x212A, "M", "k"), + (0x212B, "M", "å"), + (0x212C, "M", "b"), + (0x212D, "M", "c"), + (0x212E, "V"), + (0x212F, "M", "e"), + (0x2131, "M", "f"), + (0x2132, "X"), + (0x2133, "M", "m"), + (0x2134, "M", "o"), + (0x2135, "M", "א"), + (0x2136, "M", "ב"), + (0x2137, "M", "ג"), + (0x2138, "M", "ד"), + (0x2139, "M", "i"), + (0x213A, "V"), + (0x213B, "M", "fax"), + (0x213C, "M", "π"), + (0x213D, "M", "γ"), + (0x213F, "M", "π"), + (0x2140, "M", "∑"), + (0x2141, "V"), + (0x2145, "M", "d"), + (0x2147, "M", "e"), + (0x2148, "M", "i"), + (0x2149, "M", "j"), + (0x214A, "V"), + (0x2150, "M", "1⁄7"), + (0x2151, "M", "1⁄9"), + (0x2152, "M", "1⁄10"), + (0x2153, "M", "1⁄3"), + (0x2154, "M", "2⁄3"), + (0x2155, "M", "1⁄5"), + (0x2156, "M", "2⁄5"), + (0x2157, "M", "3⁄5"), + (0x2158, "M", "4⁄5"), + (0x2159, "M", "1⁄6"), + (0x215A, "M", "5⁄6"), + (0x215B, "M", "1⁄8"), + (0x215C, "M", "3⁄8"), + (0x215D, "M", "5⁄8"), + (0x215E, "M", "7⁄8"), + (0x215F, "M", "1⁄"), + (0x2160, "M", "i"), + (0x2161, "M", "ii"), + (0x2162, "M", "iii"), + (0x2163, "M", "iv"), + (0x2164, "M", "v"), + (0x2165, "M", "vi"), + (0x2166, "M", "vii"), + (0x2167, "M", "viii"), + (0x2168, "M", "ix"), + (0x2169, "M", "x"), + (0x216A, "M", "xi"), + (0x216B, "M", "xii"), + (0x216C, "M", "l"), + (0x216D, "M", "c"), + (0x216E, "M", "d"), + (0x216F, "M", "m"), + (0x2170, "M", "i"), + (0x2171, "M", "ii"), + (0x2172, "M", "iii"), + (0x2173, "M", "iv"), + (0x2174, "M", "v"), + (0x2175, "M", "vi"), + (0x2176, "M", "vii"), + (0x2177, "M", "viii"), + (0x2178, "M", "ix"), + (0x2179, "M", "x"), + (0x217A, "M", "xi"), + (0x217B, "M", "xii"), + (0x217C, "M", "l"), + ] + + +def _seg_23() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x217D, "M", "c"), + (0x217E, "M", "d"), + (0x217F, "M", "m"), + (0x2180, "V"), + (0x2183, "X"), + (0x2184, "V"), + (0x2189, "M", "0⁄3"), + (0x218A, "V"), + (0x218C, "X"), + (0x2190, "V"), + (0x222C, "M", "∫∫"), + (0x222D, "M", "∫∫∫"), + (0x222E, "V"), + (0x222F, "M", "∮∮"), + (0x2230, "M", "∮∮∮"), + (0x2231, "V"), + (0x2329, "M", "〈"), + (0x232A, "M", "〉"), + (0x232B, "V"), + (0x2427, "X"), + (0x2440, "V"), + (0x244B, "X"), + (0x2460, "M", "1"), + (0x2461, "M", "2"), + (0x2462, "M", "3"), + (0x2463, "M", "4"), + (0x2464, "M", "5"), + (0x2465, "M", "6"), + (0x2466, "M", "7"), + (0x2467, "M", "8"), + (0x2468, "M", "9"), + (0x2469, "M", "10"), + (0x246A, "M", "11"), + (0x246B, "M", "12"), + (0x246C, "M", "13"), + (0x246D, "M", "14"), + (0x246E, "M", "15"), + (0x246F, "M", "16"), + (0x2470, "M", "17"), + (0x2471, "M", "18"), + (0x2472, "M", "19"), + (0x2473, "M", "20"), + (0x2474, "3", "(1)"), + (0x2475, "3", "(2)"), + (0x2476, "3", "(3)"), + (0x2477, "3", "(4)"), + (0x2478, "3", "(5)"), + (0x2479, "3", "(6)"), + (0x247A, "3", "(7)"), + (0x247B, "3", "(8)"), + (0x247C, "3", "(9)"), + (0x247D, "3", "(10)"), + (0x247E, "3", "(11)"), + (0x247F, "3", "(12)"), + (0x2480, "3", "(13)"), + (0x2481, "3", "(14)"), + (0x2482, "3", "(15)"), + (0x2483, "3", "(16)"), + (0x2484, "3", "(17)"), + (0x2485, "3", "(18)"), + (0x2486, "3", "(19)"), + (0x2487, "3", "(20)"), + (0x2488, "X"), + (0x249C, "3", "(a)"), + (0x249D, "3", "(b)"), + (0x249E, "3", "(c)"), + (0x249F, "3", "(d)"), + (0x24A0, "3", "(e)"), + (0x24A1, "3", "(f)"), + (0x24A2, "3", "(g)"), + (0x24A3, "3", "(h)"), + (0x24A4, "3", "(i)"), + (0x24A5, "3", "(j)"), + (0x24A6, "3", "(k)"), + (0x24A7, "3", "(l)"), + (0x24A8, "3", "(m)"), + (0x24A9, "3", "(n)"), + (0x24AA, "3", "(o)"), + (0x24AB, "3", "(p)"), + (0x24AC, "3", "(q)"), + (0x24AD, "3", "(r)"), + (0x24AE, "3", "(s)"), + (0x24AF, "3", "(t)"), + (0x24B0, "3", "(u)"), + (0x24B1, "3", "(v)"), + (0x24B2, "3", "(w)"), + (0x24B3, "3", "(x)"), + (0x24B4, "3", "(y)"), + (0x24B5, "3", "(z)"), + (0x24B6, "M", "a"), + (0x24B7, "M", "b"), + (0x24B8, "M", "c"), + (0x24B9, "M", "d"), + (0x24BA, "M", "e"), + (0x24BB, "M", "f"), + (0x24BC, "M", "g"), + (0x24BD, "M", "h"), + (0x24BE, "M", "i"), + (0x24BF, "M", "j"), + (0x24C0, "M", "k"), + ] + + +def _seg_24() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x24C1, "M", "l"), + (0x24C2, "M", "m"), + (0x24C3, "M", "n"), + (0x24C4, "M", "o"), + (0x24C5, "M", "p"), + (0x24C6, "M", "q"), + (0x24C7, "M", "r"), + (0x24C8, "M", "s"), + (0x24C9, "M", "t"), + (0x24CA, "M", "u"), + (0x24CB, "M", "v"), + (0x24CC, "M", "w"), + (0x24CD, "M", "x"), + (0x24CE, "M", "y"), + (0x24CF, "M", "z"), + (0x24D0, "M", "a"), + (0x24D1, "M", "b"), + (0x24D2, "M", "c"), + (0x24D3, "M", "d"), + (0x24D4, "M", "e"), + (0x24D5, "M", "f"), + (0x24D6, "M", "g"), + (0x24D7, "M", "h"), + (0x24D8, "M", "i"), + (0x24D9, "M", "j"), + (0x24DA, "M", "k"), + (0x24DB, "M", "l"), + (0x24DC, "M", "m"), + (0x24DD, "M", "n"), + (0x24DE, "M", "o"), + (0x24DF, "M", "p"), + (0x24E0, "M", "q"), + (0x24E1, "M", "r"), + (0x24E2, "M", "s"), + (0x24E3, "M", "t"), + (0x24E4, "M", "u"), + (0x24E5, "M", "v"), + (0x24E6, "M", "w"), + (0x24E7, "M", "x"), + (0x24E8, "M", "y"), + (0x24E9, "M", "z"), + (0x24EA, "M", "0"), + (0x24EB, "V"), + (0x2A0C, "M", "∫∫∫∫"), + (0x2A0D, "V"), + (0x2A74, "3", "::="), + (0x2A75, "3", "=="), + (0x2A76, "3", "==="), + (0x2A77, "V"), + (0x2ADC, "M", "⫝̸"), + (0x2ADD, "V"), + (0x2B74, "X"), + (0x2B76, "V"), + (0x2B96, "X"), + (0x2B97, "V"), + (0x2C00, "M", "ⰰ"), + (0x2C01, "M", "ⰱ"), + (0x2C02, "M", "ⰲ"), + (0x2C03, "M", "ⰳ"), + (0x2C04, "M", "ⰴ"), + (0x2C05, "M", "ⰵ"), + (0x2C06, "M", "ⰶ"), + (0x2C07, "M", "ⰷ"), + (0x2C08, "M", "ⰸ"), + (0x2C09, "M", "ⰹ"), + (0x2C0A, "M", "ⰺ"), + (0x2C0B, "M", "ⰻ"), + (0x2C0C, "M", "ⰼ"), + (0x2C0D, "M", "ⰽ"), + (0x2C0E, "M", "ⰾ"), + (0x2C0F, "M", "ⰿ"), + (0x2C10, "M", "ⱀ"), + (0x2C11, "M", "ⱁ"), + (0x2C12, "M", "ⱂ"), + (0x2C13, "M", "ⱃ"), + (0x2C14, "M", "ⱄ"), + (0x2C15, "M", "ⱅ"), + (0x2C16, "M", "ⱆ"), + (0x2C17, "M", "ⱇ"), + (0x2C18, "M", "ⱈ"), + (0x2C19, "M", "ⱉ"), + (0x2C1A, "M", "ⱊ"), + (0x2C1B, "M", "ⱋ"), + (0x2C1C, "M", "ⱌ"), + (0x2C1D, "M", "ⱍ"), + (0x2C1E, "M", "ⱎ"), + (0x2C1F, "M", "ⱏ"), + (0x2C20, "M", "ⱐ"), + (0x2C21, "M", "ⱑ"), + (0x2C22, "M", "ⱒ"), + (0x2C23, "M", "ⱓ"), + (0x2C24, "M", "ⱔ"), + (0x2C25, "M", "ⱕ"), + (0x2C26, "M", "ⱖ"), + (0x2C27, "M", "ⱗ"), + (0x2C28, "M", "ⱘ"), + (0x2C29, "M", "ⱙ"), + (0x2C2A, "M", "ⱚ"), + (0x2C2B, "M", "ⱛ"), + (0x2C2C, "M", "ⱜ"), + ] + + +def _seg_25() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2C2D, "M", "ⱝ"), + (0x2C2E, "M", "ⱞ"), + (0x2C2F, "M", "ⱟ"), + (0x2C30, "V"), + (0x2C60, "M", "ⱡ"), + (0x2C61, "V"), + (0x2C62, "M", "ɫ"), + (0x2C63, "M", "ᵽ"), + (0x2C64, "M", "ɽ"), + (0x2C65, "V"), + (0x2C67, "M", "ⱨ"), + (0x2C68, "V"), + (0x2C69, "M", "ⱪ"), + (0x2C6A, "V"), + (0x2C6B, "M", "ⱬ"), + (0x2C6C, "V"), + (0x2C6D, "M", "ɑ"), + (0x2C6E, "M", "ɱ"), + (0x2C6F, "M", "ɐ"), + (0x2C70, "M", "ɒ"), + (0x2C71, "V"), + (0x2C72, "M", "ⱳ"), + (0x2C73, "V"), + (0x2C75, "M", "ⱶ"), + (0x2C76, "V"), + (0x2C7C, "M", "j"), + (0x2C7D, "M", "v"), + (0x2C7E, "M", "ȿ"), + (0x2C7F, "M", "ɀ"), + (0x2C80, "M", "ⲁ"), + (0x2C81, "V"), + (0x2C82, "M", "ⲃ"), + (0x2C83, "V"), + (0x2C84, "M", "ⲅ"), + (0x2C85, "V"), + (0x2C86, "M", "ⲇ"), + (0x2C87, "V"), + (0x2C88, "M", "ⲉ"), + (0x2C89, "V"), + (0x2C8A, "M", "ⲋ"), + (0x2C8B, "V"), + (0x2C8C, "M", "ⲍ"), + (0x2C8D, "V"), + (0x2C8E, "M", "ⲏ"), + (0x2C8F, "V"), + (0x2C90, "M", "ⲑ"), + (0x2C91, "V"), + (0x2C92, "M", "ⲓ"), + (0x2C93, "V"), + (0x2C94, "M", "ⲕ"), + (0x2C95, "V"), + (0x2C96, "M", "ⲗ"), + (0x2C97, "V"), + (0x2C98, "M", "ⲙ"), + (0x2C99, "V"), + (0x2C9A, "M", "ⲛ"), + (0x2C9B, "V"), + (0x2C9C, "M", "ⲝ"), + (0x2C9D, "V"), + (0x2C9E, "M", "ⲟ"), + (0x2C9F, "V"), + (0x2CA0, "M", "ⲡ"), + (0x2CA1, "V"), + (0x2CA2, "M", "ⲣ"), + (0x2CA3, "V"), + (0x2CA4, "M", "ⲥ"), + (0x2CA5, "V"), + (0x2CA6, "M", "ⲧ"), + (0x2CA7, "V"), + (0x2CA8, "M", "ⲩ"), + (0x2CA9, "V"), + (0x2CAA, "M", "ⲫ"), + (0x2CAB, "V"), + (0x2CAC, "M", "ⲭ"), + (0x2CAD, "V"), + (0x2CAE, "M", "ⲯ"), + (0x2CAF, "V"), + (0x2CB0, "M", "ⲱ"), + (0x2CB1, "V"), + (0x2CB2, "M", "ⲳ"), + (0x2CB3, "V"), + (0x2CB4, "M", "ⲵ"), + (0x2CB5, "V"), + (0x2CB6, "M", "ⲷ"), + (0x2CB7, "V"), + (0x2CB8, "M", "ⲹ"), + (0x2CB9, "V"), + (0x2CBA, "M", "ⲻ"), + (0x2CBB, "V"), + (0x2CBC, "M", "ⲽ"), + (0x2CBD, "V"), + (0x2CBE, "M", "ⲿ"), + (0x2CBF, "V"), + (0x2CC0, "M", "ⳁ"), + (0x2CC1, "V"), + (0x2CC2, "M", "ⳃ"), + (0x2CC3, "V"), + (0x2CC4, "M", "ⳅ"), + (0x2CC5, "V"), + (0x2CC6, "M", "ⳇ"), + ] + + +def _seg_26() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2CC7, "V"), + (0x2CC8, "M", "ⳉ"), + (0x2CC9, "V"), + (0x2CCA, "M", "ⳋ"), + (0x2CCB, "V"), + (0x2CCC, "M", "ⳍ"), + (0x2CCD, "V"), + (0x2CCE, "M", "ⳏ"), + (0x2CCF, "V"), + (0x2CD0, "M", "ⳑ"), + (0x2CD1, "V"), + (0x2CD2, "M", "ⳓ"), + (0x2CD3, "V"), + (0x2CD4, "M", "ⳕ"), + (0x2CD5, "V"), + (0x2CD6, "M", "ⳗ"), + (0x2CD7, "V"), + (0x2CD8, "M", "ⳙ"), + (0x2CD9, "V"), + (0x2CDA, "M", "ⳛ"), + (0x2CDB, "V"), + (0x2CDC, "M", "ⳝ"), + (0x2CDD, "V"), + (0x2CDE, "M", "ⳟ"), + (0x2CDF, "V"), + (0x2CE0, "M", "ⳡ"), + (0x2CE1, "V"), + (0x2CE2, "M", "ⳣ"), + (0x2CE3, "V"), + (0x2CEB, "M", "ⳬ"), + (0x2CEC, "V"), + (0x2CED, "M", "ⳮ"), + (0x2CEE, "V"), + (0x2CF2, "M", "ⳳ"), + (0x2CF3, "V"), + (0x2CF4, "X"), + (0x2CF9, "V"), + (0x2D26, "X"), + (0x2D27, "V"), + (0x2D28, "X"), + (0x2D2D, "V"), + (0x2D2E, "X"), + (0x2D30, "V"), + (0x2D68, "X"), + (0x2D6F, "M", "ⵡ"), + (0x2D70, "V"), + (0x2D71, "X"), + (0x2D7F, "V"), + (0x2D97, "X"), + (0x2DA0, "V"), + (0x2DA7, "X"), + (0x2DA8, "V"), + (0x2DAF, "X"), + (0x2DB0, "V"), + (0x2DB7, "X"), + (0x2DB8, "V"), + (0x2DBF, "X"), + (0x2DC0, "V"), + (0x2DC7, "X"), + (0x2DC8, "V"), + (0x2DCF, "X"), + (0x2DD0, "V"), + (0x2DD7, "X"), + (0x2DD8, "V"), + (0x2DDF, "X"), + (0x2DE0, "V"), + (0x2E5E, "X"), + (0x2E80, "V"), + (0x2E9A, "X"), + (0x2E9B, "V"), + (0x2E9F, "M", "母"), + (0x2EA0, "V"), + (0x2EF3, "M", "龟"), + (0x2EF4, "X"), + (0x2F00, "M", "一"), + (0x2F01, "M", "丨"), + (0x2F02, "M", "丶"), + (0x2F03, "M", "丿"), + (0x2F04, "M", "乙"), + (0x2F05, "M", "亅"), + (0x2F06, "M", "二"), + (0x2F07, "M", "亠"), + (0x2F08, "M", "人"), + (0x2F09, "M", "儿"), + (0x2F0A, "M", "入"), + (0x2F0B, "M", "八"), + (0x2F0C, "M", "冂"), + (0x2F0D, "M", "冖"), + (0x2F0E, "M", "冫"), + (0x2F0F, "M", "几"), + (0x2F10, "M", "凵"), + (0x2F11, "M", "刀"), + (0x2F12, "M", "力"), + (0x2F13, "M", "勹"), + (0x2F14, "M", "匕"), + (0x2F15, "M", "匚"), + (0x2F16, "M", "匸"), + (0x2F17, "M", "十"), + (0x2F18, "M", "卜"), + (0x2F19, "M", "卩"), + ] + + +def _seg_27() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F1A, "M", "厂"), + (0x2F1B, "M", "厶"), + (0x2F1C, "M", "又"), + (0x2F1D, "M", "口"), + (0x2F1E, "M", "囗"), + (0x2F1F, "M", "土"), + (0x2F20, "M", "士"), + (0x2F21, "M", "夂"), + (0x2F22, "M", "夊"), + (0x2F23, "M", "夕"), + (0x2F24, "M", "大"), + (0x2F25, "M", "女"), + (0x2F26, "M", "子"), + (0x2F27, "M", "宀"), + (0x2F28, "M", "寸"), + (0x2F29, "M", "小"), + (0x2F2A, "M", "尢"), + (0x2F2B, "M", "尸"), + (0x2F2C, "M", "屮"), + (0x2F2D, "M", "山"), + (0x2F2E, "M", "巛"), + (0x2F2F, "M", "工"), + (0x2F30, "M", "己"), + (0x2F31, "M", "巾"), + (0x2F32, "M", "干"), + (0x2F33, "M", "幺"), + (0x2F34, "M", "广"), + (0x2F35, "M", "廴"), + (0x2F36, "M", "廾"), + (0x2F37, "M", "弋"), + (0x2F38, "M", "弓"), + (0x2F39, "M", "彐"), + (0x2F3A, "M", "彡"), + (0x2F3B, "M", "彳"), + (0x2F3C, "M", "心"), + (0x2F3D, "M", "戈"), + (0x2F3E, "M", "戶"), + (0x2F3F, "M", "手"), + (0x2F40, "M", "支"), + (0x2F41, "M", "攴"), + (0x2F42, "M", "文"), + (0x2F43, "M", "斗"), + (0x2F44, "M", "斤"), + (0x2F45, "M", "方"), + (0x2F46, "M", "无"), + (0x2F47, "M", "日"), + (0x2F48, "M", "曰"), + (0x2F49, "M", "月"), + (0x2F4A, "M", "木"), + (0x2F4B, "M", "欠"), + (0x2F4C, "M", "止"), + (0x2F4D, "M", "歹"), + (0x2F4E, "M", "殳"), + (0x2F4F, "M", "毋"), + (0x2F50, "M", "比"), + (0x2F51, "M", "毛"), + (0x2F52, "M", "氏"), + (0x2F53, "M", "气"), + (0x2F54, "M", "水"), + (0x2F55, "M", "火"), + (0x2F56, "M", "爪"), + (0x2F57, "M", "父"), + (0x2F58, "M", "爻"), + (0x2F59, "M", "爿"), + (0x2F5A, "M", "片"), + (0x2F5B, "M", "牙"), + (0x2F5C, "M", "牛"), + (0x2F5D, "M", "犬"), + (0x2F5E, "M", "玄"), + (0x2F5F, "M", "玉"), + (0x2F60, "M", "瓜"), + (0x2F61, "M", "瓦"), + (0x2F62, "M", "甘"), + (0x2F63, "M", "生"), + (0x2F64, "M", "用"), + (0x2F65, "M", "田"), + (0x2F66, "M", "疋"), + (0x2F67, "M", "疒"), + (0x2F68, "M", "癶"), + (0x2F69, "M", "白"), + (0x2F6A, "M", "皮"), + (0x2F6B, "M", "皿"), + (0x2F6C, "M", "目"), + (0x2F6D, "M", "矛"), + (0x2F6E, "M", "矢"), + (0x2F6F, "M", "石"), + (0x2F70, "M", "示"), + (0x2F71, "M", "禸"), + (0x2F72, "M", "禾"), + (0x2F73, "M", "穴"), + (0x2F74, "M", "立"), + (0x2F75, "M", "竹"), + (0x2F76, "M", "米"), + (0x2F77, "M", "糸"), + (0x2F78, "M", "缶"), + (0x2F79, "M", "网"), + (0x2F7A, "M", "羊"), + (0x2F7B, "M", "羽"), + (0x2F7C, "M", "老"), + (0x2F7D, "M", "而"), + ] + + +def _seg_28() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F7E, "M", "耒"), + (0x2F7F, "M", "耳"), + (0x2F80, "M", "聿"), + (0x2F81, "M", "肉"), + (0x2F82, "M", "臣"), + (0x2F83, "M", "自"), + (0x2F84, "M", "至"), + (0x2F85, "M", "臼"), + (0x2F86, "M", "舌"), + (0x2F87, "M", "舛"), + (0x2F88, "M", "舟"), + (0x2F89, "M", "艮"), + (0x2F8A, "M", "色"), + (0x2F8B, "M", "艸"), + (0x2F8C, "M", "虍"), + (0x2F8D, "M", "虫"), + (0x2F8E, "M", "血"), + (0x2F8F, "M", "行"), + (0x2F90, "M", "衣"), + (0x2F91, "M", "襾"), + (0x2F92, "M", "見"), + (0x2F93, "M", "角"), + (0x2F94, "M", "言"), + (0x2F95, "M", "谷"), + (0x2F96, "M", "豆"), + (0x2F97, "M", "豕"), + (0x2F98, "M", "豸"), + (0x2F99, "M", "貝"), + (0x2F9A, "M", "赤"), + (0x2F9B, "M", "走"), + (0x2F9C, "M", "足"), + (0x2F9D, "M", "身"), + (0x2F9E, "M", "車"), + (0x2F9F, "M", "辛"), + (0x2FA0, "M", "辰"), + (0x2FA1, "M", "辵"), + (0x2FA2, "M", "邑"), + (0x2FA3, "M", "酉"), + (0x2FA4, "M", "釆"), + (0x2FA5, "M", "里"), + (0x2FA6, "M", "金"), + (0x2FA7, "M", "長"), + (0x2FA8, "M", "門"), + (0x2FA9, "M", "阜"), + (0x2FAA, "M", "隶"), + (0x2FAB, "M", "隹"), + (0x2FAC, "M", "雨"), + (0x2FAD, "M", "靑"), + (0x2FAE, "M", "非"), + (0x2FAF, "M", "面"), + (0x2FB0, "M", "革"), + (0x2FB1, "M", "韋"), + (0x2FB2, "M", "韭"), + (0x2FB3, "M", "音"), + (0x2FB4, "M", "頁"), + (0x2FB5, "M", "風"), + (0x2FB6, "M", "飛"), + (0x2FB7, "M", "食"), + (0x2FB8, "M", "首"), + (0x2FB9, "M", "香"), + (0x2FBA, "M", "馬"), + (0x2FBB, "M", "骨"), + (0x2FBC, "M", "高"), + (0x2FBD, "M", "髟"), + (0x2FBE, "M", "鬥"), + (0x2FBF, "M", "鬯"), + (0x2FC0, "M", "鬲"), + (0x2FC1, "M", "鬼"), + (0x2FC2, "M", "魚"), + (0x2FC3, "M", "鳥"), + (0x2FC4, "M", "鹵"), + (0x2FC5, "M", "鹿"), + (0x2FC6, "M", "麥"), + (0x2FC7, "M", "麻"), + (0x2FC8, "M", "黃"), + (0x2FC9, "M", "黍"), + (0x2FCA, "M", "黑"), + (0x2FCB, "M", "黹"), + (0x2FCC, "M", "黽"), + (0x2FCD, "M", "鼎"), + (0x2FCE, "M", "鼓"), + (0x2FCF, "M", "鼠"), + (0x2FD0, "M", "鼻"), + (0x2FD1, "M", "齊"), + (0x2FD2, "M", "齒"), + (0x2FD3, "M", "龍"), + (0x2FD4, "M", "龜"), + (0x2FD5, "M", "龠"), + (0x2FD6, "X"), + (0x3000, "3", " "), + (0x3001, "V"), + (0x3002, "M", "."), + (0x3003, "V"), + (0x3036, "M", "〒"), + (0x3037, "V"), + (0x3038, "M", "十"), + (0x3039, "M", "卄"), + (0x303A, "M", "卅"), + (0x303B, "V"), + (0x3040, "X"), + ] + + +def _seg_29() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x3041, "V"), + (0x3097, "X"), + (0x3099, "V"), + (0x309B, "3", " ゙"), + (0x309C, "3", " ゚"), + (0x309D, "V"), + (0x309F, "M", "より"), + (0x30A0, "V"), + (0x30FF, "M", "コト"), + (0x3100, "X"), + (0x3105, "V"), + (0x3130, "X"), + (0x3131, "M", "ᄀ"), + (0x3132, "M", "ᄁ"), + (0x3133, "M", "ᆪ"), + (0x3134, "M", "ᄂ"), + (0x3135, "M", "ᆬ"), + (0x3136, "M", "ᆭ"), + (0x3137, "M", "ᄃ"), + (0x3138, "M", "ᄄ"), + (0x3139, "M", "ᄅ"), + (0x313A, "M", "ᆰ"), + (0x313B, "M", "ᆱ"), + (0x313C, "M", "ᆲ"), + (0x313D, "M", "ᆳ"), + (0x313E, "M", "ᆴ"), + (0x313F, "M", "ᆵ"), + (0x3140, "M", "ᄚ"), + (0x3141, "M", "ᄆ"), + (0x3142, "M", "ᄇ"), + (0x3143, "M", "ᄈ"), + (0x3144, "M", "ᄡ"), + (0x3145, "M", "ᄉ"), + (0x3146, "M", "ᄊ"), + (0x3147, "M", "ᄋ"), + (0x3148, "M", "ᄌ"), + (0x3149, "M", "ᄍ"), + (0x314A, "M", "ᄎ"), + (0x314B, "M", "ᄏ"), + (0x314C, "M", "ᄐ"), + (0x314D, "M", "ᄑ"), + (0x314E, "M", "ᄒ"), + (0x314F, "M", "ᅡ"), + (0x3150, "M", "ᅢ"), + (0x3151, "M", "ᅣ"), + (0x3152, "M", "ᅤ"), + (0x3153, "M", "ᅥ"), + (0x3154, "M", "ᅦ"), + (0x3155, "M", "ᅧ"), + (0x3156, "M", "ᅨ"), + (0x3157, "M", "ᅩ"), + (0x3158, "M", "ᅪ"), + (0x3159, "M", "ᅫ"), + (0x315A, "M", "ᅬ"), + (0x315B, "M", "ᅭ"), + (0x315C, "M", "ᅮ"), + (0x315D, "M", "ᅯ"), + (0x315E, "M", "ᅰ"), + (0x315F, "M", "ᅱ"), + (0x3160, "M", "ᅲ"), + (0x3161, "M", "ᅳ"), + (0x3162, "M", "ᅴ"), + (0x3163, "M", "ᅵ"), + (0x3164, "X"), + (0x3165, "M", "ᄔ"), + (0x3166, "M", "ᄕ"), + (0x3167, "M", "ᇇ"), + (0x3168, "M", "ᇈ"), + (0x3169, "M", "ᇌ"), + (0x316A, "M", "ᇎ"), + (0x316B, "M", "ᇓ"), + (0x316C, "M", "ᇗ"), + (0x316D, "M", "ᇙ"), + (0x316E, "M", "ᄜ"), + (0x316F, "M", "ᇝ"), + (0x3170, "M", "ᇟ"), + (0x3171, "M", "ᄝ"), + (0x3172, "M", "ᄞ"), + (0x3173, "M", "ᄠ"), + (0x3174, "M", "ᄢ"), + (0x3175, "M", "ᄣ"), + (0x3176, "M", "ᄧ"), + (0x3177, "M", "ᄩ"), + (0x3178, "M", "ᄫ"), + (0x3179, "M", "ᄬ"), + (0x317A, "M", "ᄭ"), + (0x317B, "M", "ᄮ"), + (0x317C, "M", "ᄯ"), + (0x317D, "M", "ᄲ"), + (0x317E, "M", "ᄶ"), + (0x317F, "M", "ᅀ"), + (0x3180, "M", "ᅇ"), + (0x3181, "M", "ᅌ"), + (0x3182, "M", "ᇱ"), + (0x3183, "M", "ᇲ"), + (0x3184, "M", "ᅗ"), + (0x3185, "M", "ᅘ"), + (0x3186, "M", "ᅙ"), + (0x3187, "M", "ᆄ"), + (0x3188, "M", "ᆅ"), + ] + + +def _seg_30() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x3189, "M", "ᆈ"), + (0x318A, "M", "ᆑ"), + (0x318B, "M", "ᆒ"), + (0x318C, "M", "ᆔ"), + (0x318D, "M", "ᆞ"), + (0x318E, "M", "ᆡ"), + (0x318F, "X"), + (0x3190, "V"), + (0x3192, "M", "一"), + (0x3193, "M", "二"), + (0x3194, "M", "三"), + (0x3195, "M", "四"), + (0x3196, "M", "上"), + (0x3197, "M", "中"), + (0x3198, "M", "下"), + (0x3199, "M", "甲"), + (0x319A, "M", "乙"), + (0x319B, "M", "丙"), + (0x319C, "M", "丁"), + (0x319D, "M", "天"), + (0x319E, "M", "地"), + (0x319F, "M", "人"), + (0x31A0, "V"), + (0x31E4, "X"), + (0x31F0, "V"), + (0x3200, "3", "(ᄀ)"), + (0x3201, "3", "(ᄂ)"), + (0x3202, "3", "(ᄃ)"), + (0x3203, "3", "(ᄅ)"), + (0x3204, "3", "(ᄆ)"), + (0x3205, "3", "(ᄇ)"), + (0x3206, "3", "(ᄉ)"), + (0x3207, "3", "(ᄋ)"), + (0x3208, "3", "(ᄌ)"), + (0x3209, "3", "(ᄎ)"), + (0x320A, "3", "(ᄏ)"), + (0x320B, "3", "(ᄐ)"), + (0x320C, "3", "(ᄑ)"), + (0x320D, "3", "(ᄒ)"), + (0x320E, "3", "(가)"), + (0x320F, "3", "(나)"), + (0x3210, "3", "(다)"), + (0x3211, "3", "(라)"), + (0x3212, "3", "(마)"), + (0x3213, "3", "(바)"), + (0x3214, "3", "(사)"), + (0x3215, "3", "(아)"), + (0x3216, "3", "(자)"), + (0x3217, "3", "(차)"), + (0x3218, "3", "(카)"), + (0x3219, "3", "(타)"), + (0x321A, "3", "(파)"), + (0x321B, "3", "(하)"), + (0x321C, "3", "(주)"), + (0x321D, "3", "(오전)"), + (0x321E, "3", "(오후)"), + (0x321F, "X"), + (0x3220, "3", "(一)"), + (0x3221, "3", "(二)"), + (0x3222, "3", "(三)"), + (0x3223, "3", "(四)"), + (0x3224, "3", "(五)"), + (0x3225, "3", "(六)"), + (0x3226, "3", "(七)"), + (0x3227, "3", "(八)"), + (0x3228, "3", "(九)"), + (0x3229, "3", "(十)"), + (0x322A, "3", "(月)"), + (0x322B, "3", "(火)"), + (0x322C, "3", "(水)"), + (0x322D, "3", "(木)"), + (0x322E, "3", "(金)"), + (0x322F, "3", "(土)"), + (0x3230, "3", "(日)"), + (0x3231, "3", "(株)"), + (0x3232, "3", "(有)"), + (0x3233, "3", "(社)"), + (0x3234, "3", "(名)"), + (0x3235, "3", "(特)"), + (0x3236, "3", "(財)"), + (0x3237, "3", "(祝)"), + (0x3238, "3", "(労)"), + (0x3239, "3", "(代)"), + (0x323A, "3", "(呼)"), + (0x323B, "3", "(学)"), + (0x323C, "3", "(監)"), + (0x323D, "3", "(企)"), + (0x323E, "3", "(資)"), + (0x323F, "3", "(協)"), + (0x3240, "3", "(祭)"), + (0x3241, "3", "(休)"), + (0x3242, "3", "(自)"), + (0x3243, "3", "(至)"), + (0x3244, "M", "問"), + (0x3245, "M", "幼"), + (0x3246, "M", "文"), + (0x3247, "M", "箏"), + (0x3248, "V"), + (0x3250, "M", "pte"), + (0x3251, "M", "21"), + ] + + +def _seg_31() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x3252, "M", "22"), + (0x3253, "M", "23"), + (0x3254, "M", "24"), + (0x3255, "M", "25"), + (0x3256, "M", "26"), + (0x3257, "M", "27"), + (0x3258, "M", "28"), + (0x3259, "M", "29"), + (0x325A, "M", "30"), + (0x325B, "M", "31"), + (0x325C, "M", "32"), + (0x325D, "M", "33"), + (0x325E, "M", "34"), + (0x325F, "M", "35"), + (0x3260, "M", "ᄀ"), + (0x3261, "M", "ᄂ"), + (0x3262, "M", "ᄃ"), + (0x3263, "M", "ᄅ"), + (0x3264, "M", "ᄆ"), + (0x3265, "M", "ᄇ"), + (0x3266, "M", "ᄉ"), + (0x3267, "M", "ᄋ"), + (0x3268, "M", "ᄌ"), + (0x3269, "M", "ᄎ"), + (0x326A, "M", "ᄏ"), + (0x326B, "M", "ᄐ"), + (0x326C, "M", "ᄑ"), + (0x326D, "M", "ᄒ"), + (0x326E, "M", "가"), + (0x326F, "M", "나"), + (0x3270, "M", "다"), + (0x3271, "M", "라"), + (0x3272, "M", "마"), + (0x3273, "M", "바"), + (0x3274, "M", "사"), + (0x3275, "M", "아"), + (0x3276, "M", "자"), + (0x3277, "M", "차"), + (0x3278, "M", "카"), + (0x3279, "M", "타"), + (0x327A, "M", "파"), + (0x327B, "M", "하"), + (0x327C, "M", "참고"), + (0x327D, "M", "주의"), + (0x327E, "M", "우"), + (0x327F, "V"), + (0x3280, "M", "一"), + (0x3281, "M", "二"), + (0x3282, "M", "三"), + (0x3283, "M", "四"), + (0x3284, "M", "五"), + (0x3285, "M", "六"), + (0x3286, "M", "七"), + (0x3287, "M", "八"), + (0x3288, "M", "九"), + (0x3289, "M", "十"), + (0x328A, "M", "月"), + (0x328B, "M", "火"), + (0x328C, "M", "水"), + (0x328D, "M", "木"), + (0x328E, "M", "金"), + (0x328F, "M", "土"), + (0x3290, "M", "日"), + (0x3291, "M", "株"), + (0x3292, "M", "有"), + (0x3293, "M", "社"), + (0x3294, "M", "名"), + (0x3295, "M", "特"), + (0x3296, "M", "財"), + (0x3297, "M", "祝"), + (0x3298, "M", "労"), + (0x3299, "M", "秘"), + (0x329A, "M", "男"), + (0x329B, "M", "女"), + (0x329C, "M", "適"), + (0x329D, "M", "優"), + (0x329E, "M", "印"), + (0x329F, "M", "注"), + (0x32A0, "M", "項"), + (0x32A1, "M", "休"), + (0x32A2, "M", "写"), + (0x32A3, "M", "正"), + (0x32A4, "M", "上"), + (0x32A5, "M", "中"), + (0x32A6, "M", "下"), + (0x32A7, "M", "左"), + (0x32A8, "M", "右"), + (0x32A9, "M", "医"), + (0x32AA, "M", "宗"), + (0x32AB, "M", "学"), + (0x32AC, "M", "監"), + (0x32AD, "M", "企"), + (0x32AE, "M", "資"), + (0x32AF, "M", "協"), + (0x32B0, "M", "夜"), + (0x32B1, "M", "36"), + (0x32B2, "M", "37"), + (0x32B3, "M", "38"), + (0x32B4, "M", "39"), + (0x32B5, "M", "40"), + ] + + +def _seg_32() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x32B6, "M", "41"), + (0x32B7, "M", "42"), + (0x32B8, "M", "43"), + (0x32B9, "M", "44"), + (0x32BA, "M", "45"), + (0x32BB, "M", "46"), + (0x32BC, "M", "47"), + (0x32BD, "M", "48"), + (0x32BE, "M", "49"), + (0x32BF, "M", "50"), + (0x32C0, "M", "1月"), + (0x32C1, "M", "2月"), + (0x32C2, "M", "3月"), + (0x32C3, "M", "4月"), + (0x32C4, "M", "5月"), + (0x32C5, "M", "6月"), + (0x32C6, "M", "7月"), + (0x32C7, "M", "8月"), + (0x32C8, "M", "9月"), + (0x32C9, "M", "10月"), + (0x32CA, "M", "11月"), + (0x32CB, "M", "12月"), + (0x32CC, "M", "hg"), + (0x32CD, "M", "erg"), + (0x32CE, "M", "ev"), + (0x32CF, "M", "ltd"), + (0x32D0, "M", "ア"), + (0x32D1, "M", "イ"), + (0x32D2, "M", "ウ"), + (0x32D3, "M", "エ"), + (0x32D4, "M", "オ"), + (0x32D5, "M", "カ"), + (0x32D6, "M", "キ"), + (0x32D7, "M", "ク"), + (0x32D8, "M", "ケ"), + (0x32D9, "M", "コ"), + (0x32DA, "M", "サ"), + (0x32DB, "M", "シ"), + (0x32DC, "M", "ス"), + (0x32DD, "M", "セ"), + (0x32DE, "M", "ソ"), + (0x32DF, "M", "タ"), + (0x32E0, "M", "チ"), + (0x32E1, "M", "ツ"), + (0x32E2, "M", "テ"), + (0x32E3, "M", "ト"), + (0x32E4, "M", "ナ"), + (0x32E5, "M", "ニ"), + (0x32E6, "M", "ヌ"), + (0x32E7, "M", "ネ"), + (0x32E8, "M", "ノ"), + (0x32E9, "M", "ハ"), + (0x32EA, "M", "ヒ"), + (0x32EB, "M", "フ"), + (0x32EC, "M", "ヘ"), + (0x32ED, "M", "ホ"), + (0x32EE, "M", "マ"), + (0x32EF, "M", "ミ"), + (0x32F0, "M", "ム"), + (0x32F1, "M", "メ"), + (0x32F2, "M", "モ"), + (0x32F3, "M", "ヤ"), + (0x32F4, "M", "ユ"), + (0x32F5, "M", "ヨ"), + (0x32F6, "M", "ラ"), + (0x32F7, "M", "リ"), + (0x32F8, "M", "ル"), + (0x32F9, "M", "レ"), + (0x32FA, "M", "ロ"), + (0x32FB, "M", "ワ"), + (0x32FC, "M", "ヰ"), + (0x32FD, "M", "ヱ"), + (0x32FE, "M", "ヲ"), + (0x32FF, "M", "令和"), + (0x3300, "M", "アパート"), + (0x3301, "M", "アルファ"), + (0x3302, "M", "アンペア"), + (0x3303, "M", "アール"), + (0x3304, "M", "イニング"), + (0x3305, "M", "インチ"), + (0x3306, "M", "ウォン"), + (0x3307, "M", "エスクード"), + (0x3308, "M", "エーカー"), + (0x3309, "M", "オンス"), + (0x330A, "M", "オーム"), + (0x330B, "M", "カイリ"), + (0x330C, "M", "カラット"), + (0x330D, "M", "カロリー"), + (0x330E, "M", "ガロン"), + (0x330F, "M", "ガンマ"), + (0x3310, "M", "ギガ"), + (0x3311, "M", "ギニー"), + (0x3312, "M", "キュリー"), + (0x3313, "M", "ギルダー"), + (0x3314, "M", "キロ"), + (0x3315, "M", "キログラム"), + (0x3316, "M", "キロメートル"), + (0x3317, "M", "キロワット"), + (0x3318, "M", "グラム"), + (0x3319, "M", "グラムトン"), + ] + + +def _seg_33() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x331A, "M", "クルゼイロ"), + (0x331B, "M", "クローネ"), + (0x331C, "M", "ケース"), + (0x331D, "M", "コルナ"), + (0x331E, "M", "コーポ"), + (0x331F, "M", "サイクル"), + (0x3320, "M", "サンチーム"), + (0x3321, "M", "シリング"), + (0x3322, "M", "センチ"), + (0x3323, "M", "セント"), + (0x3324, "M", "ダース"), + (0x3325, "M", "デシ"), + (0x3326, "M", "ドル"), + (0x3327, "M", "トン"), + (0x3328, "M", "ナノ"), + (0x3329, "M", "ノット"), + (0x332A, "M", "ハイツ"), + (0x332B, "M", "パーセント"), + (0x332C, "M", "パーツ"), + (0x332D, "M", "バーレル"), + (0x332E, "M", "ピアストル"), + (0x332F, "M", "ピクル"), + (0x3330, "M", "ピコ"), + (0x3331, "M", "ビル"), + (0x3332, "M", "ファラッド"), + (0x3333, "M", "フィート"), + (0x3334, "M", "ブッシェル"), + (0x3335, "M", "フラン"), + (0x3336, "M", "ヘクタール"), + (0x3337, "M", "ペソ"), + (0x3338, "M", "ペニヒ"), + (0x3339, "M", "ヘルツ"), + (0x333A, "M", "ペンス"), + (0x333B, "M", "ページ"), + (0x333C, "M", "ベータ"), + (0x333D, "M", "ポイント"), + (0x333E, "M", "ボルト"), + (0x333F, "M", "ホン"), + (0x3340, "M", "ポンド"), + (0x3341, "M", "ホール"), + (0x3342, "M", "ホーン"), + (0x3343, "M", "マイクロ"), + (0x3344, "M", "マイル"), + (0x3345, "M", "マッハ"), + (0x3346, "M", "マルク"), + (0x3347, "M", "マンション"), + (0x3348, "M", "ミクロン"), + (0x3349, "M", "ミリ"), + (0x334A, "M", "ミリバール"), + (0x334B, "M", "メガ"), + (0x334C, "M", "メガトン"), + (0x334D, "M", "メートル"), + (0x334E, "M", "ヤード"), + (0x334F, "M", "ヤール"), + (0x3350, "M", "ユアン"), + (0x3351, "M", "リットル"), + (0x3352, "M", "リラ"), + (0x3353, "M", "ルピー"), + (0x3354, "M", "ルーブル"), + (0x3355, "M", "レム"), + (0x3356, "M", "レントゲン"), + (0x3357, "M", "ワット"), + (0x3358, "M", "0点"), + (0x3359, "M", "1点"), + (0x335A, "M", "2点"), + (0x335B, "M", "3点"), + (0x335C, "M", "4点"), + (0x335D, "M", "5点"), + (0x335E, "M", "6点"), + (0x335F, "M", "7点"), + (0x3360, "M", "8点"), + (0x3361, "M", "9点"), + (0x3362, "M", "10点"), + (0x3363, "M", "11点"), + (0x3364, "M", "12点"), + (0x3365, "M", "13点"), + (0x3366, "M", "14点"), + (0x3367, "M", "15点"), + (0x3368, "M", "16点"), + (0x3369, "M", "17点"), + (0x336A, "M", "18点"), + (0x336B, "M", "19点"), + (0x336C, "M", "20点"), + (0x336D, "M", "21点"), + (0x336E, "M", "22点"), + (0x336F, "M", "23点"), + (0x3370, "M", "24点"), + (0x3371, "M", "hpa"), + (0x3372, "M", "da"), + (0x3373, "M", "au"), + (0x3374, "M", "bar"), + (0x3375, "M", "ov"), + (0x3376, "M", "pc"), + (0x3377, "M", "dm"), + (0x3378, "M", "dm2"), + (0x3379, "M", "dm3"), + (0x337A, "M", "iu"), + (0x337B, "M", "平成"), + (0x337C, "M", "昭和"), + (0x337D, "M", "大正"), + ] + + +def _seg_34() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x337E, "M", "明治"), + (0x337F, "M", "株式会社"), + (0x3380, "M", "pa"), + (0x3381, "M", "na"), + (0x3382, "M", "μa"), + (0x3383, "M", "ma"), + (0x3384, "M", "ka"), + (0x3385, "M", "kb"), + (0x3386, "M", "mb"), + (0x3387, "M", "gb"), + (0x3388, "M", "cal"), + (0x3389, "M", "kcal"), + (0x338A, "M", "pf"), + (0x338B, "M", "nf"), + (0x338C, "M", "μf"), + (0x338D, "M", "μg"), + (0x338E, "M", "mg"), + (0x338F, "M", "kg"), + (0x3390, "M", "hz"), + (0x3391, "M", "khz"), + (0x3392, "M", "mhz"), + (0x3393, "M", "ghz"), + (0x3394, "M", "thz"), + (0x3395, "M", "μl"), + (0x3396, "M", "ml"), + (0x3397, "M", "dl"), + (0x3398, "M", "kl"), + (0x3399, "M", "fm"), + (0x339A, "M", "nm"), + (0x339B, "M", "μm"), + (0x339C, "M", "mm"), + (0x339D, "M", "cm"), + (0x339E, "M", "km"), + (0x339F, "M", "mm2"), + (0x33A0, "M", "cm2"), + (0x33A1, "M", "m2"), + (0x33A2, "M", "km2"), + (0x33A3, "M", "mm3"), + (0x33A4, "M", "cm3"), + (0x33A5, "M", "m3"), + (0x33A6, "M", "km3"), + (0x33A7, "M", "m∕s"), + (0x33A8, "M", "m∕s2"), + (0x33A9, "M", "pa"), + (0x33AA, "M", "kpa"), + (0x33AB, "M", "mpa"), + (0x33AC, "M", "gpa"), + (0x33AD, "M", "rad"), + (0x33AE, "M", "rad∕s"), + (0x33AF, "M", "rad∕s2"), + (0x33B0, "M", "ps"), + (0x33B1, "M", "ns"), + (0x33B2, "M", "μs"), + (0x33B3, "M", "ms"), + (0x33B4, "M", "pv"), + (0x33B5, "M", "nv"), + (0x33B6, "M", "μv"), + (0x33B7, "M", "mv"), + (0x33B8, "M", "kv"), + (0x33B9, "M", "mv"), + (0x33BA, "M", "pw"), + (0x33BB, "M", "nw"), + (0x33BC, "M", "μw"), + (0x33BD, "M", "mw"), + (0x33BE, "M", "kw"), + (0x33BF, "M", "mw"), + (0x33C0, "M", "kω"), + (0x33C1, "M", "mω"), + (0x33C2, "X"), + (0x33C3, "M", "bq"), + (0x33C4, "M", "cc"), + (0x33C5, "M", "cd"), + (0x33C6, "M", "c∕kg"), + (0x33C7, "X"), + (0x33C8, "M", "db"), + (0x33C9, "M", "gy"), + (0x33CA, "M", "ha"), + (0x33CB, "M", "hp"), + (0x33CC, "M", "in"), + (0x33CD, "M", "kk"), + (0x33CE, "M", "km"), + (0x33CF, "M", "kt"), + (0x33D0, "M", "lm"), + (0x33D1, "M", "ln"), + (0x33D2, "M", "log"), + (0x33D3, "M", "lx"), + (0x33D4, "M", "mb"), + (0x33D5, "M", "mil"), + (0x33D6, "M", "mol"), + (0x33D7, "M", "ph"), + (0x33D8, "X"), + (0x33D9, "M", "ppm"), + (0x33DA, "M", "pr"), + (0x33DB, "M", "sr"), + (0x33DC, "M", "sv"), + (0x33DD, "M", "wb"), + (0x33DE, "M", "v∕m"), + (0x33DF, "M", "a∕m"), + (0x33E0, "M", "1日"), + (0x33E1, "M", "2日"), + ] + + +def _seg_35() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x33E2, "M", "3日"), + (0x33E3, "M", "4日"), + (0x33E4, "M", "5日"), + (0x33E5, "M", "6日"), + (0x33E6, "M", "7日"), + (0x33E7, "M", "8日"), + (0x33E8, "M", "9日"), + (0x33E9, "M", "10日"), + (0x33EA, "M", "11日"), + (0x33EB, "M", "12日"), + (0x33EC, "M", "13日"), + (0x33ED, "M", "14日"), + (0x33EE, "M", "15日"), + (0x33EF, "M", "16日"), + (0x33F0, "M", "17日"), + (0x33F1, "M", "18日"), + (0x33F2, "M", "19日"), + (0x33F3, "M", "20日"), + (0x33F4, "M", "21日"), + (0x33F5, "M", "22日"), + (0x33F6, "M", "23日"), + (0x33F7, "M", "24日"), + (0x33F8, "M", "25日"), + (0x33F9, "M", "26日"), + (0x33FA, "M", "27日"), + (0x33FB, "M", "28日"), + (0x33FC, "M", "29日"), + (0x33FD, "M", "30日"), + (0x33FE, "M", "31日"), + (0x33FF, "M", "gal"), + (0x3400, "V"), + (0xA48D, "X"), + (0xA490, "V"), + (0xA4C7, "X"), + (0xA4D0, "V"), + (0xA62C, "X"), + (0xA640, "M", "ꙁ"), + (0xA641, "V"), + (0xA642, "M", "ꙃ"), + (0xA643, "V"), + (0xA644, "M", "ꙅ"), + (0xA645, "V"), + (0xA646, "M", "ꙇ"), + (0xA647, "V"), + (0xA648, "M", "ꙉ"), + (0xA649, "V"), + (0xA64A, "M", "ꙋ"), + (0xA64B, "V"), + (0xA64C, "M", "ꙍ"), + (0xA64D, "V"), + (0xA64E, "M", "ꙏ"), + (0xA64F, "V"), + (0xA650, "M", "ꙑ"), + (0xA651, "V"), + (0xA652, "M", "ꙓ"), + (0xA653, "V"), + (0xA654, "M", "ꙕ"), + (0xA655, "V"), + (0xA656, "M", "ꙗ"), + (0xA657, "V"), + (0xA658, "M", "ꙙ"), + (0xA659, "V"), + (0xA65A, "M", "ꙛ"), + (0xA65B, "V"), + (0xA65C, "M", "ꙝ"), + (0xA65D, "V"), + (0xA65E, "M", "ꙟ"), + (0xA65F, "V"), + (0xA660, "M", "ꙡ"), + (0xA661, "V"), + (0xA662, "M", "ꙣ"), + (0xA663, "V"), + (0xA664, "M", "ꙥ"), + (0xA665, "V"), + (0xA666, "M", "ꙧ"), + (0xA667, "V"), + (0xA668, "M", "ꙩ"), + (0xA669, "V"), + (0xA66A, "M", "ꙫ"), + (0xA66B, "V"), + (0xA66C, "M", "ꙭ"), + (0xA66D, "V"), + (0xA680, "M", "ꚁ"), + (0xA681, "V"), + (0xA682, "M", "ꚃ"), + (0xA683, "V"), + (0xA684, "M", "ꚅ"), + (0xA685, "V"), + (0xA686, "M", "ꚇ"), + (0xA687, "V"), + (0xA688, "M", "ꚉ"), + (0xA689, "V"), + (0xA68A, "M", "ꚋ"), + (0xA68B, "V"), + (0xA68C, "M", "ꚍ"), + (0xA68D, "V"), + (0xA68E, "M", "ꚏ"), + (0xA68F, "V"), + (0xA690, "M", "ꚑ"), + (0xA691, "V"), + ] + + +def _seg_36() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA692, "M", "ꚓ"), + (0xA693, "V"), + (0xA694, "M", "ꚕ"), + (0xA695, "V"), + (0xA696, "M", "ꚗ"), + (0xA697, "V"), + (0xA698, "M", "ꚙ"), + (0xA699, "V"), + (0xA69A, "M", "ꚛ"), + (0xA69B, "V"), + (0xA69C, "M", "ъ"), + (0xA69D, "M", "ь"), + (0xA69E, "V"), + (0xA6F8, "X"), + (0xA700, "V"), + (0xA722, "M", "ꜣ"), + (0xA723, "V"), + (0xA724, "M", "ꜥ"), + (0xA725, "V"), + (0xA726, "M", "ꜧ"), + (0xA727, "V"), + (0xA728, "M", "ꜩ"), + (0xA729, "V"), + (0xA72A, "M", "ꜫ"), + (0xA72B, "V"), + (0xA72C, "M", "ꜭ"), + (0xA72D, "V"), + (0xA72E, "M", "ꜯ"), + (0xA72F, "V"), + (0xA732, "M", "ꜳ"), + (0xA733, "V"), + (0xA734, "M", "ꜵ"), + (0xA735, "V"), + (0xA736, "M", "ꜷ"), + (0xA737, "V"), + (0xA738, "M", "ꜹ"), + (0xA739, "V"), + (0xA73A, "M", "ꜻ"), + (0xA73B, "V"), + (0xA73C, "M", "ꜽ"), + (0xA73D, "V"), + (0xA73E, "M", "ꜿ"), + (0xA73F, "V"), + (0xA740, "M", "ꝁ"), + (0xA741, "V"), + (0xA742, "M", "ꝃ"), + (0xA743, "V"), + (0xA744, "M", "ꝅ"), + (0xA745, "V"), + (0xA746, "M", "ꝇ"), + (0xA747, "V"), + (0xA748, "M", "ꝉ"), + (0xA749, "V"), + (0xA74A, "M", "ꝋ"), + (0xA74B, "V"), + (0xA74C, "M", "ꝍ"), + (0xA74D, "V"), + (0xA74E, "M", "ꝏ"), + (0xA74F, "V"), + (0xA750, "M", "ꝑ"), + (0xA751, "V"), + (0xA752, "M", "ꝓ"), + (0xA753, "V"), + (0xA754, "M", "ꝕ"), + (0xA755, "V"), + (0xA756, "M", "ꝗ"), + (0xA757, "V"), + (0xA758, "M", "ꝙ"), + (0xA759, "V"), + (0xA75A, "M", "ꝛ"), + (0xA75B, "V"), + (0xA75C, "M", "ꝝ"), + (0xA75D, "V"), + (0xA75E, "M", "ꝟ"), + (0xA75F, "V"), + (0xA760, "M", "ꝡ"), + (0xA761, "V"), + (0xA762, "M", "ꝣ"), + (0xA763, "V"), + (0xA764, "M", "ꝥ"), + (0xA765, "V"), + (0xA766, "M", "ꝧ"), + (0xA767, "V"), + (0xA768, "M", "ꝩ"), + (0xA769, "V"), + (0xA76A, "M", "ꝫ"), + (0xA76B, "V"), + (0xA76C, "M", "ꝭ"), + (0xA76D, "V"), + (0xA76E, "M", "ꝯ"), + (0xA76F, "V"), + (0xA770, "M", "ꝯ"), + (0xA771, "V"), + (0xA779, "M", "ꝺ"), + (0xA77A, "V"), + (0xA77B, "M", "ꝼ"), + (0xA77C, "V"), + (0xA77D, "M", "ᵹ"), + (0xA77E, "M", "ꝿ"), + (0xA77F, "V"), + ] + + +def _seg_37() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA780, "M", "ꞁ"), + (0xA781, "V"), + (0xA782, "M", "ꞃ"), + (0xA783, "V"), + (0xA784, "M", "ꞅ"), + (0xA785, "V"), + (0xA786, "M", "ꞇ"), + (0xA787, "V"), + (0xA78B, "M", "ꞌ"), + (0xA78C, "V"), + (0xA78D, "M", "ɥ"), + (0xA78E, "V"), + (0xA790, "M", "ꞑ"), + (0xA791, "V"), + (0xA792, "M", "ꞓ"), + (0xA793, "V"), + (0xA796, "M", "ꞗ"), + (0xA797, "V"), + (0xA798, "M", "ꞙ"), + (0xA799, "V"), + (0xA79A, "M", "ꞛ"), + (0xA79B, "V"), + (0xA79C, "M", "ꞝ"), + (0xA79D, "V"), + (0xA79E, "M", "ꞟ"), + (0xA79F, "V"), + (0xA7A0, "M", "ꞡ"), + (0xA7A1, "V"), + (0xA7A2, "M", "ꞣ"), + (0xA7A3, "V"), + (0xA7A4, "M", "ꞥ"), + (0xA7A5, "V"), + (0xA7A6, "M", "ꞧ"), + (0xA7A7, "V"), + (0xA7A8, "M", "ꞩ"), + (0xA7A9, "V"), + (0xA7AA, "M", "ɦ"), + (0xA7AB, "M", "ɜ"), + (0xA7AC, "M", "ɡ"), + (0xA7AD, "M", "ɬ"), + (0xA7AE, "M", "ɪ"), + (0xA7AF, "V"), + (0xA7B0, "M", "ʞ"), + (0xA7B1, "M", "ʇ"), + (0xA7B2, "M", "ʝ"), + (0xA7B3, "M", "ꭓ"), + (0xA7B4, "M", "ꞵ"), + (0xA7B5, "V"), + (0xA7B6, "M", "ꞷ"), + (0xA7B7, "V"), + (0xA7B8, "M", "ꞹ"), + (0xA7B9, "V"), + (0xA7BA, "M", "ꞻ"), + (0xA7BB, "V"), + (0xA7BC, "M", "ꞽ"), + (0xA7BD, "V"), + (0xA7BE, "M", "ꞿ"), + (0xA7BF, "V"), + (0xA7C0, "M", "ꟁ"), + (0xA7C1, "V"), + (0xA7C2, "M", "ꟃ"), + (0xA7C3, "V"), + (0xA7C4, "M", "ꞔ"), + (0xA7C5, "M", "ʂ"), + (0xA7C6, "M", "ᶎ"), + (0xA7C7, "M", "ꟈ"), + (0xA7C8, "V"), + (0xA7C9, "M", "ꟊ"), + (0xA7CA, "V"), + (0xA7CB, "X"), + (0xA7D0, "M", "ꟑ"), + (0xA7D1, "V"), + (0xA7D2, "X"), + (0xA7D3, "V"), + (0xA7D4, "X"), + (0xA7D5, "V"), + (0xA7D6, "M", "ꟗ"), + (0xA7D7, "V"), + (0xA7D8, "M", "ꟙ"), + (0xA7D9, "V"), + (0xA7DA, "X"), + (0xA7F2, "M", "c"), + (0xA7F3, "M", "f"), + (0xA7F4, "M", "q"), + (0xA7F5, "M", "ꟶ"), + (0xA7F6, "V"), + (0xA7F8, "M", "ħ"), + (0xA7F9, "M", "œ"), + (0xA7FA, "V"), + (0xA82D, "X"), + (0xA830, "V"), + (0xA83A, "X"), + (0xA840, "V"), + (0xA878, "X"), + (0xA880, "V"), + (0xA8C6, "X"), + (0xA8CE, "V"), + (0xA8DA, "X"), + (0xA8E0, "V"), + (0xA954, "X"), + ] + + +def _seg_38() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xA95F, "V"), + (0xA97D, "X"), + (0xA980, "V"), + (0xA9CE, "X"), + (0xA9CF, "V"), + (0xA9DA, "X"), + (0xA9DE, "V"), + (0xA9FF, "X"), + (0xAA00, "V"), + (0xAA37, "X"), + (0xAA40, "V"), + (0xAA4E, "X"), + (0xAA50, "V"), + (0xAA5A, "X"), + (0xAA5C, "V"), + (0xAAC3, "X"), + (0xAADB, "V"), + (0xAAF7, "X"), + (0xAB01, "V"), + (0xAB07, "X"), + (0xAB09, "V"), + (0xAB0F, "X"), + (0xAB11, "V"), + (0xAB17, "X"), + (0xAB20, "V"), + (0xAB27, "X"), + (0xAB28, "V"), + (0xAB2F, "X"), + (0xAB30, "V"), + (0xAB5C, "M", "ꜧ"), + (0xAB5D, "M", "ꬷ"), + (0xAB5E, "M", "ɫ"), + (0xAB5F, "M", "ꭒ"), + (0xAB60, "V"), + (0xAB69, "M", "ʍ"), + (0xAB6A, "V"), + (0xAB6C, "X"), + (0xAB70, "M", "Ꭰ"), + (0xAB71, "M", "Ꭱ"), + (0xAB72, "M", "Ꭲ"), + (0xAB73, "M", "Ꭳ"), + (0xAB74, "M", "Ꭴ"), + (0xAB75, "M", "Ꭵ"), + (0xAB76, "M", "Ꭶ"), + (0xAB77, "M", "Ꭷ"), + (0xAB78, "M", "Ꭸ"), + (0xAB79, "M", "Ꭹ"), + (0xAB7A, "M", "Ꭺ"), + (0xAB7B, "M", "Ꭻ"), + (0xAB7C, "M", "Ꭼ"), + (0xAB7D, "M", "Ꭽ"), + (0xAB7E, "M", "Ꭾ"), + (0xAB7F, "M", "Ꭿ"), + (0xAB80, "M", "Ꮀ"), + (0xAB81, "M", "Ꮁ"), + (0xAB82, "M", "Ꮂ"), + (0xAB83, "M", "Ꮃ"), + (0xAB84, "M", "Ꮄ"), + (0xAB85, "M", "Ꮅ"), + (0xAB86, "M", "Ꮆ"), + (0xAB87, "M", "Ꮇ"), + (0xAB88, "M", "Ꮈ"), + (0xAB89, "M", "Ꮉ"), + (0xAB8A, "M", "Ꮊ"), + (0xAB8B, "M", "Ꮋ"), + (0xAB8C, "M", "Ꮌ"), + (0xAB8D, "M", "Ꮍ"), + (0xAB8E, "M", "Ꮎ"), + (0xAB8F, "M", "Ꮏ"), + (0xAB90, "M", "Ꮐ"), + (0xAB91, "M", "Ꮑ"), + (0xAB92, "M", "Ꮒ"), + (0xAB93, "M", "Ꮓ"), + (0xAB94, "M", "Ꮔ"), + (0xAB95, "M", "Ꮕ"), + (0xAB96, "M", "Ꮖ"), + (0xAB97, "M", "Ꮗ"), + (0xAB98, "M", "Ꮘ"), + (0xAB99, "M", "Ꮙ"), + (0xAB9A, "M", "Ꮚ"), + (0xAB9B, "M", "Ꮛ"), + (0xAB9C, "M", "Ꮜ"), + (0xAB9D, "M", "Ꮝ"), + (0xAB9E, "M", "Ꮞ"), + (0xAB9F, "M", "Ꮟ"), + (0xABA0, "M", "Ꮠ"), + (0xABA1, "M", "Ꮡ"), + (0xABA2, "M", "Ꮢ"), + (0xABA3, "M", "Ꮣ"), + (0xABA4, "M", "Ꮤ"), + (0xABA5, "M", "Ꮥ"), + (0xABA6, "M", "Ꮦ"), + (0xABA7, "M", "Ꮧ"), + (0xABA8, "M", "Ꮨ"), + (0xABA9, "M", "Ꮩ"), + (0xABAA, "M", "Ꮪ"), + (0xABAB, "M", "Ꮫ"), + (0xABAC, "M", "Ꮬ"), + (0xABAD, "M", "Ꮭ"), + (0xABAE, "M", "Ꮮ"), + ] + + +def _seg_39() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xABAF, "M", "Ꮯ"), + (0xABB0, "M", "Ꮰ"), + (0xABB1, "M", "Ꮱ"), + (0xABB2, "M", "Ꮲ"), + (0xABB3, "M", "Ꮳ"), + (0xABB4, "M", "Ꮴ"), + (0xABB5, "M", "Ꮵ"), + (0xABB6, "M", "Ꮶ"), + (0xABB7, "M", "Ꮷ"), + (0xABB8, "M", "Ꮸ"), + (0xABB9, "M", "Ꮹ"), + (0xABBA, "M", "Ꮺ"), + (0xABBB, "M", "Ꮻ"), + (0xABBC, "M", "Ꮼ"), + (0xABBD, "M", "Ꮽ"), + (0xABBE, "M", "Ꮾ"), + (0xABBF, "M", "Ꮿ"), + (0xABC0, "V"), + (0xABEE, "X"), + (0xABF0, "V"), + (0xABFA, "X"), + (0xAC00, "V"), + (0xD7A4, "X"), + (0xD7B0, "V"), + (0xD7C7, "X"), + (0xD7CB, "V"), + (0xD7FC, "X"), + (0xF900, "M", "豈"), + (0xF901, "M", "更"), + (0xF902, "M", "車"), + (0xF903, "M", "賈"), + (0xF904, "M", "滑"), + (0xF905, "M", "串"), + (0xF906, "M", "句"), + (0xF907, "M", "龜"), + (0xF909, "M", "契"), + (0xF90A, "M", "金"), + (0xF90B, "M", "喇"), + (0xF90C, "M", "奈"), + (0xF90D, "M", "懶"), + (0xF90E, "M", "癩"), + (0xF90F, "M", "羅"), + (0xF910, "M", "蘿"), + (0xF911, "M", "螺"), + (0xF912, "M", "裸"), + (0xF913, "M", "邏"), + (0xF914, "M", "樂"), + (0xF915, "M", "洛"), + (0xF916, "M", "烙"), + (0xF917, "M", "珞"), + (0xF918, "M", "落"), + (0xF919, "M", "酪"), + (0xF91A, "M", "駱"), + (0xF91B, "M", "亂"), + (0xF91C, "M", "卵"), + (0xF91D, "M", "欄"), + (0xF91E, "M", "爛"), + (0xF91F, "M", "蘭"), + (0xF920, "M", "鸞"), + (0xF921, "M", "嵐"), + (0xF922, "M", "濫"), + (0xF923, "M", "藍"), + (0xF924, "M", "襤"), + (0xF925, "M", "拉"), + (0xF926, "M", "臘"), + (0xF927, "M", "蠟"), + (0xF928, "M", "廊"), + (0xF929, "M", "朗"), + (0xF92A, "M", "浪"), + (0xF92B, "M", "狼"), + (0xF92C, "M", "郎"), + (0xF92D, "M", "來"), + (0xF92E, "M", "冷"), + (0xF92F, "M", "勞"), + (0xF930, "M", "擄"), + (0xF931, "M", "櫓"), + (0xF932, "M", "爐"), + (0xF933, "M", "盧"), + (0xF934, "M", "老"), + (0xF935, "M", "蘆"), + (0xF936, "M", "虜"), + (0xF937, "M", "路"), + (0xF938, "M", "露"), + (0xF939, "M", "魯"), + (0xF93A, "M", "鷺"), + (0xF93B, "M", "碌"), + (0xF93C, "M", "祿"), + (0xF93D, "M", "綠"), + (0xF93E, "M", "菉"), + (0xF93F, "M", "錄"), + (0xF940, "M", "鹿"), + (0xF941, "M", "論"), + (0xF942, "M", "壟"), + (0xF943, "M", "弄"), + (0xF944, "M", "籠"), + (0xF945, "M", "聾"), + (0xF946, "M", "牢"), + (0xF947, "M", "磊"), + (0xF948, "M", "賂"), + (0xF949, "M", "雷"), + ] + + +def _seg_40() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xF94A, "M", "壘"), + (0xF94B, "M", "屢"), + (0xF94C, "M", "樓"), + (0xF94D, "M", "淚"), + (0xF94E, "M", "漏"), + (0xF94F, "M", "累"), + (0xF950, "M", "縷"), + (0xF951, "M", "陋"), + (0xF952, "M", "勒"), + (0xF953, "M", "肋"), + (0xF954, "M", "凜"), + (0xF955, "M", "凌"), + (0xF956, "M", "稜"), + (0xF957, "M", "綾"), + (0xF958, "M", "菱"), + (0xF959, "M", "陵"), + (0xF95A, "M", "讀"), + (0xF95B, "M", "拏"), + (0xF95C, "M", "樂"), + (0xF95D, "M", "諾"), + (0xF95E, "M", "丹"), + (0xF95F, "M", "寧"), + (0xF960, "M", "怒"), + (0xF961, "M", "率"), + (0xF962, "M", "異"), + (0xF963, "M", "北"), + (0xF964, "M", "磻"), + (0xF965, "M", "便"), + (0xF966, "M", "復"), + (0xF967, "M", "不"), + (0xF968, "M", "泌"), + (0xF969, "M", "數"), + (0xF96A, "M", "索"), + (0xF96B, "M", "參"), + (0xF96C, "M", "塞"), + (0xF96D, "M", "省"), + (0xF96E, "M", "葉"), + (0xF96F, "M", "說"), + (0xF970, "M", "殺"), + (0xF971, "M", "辰"), + (0xF972, "M", "沈"), + (0xF973, "M", "拾"), + (0xF974, "M", "若"), + (0xF975, "M", "掠"), + (0xF976, "M", "略"), + (0xF977, "M", "亮"), + (0xF978, "M", "兩"), + (0xF979, "M", "凉"), + (0xF97A, "M", "梁"), + (0xF97B, "M", "糧"), + (0xF97C, "M", "良"), + (0xF97D, "M", "諒"), + (0xF97E, "M", "量"), + (0xF97F, "M", "勵"), + (0xF980, "M", "呂"), + (0xF981, "M", "女"), + (0xF982, "M", "廬"), + (0xF983, "M", "旅"), + (0xF984, "M", "濾"), + (0xF985, "M", "礪"), + (0xF986, "M", "閭"), + (0xF987, "M", "驪"), + (0xF988, "M", "麗"), + (0xF989, "M", "黎"), + (0xF98A, "M", "力"), + (0xF98B, "M", "曆"), + (0xF98C, "M", "歷"), + (0xF98D, "M", "轢"), + (0xF98E, "M", "年"), + (0xF98F, "M", "憐"), + (0xF990, "M", "戀"), + (0xF991, "M", "撚"), + (0xF992, "M", "漣"), + (0xF993, "M", "煉"), + (0xF994, "M", "璉"), + (0xF995, "M", "秊"), + (0xF996, "M", "練"), + (0xF997, "M", "聯"), + (0xF998, "M", "輦"), + (0xF999, "M", "蓮"), + (0xF99A, "M", "連"), + (0xF99B, "M", "鍊"), + (0xF99C, "M", "列"), + (0xF99D, "M", "劣"), + (0xF99E, "M", "咽"), + (0xF99F, "M", "烈"), + (0xF9A0, "M", "裂"), + (0xF9A1, "M", "說"), + (0xF9A2, "M", "廉"), + (0xF9A3, "M", "念"), + (0xF9A4, "M", "捻"), + (0xF9A5, "M", "殮"), + (0xF9A6, "M", "簾"), + (0xF9A7, "M", "獵"), + (0xF9A8, "M", "令"), + (0xF9A9, "M", "囹"), + (0xF9AA, "M", "寧"), + (0xF9AB, "M", "嶺"), + (0xF9AC, "M", "怜"), + (0xF9AD, "M", "玲"), + ] + + +def _seg_41() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xF9AE, "M", "瑩"), + (0xF9AF, "M", "羚"), + (0xF9B0, "M", "聆"), + (0xF9B1, "M", "鈴"), + (0xF9B2, "M", "零"), + (0xF9B3, "M", "靈"), + (0xF9B4, "M", "領"), + (0xF9B5, "M", "例"), + (0xF9B6, "M", "禮"), + (0xF9B7, "M", "醴"), + (0xF9B8, "M", "隸"), + (0xF9B9, "M", "惡"), + (0xF9BA, "M", "了"), + (0xF9BB, "M", "僚"), + (0xF9BC, "M", "寮"), + (0xF9BD, "M", "尿"), + (0xF9BE, "M", "料"), + (0xF9BF, "M", "樂"), + (0xF9C0, "M", "燎"), + (0xF9C1, "M", "療"), + (0xF9C2, "M", "蓼"), + (0xF9C3, "M", "遼"), + (0xF9C4, "M", "龍"), + (0xF9C5, "M", "暈"), + (0xF9C6, "M", "阮"), + (0xF9C7, "M", "劉"), + (0xF9C8, "M", "杻"), + (0xF9C9, "M", "柳"), + (0xF9CA, "M", "流"), + (0xF9CB, "M", "溜"), + (0xF9CC, "M", "琉"), + (0xF9CD, "M", "留"), + (0xF9CE, "M", "硫"), + (0xF9CF, "M", "紐"), + (0xF9D0, "M", "類"), + (0xF9D1, "M", "六"), + (0xF9D2, "M", "戮"), + (0xF9D3, "M", "陸"), + (0xF9D4, "M", "倫"), + (0xF9D5, "M", "崙"), + (0xF9D6, "M", "淪"), + (0xF9D7, "M", "輪"), + (0xF9D8, "M", "律"), + (0xF9D9, "M", "慄"), + (0xF9DA, "M", "栗"), + (0xF9DB, "M", "率"), + (0xF9DC, "M", "隆"), + (0xF9DD, "M", "利"), + (0xF9DE, "M", "吏"), + (0xF9DF, "M", "履"), + (0xF9E0, "M", "易"), + (0xF9E1, "M", "李"), + (0xF9E2, "M", "梨"), + (0xF9E3, "M", "泥"), + (0xF9E4, "M", "理"), + (0xF9E5, "M", "痢"), + (0xF9E6, "M", "罹"), + (0xF9E7, "M", "裏"), + (0xF9E8, "M", "裡"), + (0xF9E9, "M", "里"), + (0xF9EA, "M", "離"), + (0xF9EB, "M", "匿"), + (0xF9EC, "M", "溺"), + (0xF9ED, "M", "吝"), + (0xF9EE, "M", "燐"), + (0xF9EF, "M", "璘"), + (0xF9F0, "M", "藺"), + (0xF9F1, "M", "隣"), + (0xF9F2, "M", "鱗"), + (0xF9F3, "M", "麟"), + (0xF9F4, "M", "林"), + (0xF9F5, "M", "淋"), + (0xF9F6, "M", "臨"), + (0xF9F7, "M", "立"), + (0xF9F8, "M", "笠"), + (0xF9F9, "M", "粒"), + (0xF9FA, "M", "狀"), + (0xF9FB, "M", "炙"), + (0xF9FC, "M", "識"), + (0xF9FD, "M", "什"), + (0xF9FE, "M", "茶"), + (0xF9FF, "M", "刺"), + (0xFA00, "M", "切"), + (0xFA01, "M", "度"), + (0xFA02, "M", "拓"), + (0xFA03, "M", "糖"), + (0xFA04, "M", "宅"), + (0xFA05, "M", "洞"), + (0xFA06, "M", "暴"), + (0xFA07, "M", "輻"), + (0xFA08, "M", "行"), + (0xFA09, "M", "降"), + (0xFA0A, "M", "見"), + (0xFA0B, "M", "廓"), + (0xFA0C, "M", "兀"), + (0xFA0D, "M", "嗀"), + (0xFA0E, "V"), + (0xFA10, "M", "塚"), + (0xFA11, "V"), + (0xFA12, "M", "晴"), + ] + + +def _seg_42() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFA13, "V"), + (0xFA15, "M", "凞"), + (0xFA16, "M", "猪"), + (0xFA17, "M", "益"), + (0xFA18, "M", "礼"), + (0xFA19, "M", "神"), + (0xFA1A, "M", "祥"), + (0xFA1B, "M", "福"), + (0xFA1C, "M", "靖"), + (0xFA1D, "M", "精"), + (0xFA1E, "M", "羽"), + (0xFA1F, "V"), + (0xFA20, "M", "蘒"), + (0xFA21, "V"), + (0xFA22, "M", "諸"), + (0xFA23, "V"), + (0xFA25, "M", "逸"), + (0xFA26, "M", "都"), + (0xFA27, "V"), + (0xFA2A, "M", "飯"), + (0xFA2B, "M", "飼"), + (0xFA2C, "M", "館"), + (0xFA2D, "M", "鶴"), + (0xFA2E, "M", "郞"), + (0xFA2F, "M", "隷"), + (0xFA30, "M", "侮"), + (0xFA31, "M", "僧"), + (0xFA32, "M", "免"), + (0xFA33, "M", "勉"), + (0xFA34, "M", "勤"), + (0xFA35, "M", "卑"), + (0xFA36, "M", "喝"), + (0xFA37, "M", "嘆"), + (0xFA38, "M", "器"), + (0xFA39, "M", "塀"), + (0xFA3A, "M", "墨"), + (0xFA3B, "M", "層"), + (0xFA3C, "M", "屮"), + (0xFA3D, "M", "悔"), + (0xFA3E, "M", "慨"), + (0xFA3F, "M", "憎"), + (0xFA40, "M", "懲"), + (0xFA41, "M", "敏"), + (0xFA42, "M", "既"), + (0xFA43, "M", "暑"), + (0xFA44, "M", "梅"), + (0xFA45, "M", "海"), + (0xFA46, "M", "渚"), + (0xFA47, "M", "漢"), + (0xFA48, "M", "煮"), + (0xFA49, "M", "爫"), + (0xFA4A, "M", "琢"), + (0xFA4B, "M", "碑"), + (0xFA4C, "M", "社"), + (0xFA4D, "M", "祉"), + (0xFA4E, "M", "祈"), + (0xFA4F, "M", "祐"), + (0xFA50, "M", "祖"), + (0xFA51, "M", "祝"), + (0xFA52, "M", "禍"), + (0xFA53, "M", "禎"), + (0xFA54, "M", "穀"), + (0xFA55, "M", "突"), + (0xFA56, "M", "節"), + (0xFA57, "M", "練"), + (0xFA58, "M", "縉"), + (0xFA59, "M", "繁"), + (0xFA5A, "M", "署"), + (0xFA5B, "M", "者"), + (0xFA5C, "M", "臭"), + (0xFA5D, "M", "艹"), + (0xFA5F, "M", "著"), + (0xFA60, "M", "褐"), + (0xFA61, "M", "視"), + (0xFA62, "M", "謁"), + (0xFA63, "M", "謹"), + (0xFA64, "M", "賓"), + (0xFA65, "M", "贈"), + (0xFA66, "M", "辶"), + (0xFA67, "M", "逸"), + (0xFA68, "M", "難"), + (0xFA69, "M", "響"), + (0xFA6A, "M", "頻"), + (0xFA6B, "M", "恵"), + (0xFA6C, "M", "𤋮"), + (0xFA6D, "M", "舘"), + (0xFA6E, "X"), + (0xFA70, "M", "並"), + (0xFA71, "M", "况"), + (0xFA72, "M", "全"), + (0xFA73, "M", "侀"), + (0xFA74, "M", "充"), + (0xFA75, "M", "冀"), + (0xFA76, "M", "勇"), + (0xFA77, "M", "勺"), + (0xFA78, "M", "喝"), + (0xFA79, "M", "啕"), + (0xFA7A, "M", "喙"), + (0xFA7B, "M", "嗢"), + (0xFA7C, "M", "塚"), + ] + + +def _seg_43() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFA7D, "M", "墳"), + (0xFA7E, "M", "奄"), + (0xFA7F, "M", "奔"), + (0xFA80, "M", "婢"), + (0xFA81, "M", "嬨"), + (0xFA82, "M", "廒"), + (0xFA83, "M", "廙"), + (0xFA84, "M", "彩"), + (0xFA85, "M", "徭"), + (0xFA86, "M", "惘"), + (0xFA87, "M", "慎"), + (0xFA88, "M", "愈"), + (0xFA89, "M", "憎"), + (0xFA8A, "M", "慠"), + (0xFA8B, "M", "懲"), + (0xFA8C, "M", "戴"), + (0xFA8D, "M", "揄"), + (0xFA8E, "M", "搜"), + (0xFA8F, "M", "摒"), + (0xFA90, "M", "敖"), + (0xFA91, "M", "晴"), + (0xFA92, "M", "朗"), + (0xFA93, "M", "望"), + (0xFA94, "M", "杖"), + (0xFA95, "M", "歹"), + (0xFA96, "M", "殺"), + (0xFA97, "M", "流"), + (0xFA98, "M", "滛"), + (0xFA99, "M", "滋"), + (0xFA9A, "M", "漢"), + (0xFA9B, "M", "瀞"), + (0xFA9C, "M", "煮"), + (0xFA9D, "M", "瞧"), + (0xFA9E, "M", "爵"), + (0xFA9F, "M", "犯"), + (0xFAA0, "M", "猪"), + (0xFAA1, "M", "瑱"), + (0xFAA2, "M", "甆"), + (0xFAA3, "M", "画"), + (0xFAA4, "M", "瘝"), + (0xFAA5, "M", "瘟"), + (0xFAA6, "M", "益"), + (0xFAA7, "M", "盛"), + (0xFAA8, "M", "直"), + (0xFAA9, "M", "睊"), + (0xFAAA, "M", "着"), + (0xFAAB, "M", "磌"), + (0xFAAC, "M", "窱"), + (0xFAAD, "M", "節"), + (0xFAAE, "M", "类"), + (0xFAAF, "M", "絛"), + (0xFAB0, "M", "練"), + (0xFAB1, "M", "缾"), + (0xFAB2, "M", "者"), + (0xFAB3, "M", "荒"), + (0xFAB4, "M", "華"), + (0xFAB5, "M", "蝹"), + (0xFAB6, "M", "襁"), + (0xFAB7, "M", "覆"), + (0xFAB8, "M", "視"), + (0xFAB9, "M", "調"), + (0xFABA, "M", "諸"), + (0xFABB, "M", "請"), + (0xFABC, "M", "謁"), + (0xFABD, "M", "諾"), + (0xFABE, "M", "諭"), + (0xFABF, "M", "謹"), + (0xFAC0, "M", "變"), + (0xFAC1, "M", "贈"), + (0xFAC2, "M", "輸"), + (0xFAC3, "M", "遲"), + (0xFAC4, "M", "醙"), + (0xFAC5, "M", "鉶"), + (0xFAC6, "M", "陼"), + (0xFAC7, "M", "難"), + (0xFAC8, "M", "靖"), + (0xFAC9, "M", "韛"), + (0xFACA, "M", "響"), + (0xFACB, "M", "頋"), + (0xFACC, "M", "頻"), + (0xFACD, "M", "鬒"), + (0xFACE, "M", "龜"), + (0xFACF, "M", "𢡊"), + (0xFAD0, "M", "𢡄"), + (0xFAD1, "M", "𣏕"), + (0xFAD2, "M", "㮝"), + (0xFAD3, "M", "䀘"), + (0xFAD4, "M", "䀹"), + (0xFAD5, "M", "𥉉"), + (0xFAD6, "M", "𥳐"), + (0xFAD7, "M", "𧻓"), + (0xFAD8, "M", "齃"), + (0xFAD9, "M", "龎"), + (0xFADA, "X"), + (0xFB00, "M", "ff"), + (0xFB01, "M", "fi"), + (0xFB02, "M", "fl"), + (0xFB03, "M", "ffi"), + (0xFB04, "M", "ffl"), + (0xFB05, "M", "st"), + ] + + +def _seg_44() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFB07, "X"), + (0xFB13, "M", "մն"), + (0xFB14, "M", "մե"), + (0xFB15, "M", "մի"), + (0xFB16, "M", "վն"), + (0xFB17, "M", "մխ"), + (0xFB18, "X"), + (0xFB1D, "M", "יִ"), + (0xFB1E, "V"), + (0xFB1F, "M", "ײַ"), + (0xFB20, "M", "ע"), + (0xFB21, "M", "א"), + (0xFB22, "M", "ד"), + (0xFB23, "M", "ה"), + (0xFB24, "M", "כ"), + (0xFB25, "M", "ל"), + (0xFB26, "M", "ם"), + (0xFB27, "M", "ר"), + (0xFB28, "M", "ת"), + (0xFB29, "3", "+"), + (0xFB2A, "M", "שׁ"), + (0xFB2B, "M", "שׂ"), + (0xFB2C, "M", "שּׁ"), + (0xFB2D, "M", "שּׂ"), + (0xFB2E, "M", "אַ"), + (0xFB2F, "M", "אָ"), + (0xFB30, "M", "אּ"), + (0xFB31, "M", "בּ"), + (0xFB32, "M", "גּ"), + (0xFB33, "M", "דּ"), + (0xFB34, "M", "הּ"), + (0xFB35, "M", "וּ"), + (0xFB36, "M", "זּ"), + (0xFB37, "X"), + (0xFB38, "M", "טּ"), + (0xFB39, "M", "יּ"), + (0xFB3A, "M", "ךּ"), + (0xFB3B, "M", "כּ"), + (0xFB3C, "M", "לּ"), + (0xFB3D, "X"), + (0xFB3E, "M", "מּ"), + (0xFB3F, "X"), + (0xFB40, "M", "נּ"), + (0xFB41, "M", "סּ"), + (0xFB42, "X"), + (0xFB43, "M", "ףּ"), + (0xFB44, "M", "פּ"), + (0xFB45, "X"), + (0xFB46, "M", "צּ"), + (0xFB47, "M", "קּ"), + (0xFB48, "M", "רּ"), + (0xFB49, "M", "שּ"), + (0xFB4A, "M", "תּ"), + (0xFB4B, "M", "וֹ"), + (0xFB4C, "M", "בֿ"), + (0xFB4D, "M", "כֿ"), + (0xFB4E, "M", "פֿ"), + (0xFB4F, "M", "אל"), + (0xFB50, "M", "ٱ"), + (0xFB52, "M", "ٻ"), + (0xFB56, "M", "پ"), + (0xFB5A, "M", "ڀ"), + (0xFB5E, "M", "ٺ"), + (0xFB62, "M", "ٿ"), + (0xFB66, "M", "ٹ"), + (0xFB6A, "M", "ڤ"), + (0xFB6E, "M", "ڦ"), + (0xFB72, "M", "ڄ"), + (0xFB76, "M", "ڃ"), + (0xFB7A, "M", "چ"), + (0xFB7E, "M", "ڇ"), + (0xFB82, "M", "ڍ"), + (0xFB84, "M", "ڌ"), + (0xFB86, "M", "ڎ"), + (0xFB88, "M", "ڈ"), + (0xFB8A, "M", "ژ"), + (0xFB8C, "M", "ڑ"), + (0xFB8E, "M", "ک"), + (0xFB92, "M", "گ"), + (0xFB96, "M", "ڳ"), + (0xFB9A, "M", "ڱ"), + (0xFB9E, "M", "ں"), + (0xFBA0, "M", "ڻ"), + (0xFBA4, "M", "ۀ"), + (0xFBA6, "M", "ہ"), + (0xFBAA, "M", "ھ"), + (0xFBAE, "M", "ے"), + (0xFBB0, "M", "ۓ"), + (0xFBB2, "V"), + (0xFBC3, "X"), + (0xFBD3, "M", "ڭ"), + (0xFBD7, "M", "ۇ"), + (0xFBD9, "M", "ۆ"), + (0xFBDB, "M", "ۈ"), + (0xFBDD, "M", "ۇٴ"), + (0xFBDE, "M", "ۋ"), + (0xFBE0, "M", "ۅ"), + (0xFBE2, "M", "ۉ"), + (0xFBE4, "M", "ې"), + (0xFBE8, "M", "ى"), + ] + + +def _seg_45() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFBEA, "M", "ئا"), + (0xFBEC, "M", "ئە"), + (0xFBEE, "M", "ئو"), + (0xFBF0, "M", "ئۇ"), + (0xFBF2, "M", "ئۆ"), + (0xFBF4, "M", "ئۈ"), + (0xFBF6, "M", "ئې"), + (0xFBF9, "M", "ئى"), + (0xFBFC, "M", "ی"), + (0xFC00, "M", "ئج"), + (0xFC01, "M", "ئح"), + (0xFC02, "M", "ئم"), + (0xFC03, "M", "ئى"), + (0xFC04, "M", "ئي"), + (0xFC05, "M", "بج"), + (0xFC06, "M", "بح"), + (0xFC07, "M", "بخ"), + (0xFC08, "M", "بم"), + (0xFC09, "M", "بى"), + (0xFC0A, "M", "بي"), + (0xFC0B, "M", "تج"), + (0xFC0C, "M", "تح"), + (0xFC0D, "M", "تخ"), + (0xFC0E, "M", "تم"), + (0xFC0F, "M", "تى"), + (0xFC10, "M", "تي"), + (0xFC11, "M", "ثج"), + (0xFC12, "M", "ثم"), + (0xFC13, "M", "ثى"), + (0xFC14, "M", "ثي"), + (0xFC15, "M", "جح"), + (0xFC16, "M", "جم"), + (0xFC17, "M", "حج"), + (0xFC18, "M", "حم"), + (0xFC19, "M", "خج"), + (0xFC1A, "M", "خح"), + (0xFC1B, "M", "خم"), + (0xFC1C, "M", "سج"), + (0xFC1D, "M", "سح"), + (0xFC1E, "M", "سخ"), + (0xFC1F, "M", "سم"), + (0xFC20, "M", "صح"), + (0xFC21, "M", "صم"), + (0xFC22, "M", "ضج"), + (0xFC23, "M", "ضح"), + (0xFC24, "M", "ضخ"), + (0xFC25, "M", "ضم"), + (0xFC26, "M", "طح"), + (0xFC27, "M", "طم"), + (0xFC28, "M", "ظم"), + (0xFC29, "M", "عج"), + (0xFC2A, "M", "عم"), + (0xFC2B, "M", "غج"), + (0xFC2C, "M", "غم"), + (0xFC2D, "M", "فج"), + (0xFC2E, "M", "فح"), + (0xFC2F, "M", "فخ"), + (0xFC30, "M", "فم"), + (0xFC31, "M", "فى"), + (0xFC32, "M", "في"), + (0xFC33, "M", "قح"), + (0xFC34, "M", "قم"), + (0xFC35, "M", "قى"), + (0xFC36, "M", "قي"), + (0xFC37, "M", "كا"), + (0xFC38, "M", "كج"), + (0xFC39, "M", "كح"), + (0xFC3A, "M", "كخ"), + (0xFC3B, "M", "كل"), + (0xFC3C, "M", "كم"), + (0xFC3D, "M", "كى"), + (0xFC3E, "M", "كي"), + (0xFC3F, "M", "لج"), + (0xFC40, "M", "لح"), + (0xFC41, "M", "لخ"), + (0xFC42, "M", "لم"), + (0xFC43, "M", "لى"), + (0xFC44, "M", "لي"), + (0xFC45, "M", "مج"), + (0xFC46, "M", "مح"), + (0xFC47, "M", "مخ"), + (0xFC48, "M", "مم"), + (0xFC49, "M", "مى"), + (0xFC4A, "M", "مي"), + (0xFC4B, "M", "نج"), + (0xFC4C, "M", "نح"), + (0xFC4D, "M", "نخ"), + (0xFC4E, "M", "نم"), + (0xFC4F, "M", "نى"), + (0xFC50, "M", "ني"), + (0xFC51, "M", "هج"), + (0xFC52, "M", "هم"), + (0xFC53, "M", "هى"), + (0xFC54, "M", "هي"), + (0xFC55, "M", "يج"), + (0xFC56, "M", "يح"), + (0xFC57, "M", "يخ"), + (0xFC58, "M", "يم"), + (0xFC59, "M", "يى"), + (0xFC5A, "M", "يي"), + ] + + +def _seg_46() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFC5B, "M", "ذٰ"), + (0xFC5C, "M", "رٰ"), + (0xFC5D, "M", "ىٰ"), + (0xFC5E, "3", " ٌّ"), + (0xFC5F, "3", " ٍّ"), + (0xFC60, "3", " َّ"), + (0xFC61, "3", " ُّ"), + (0xFC62, "3", " ِّ"), + (0xFC63, "3", " ّٰ"), + (0xFC64, "M", "ئر"), + (0xFC65, "M", "ئز"), + (0xFC66, "M", "ئم"), + (0xFC67, "M", "ئن"), + (0xFC68, "M", "ئى"), + (0xFC69, "M", "ئي"), + (0xFC6A, "M", "بر"), + (0xFC6B, "M", "بز"), + (0xFC6C, "M", "بم"), + (0xFC6D, "M", "بن"), + (0xFC6E, "M", "بى"), + (0xFC6F, "M", "بي"), + (0xFC70, "M", "تر"), + (0xFC71, "M", "تز"), + (0xFC72, "M", "تم"), + (0xFC73, "M", "تن"), + (0xFC74, "M", "تى"), + (0xFC75, "M", "تي"), + (0xFC76, "M", "ثر"), + (0xFC77, "M", "ثز"), + (0xFC78, "M", "ثم"), + (0xFC79, "M", "ثن"), + (0xFC7A, "M", "ثى"), + (0xFC7B, "M", "ثي"), + (0xFC7C, "M", "فى"), + (0xFC7D, "M", "في"), + (0xFC7E, "M", "قى"), + (0xFC7F, "M", "قي"), + (0xFC80, "M", "كا"), + (0xFC81, "M", "كل"), + (0xFC82, "M", "كم"), + (0xFC83, "M", "كى"), + (0xFC84, "M", "كي"), + (0xFC85, "M", "لم"), + (0xFC86, "M", "لى"), + (0xFC87, "M", "لي"), + (0xFC88, "M", "ما"), + (0xFC89, "M", "مم"), + (0xFC8A, "M", "نر"), + (0xFC8B, "M", "نز"), + (0xFC8C, "M", "نم"), + (0xFC8D, "M", "نن"), + (0xFC8E, "M", "نى"), + (0xFC8F, "M", "ني"), + (0xFC90, "M", "ىٰ"), + (0xFC91, "M", "ير"), + (0xFC92, "M", "يز"), + (0xFC93, "M", "يم"), + (0xFC94, "M", "ين"), + (0xFC95, "M", "يى"), + (0xFC96, "M", "يي"), + (0xFC97, "M", "ئج"), + (0xFC98, "M", "ئح"), + (0xFC99, "M", "ئخ"), + (0xFC9A, "M", "ئم"), + (0xFC9B, "M", "ئه"), + (0xFC9C, "M", "بج"), + (0xFC9D, "M", "بح"), + (0xFC9E, "M", "بخ"), + (0xFC9F, "M", "بم"), + (0xFCA0, "M", "به"), + (0xFCA1, "M", "تج"), + (0xFCA2, "M", "تح"), + (0xFCA3, "M", "تخ"), + (0xFCA4, "M", "تم"), + (0xFCA5, "M", "ته"), + (0xFCA6, "M", "ثم"), + (0xFCA7, "M", "جح"), + (0xFCA8, "M", "جم"), + (0xFCA9, "M", "حج"), + (0xFCAA, "M", "حم"), + (0xFCAB, "M", "خج"), + (0xFCAC, "M", "خم"), + (0xFCAD, "M", "سج"), + (0xFCAE, "M", "سح"), + (0xFCAF, "M", "سخ"), + (0xFCB0, "M", "سم"), + (0xFCB1, "M", "صح"), + (0xFCB2, "M", "صخ"), + (0xFCB3, "M", "صم"), + (0xFCB4, "M", "ضج"), + (0xFCB5, "M", "ضح"), + (0xFCB6, "M", "ضخ"), + (0xFCB7, "M", "ضم"), + (0xFCB8, "M", "طح"), + (0xFCB9, "M", "ظم"), + (0xFCBA, "M", "عج"), + (0xFCBB, "M", "عم"), + (0xFCBC, "M", "غج"), + (0xFCBD, "M", "غم"), + (0xFCBE, "M", "فج"), + ] + + +def _seg_47() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFCBF, "M", "فح"), + (0xFCC0, "M", "فخ"), + (0xFCC1, "M", "فم"), + (0xFCC2, "M", "قح"), + (0xFCC3, "M", "قم"), + (0xFCC4, "M", "كج"), + (0xFCC5, "M", "كح"), + (0xFCC6, "M", "كخ"), + (0xFCC7, "M", "كل"), + (0xFCC8, "M", "كم"), + (0xFCC9, "M", "لج"), + (0xFCCA, "M", "لح"), + (0xFCCB, "M", "لخ"), + (0xFCCC, "M", "لم"), + (0xFCCD, "M", "له"), + (0xFCCE, "M", "مج"), + (0xFCCF, "M", "مح"), + (0xFCD0, "M", "مخ"), + (0xFCD1, "M", "مم"), + (0xFCD2, "M", "نج"), + (0xFCD3, "M", "نح"), + (0xFCD4, "M", "نخ"), + (0xFCD5, "M", "نم"), + (0xFCD6, "M", "نه"), + (0xFCD7, "M", "هج"), + (0xFCD8, "M", "هم"), + (0xFCD9, "M", "هٰ"), + (0xFCDA, "M", "يج"), + (0xFCDB, "M", "يح"), + (0xFCDC, "M", "يخ"), + (0xFCDD, "M", "يم"), + (0xFCDE, "M", "يه"), + (0xFCDF, "M", "ئم"), + (0xFCE0, "M", "ئه"), + (0xFCE1, "M", "بم"), + (0xFCE2, "M", "به"), + (0xFCE3, "M", "تم"), + (0xFCE4, "M", "ته"), + (0xFCE5, "M", "ثم"), + (0xFCE6, "M", "ثه"), + (0xFCE7, "M", "سم"), + (0xFCE8, "M", "سه"), + (0xFCE9, "M", "شم"), + (0xFCEA, "M", "شه"), + (0xFCEB, "M", "كل"), + (0xFCEC, "M", "كم"), + (0xFCED, "M", "لم"), + (0xFCEE, "M", "نم"), + (0xFCEF, "M", "نه"), + (0xFCF0, "M", "يم"), + (0xFCF1, "M", "يه"), + (0xFCF2, "M", "ـَّ"), + (0xFCF3, "M", "ـُّ"), + (0xFCF4, "M", "ـِّ"), + (0xFCF5, "M", "طى"), + (0xFCF6, "M", "طي"), + (0xFCF7, "M", "عى"), + (0xFCF8, "M", "عي"), + (0xFCF9, "M", "غى"), + (0xFCFA, "M", "غي"), + (0xFCFB, "M", "سى"), + (0xFCFC, "M", "سي"), + (0xFCFD, "M", "شى"), + (0xFCFE, "M", "شي"), + (0xFCFF, "M", "حى"), + (0xFD00, "M", "حي"), + (0xFD01, "M", "جى"), + (0xFD02, "M", "جي"), + (0xFD03, "M", "خى"), + (0xFD04, "M", "خي"), + (0xFD05, "M", "صى"), + (0xFD06, "M", "صي"), + (0xFD07, "M", "ضى"), + (0xFD08, "M", "ضي"), + (0xFD09, "M", "شج"), + (0xFD0A, "M", "شح"), + (0xFD0B, "M", "شخ"), + (0xFD0C, "M", "شم"), + (0xFD0D, "M", "شر"), + (0xFD0E, "M", "سر"), + (0xFD0F, "M", "صر"), + (0xFD10, "M", "ضر"), + (0xFD11, "M", "طى"), + (0xFD12, "M", "طي"), + (0xFD13, "M", "عى"), + (0xFD14, "M", "عي"), + (0xFD15, "M", "غى"), + (0xFD16, "M", "غي"), + (0xFD17, "M", "سى"), + (0xFD18, "M", "سي"), + (0xFD19, "M", "شى"), + (0xFD1A, "M", "شي"), + (0xFD1B, "M", "حى"), + (0xFD1C, "M", "حي"), + (0xFD1D, "M", "جى"), + (0xFD1E, "M", "جي"), + (0xFD1F, "M", "خى"), + (0xFD20, "M", "خي"), + (0xFD21, "M", "صى"), + (0xFD22, "M", "صي"), + ] + + +def _seg_48() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFD23, "M", "ضى"), + (0xFD24, "M", "ضي"), + (0xFD25, "M", "شج"), + (0xFD26, "M", "شح"), + (0xFD27, "M", "شخ"), + (0xFD28, "M", "شم"), + (0xFD29, "M", "شر"), + (0xFD2A, "M", "سر"), + (0xFD2B, "M", "صر"), + (0xFD2C, "M", "ضر"), + (0xFD2D, "M", "شج"), + (0xFD2E, "M", "شح"), + (0xFD2F, "M", "شخ"), + (0xFD30, "M", "شم"), + (0xFD31, "M", "سه"), + (0xFD32, "M", "شه"), + (0xFD33, "M", "طم"), + (0xFD34, "M", "سج"), + (0xFD35, "M", "سح"), + (0xFD36, "M", "سخ"), + (0xFD37, "M", "شج"), + (0xFD38, "M", "شح"), + (0xFD39, "M", "شخ"), + (0xFD3A, "M", "طم"), + (0xFD3B, "M", "ظم"), + (0xFD3C, "M", "اً"), + (0xFD3E, "V"), + (0xFD50, "M", "تجم"), + (0xFD51, "M", "تحج"), + (0xFD53, "M", "تحم"), + (0xFD54, "M", "تخم"), + (0xFD55, "M", "تمج"), + (0xFD56, "M", "تمح"), + (0xFD57, "M", "تمخ"), + (0xFD58, "M", "جمح"), + (0xFD5A, "M", "حمي"), + (0xFD5B, "M", "حمى"), + (0xFD5C, "M", "سحج"), + (0xFD5D, "M", "سجح"), + (0xFD5E, "M", "سجى"), + (0xFD5F, "M", "سمح"), + (0xFD61, "M", "سمج"), + (0xFD62, "M", "سمم"), + (0xFD64, "M", "صحح"), + (0xFD66, "M", "صمم"), + (0xFD67, "M", "شحم"), + (0xFD69, "M", "شجي"), + (0xFD6A, "M", "شمخ"), + (0xFD6C, "M", "شمم"), + (0xFD6E, "M", "ضحى"), + (0xFD6F, "M", "ضخم"), + (0xFD71, "M", "طمح"), + (0xFD73, "M", "طمم"), + (0xFD74, "M", "طمي"), + (0xFD75, "M", "عجم"), + (0xFD76, "M", "عمم"), + (0xFD78, "M", "عمى"), + (0xFD79, "M", "غمم"), + (0xFD7A, "M", "غمي"), + (0xFD7B, "M", "غمى"), + (0xFD7C, "M", "فخم"), + (0xFD7E, "M", "قمح"), + (0xFD7F, "M", "قمم"), + (0xFD80, "M", "لحم"), + (0xFD81, "M", "لحي"), + (0xFD82, "M", "لحى"), + (0xFD83, "M", "لجج"), + (0xFD85, "M", "لخم"), + (0xFD87, "M", "لمح"), + (0xFD89, "M", "محج"), + (0xFD8A, "M", "محم"), + (0xFD8B, "M", "محي"), + (0xFD8C, "M", "مجح"), + (0xFD8D, "M", "مجم"), + (0xFD8E, "M", "مخج"), + (0xFD8F, "M", "مخم"), + (0xFD90, "X"), + (0xFD92, "M", "مجخ"), + (0xFD93, "M", "همج"), + (0xFD94, "M", "همم"), + (0xFD95, "M", "نحم"), + (0xFD96, "M", "نحى"), + (0xFD97, "M", "نجم"), + (0xFD99, "M", "نجى"), + (0xFD9A, "M", "نمي"), + (0xFD9B, "M", "نمى"), + (0xFD9C, "M", "يمم"), + (0xFD9E, "M", "بخي"), + (0xFD9F, "M", "تجي"), + (0xFDA0, "M", "تجى"), + (0xFDA1, "M", "تخي"), + (0xFDA2, "M", "تخى"), + (0xFDA3, "M", "تمي"), + (0xFDA4, "M", "تمى"), + (0xFDA5, "M", "جمي"), + (0xFDA6, "M", "جحى"), + (0xFDA7, "M", "جمى"), + (0xFDA8, "M", "سخى"), + (0xFDA9, "M", "صحي"), + (0xFDAA, "M", "شحي"), + ] + + +def _seg_49() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFDAB, "M", "ضحي"), + (0xFDAC, "M", "لجي"), + (0xFDAD, "M", "لمي"), + (0xFDAE, "M", "يحي"), + (0xFDAF, "M", "يجي"), + (0xFDB0, "M", "يمي"), + (0xFDB1, "M", "ممي"), + (0xFDB2, "M", "قمي"), + (0xFDB3, "M", "نحي"), + (0xFDB4, "M", "قمح"), + (0xFDB5, "M", "لحم"), + (0xFDB6, "M", "عمي"), + (0xFDB7, "M", "كمي"), + (0xFDB8, "M", "نجح"), + (0xFDB9, "M", "مخي"), + (0xFDBA, "M", "لجم"), + (0xFDBB, "M", "كمم"), + (0xFDBC, "M", "لجم"), + (0xFDBD, "M", "نجح"), + (0xFDBE, "M", "جحي"), + (0xFDBF, "M", "حجي"), + (0xFDC0, "M", "مجي"), + (0xFDC1, "M", "فمي"), + (0xFDC2, "M", "بحي"), + (0xFDC3, "M", "كمم"), + (0xFDC4, "M", "عجم"), + (0xFDC5, "M", "صمم"), + (0xFDC6, "M", "سخي"), + (0xFDC7, "M", "نجي"), + (0xFDC8, "X"), + (0xFDCF, "V"), + (0xFDD0, "X"), + (0xFDF0, "M", "صلے"), + (0xFDF1, "M", "قلے"), + (0xFDF2, "M", "الله"), + (0xFDF3, "M", "اكبر"), + (0xFDF4, "M", "محمد"), + (0xFDF5, "M", "صلعم"), + (0xFDF6, "M", "رسول"), + (0xFDF7, "M", "عليه"), + (0xFDF8, "M", "وسلم"), + (0xFDF9, "M", "صلى"), + (0xFDFA, "3", "صلى الله عليه وسلم"), + (0xFDFB, "3", "جل جلاله"), + (0xFDFC, "M", "ریال"), + (0xFDFD, "V"), + (0xFE00, "I"), + (0xFE10, "3", ","), + (0xFE11, "M", "、"), + (0xFE12, "X"), + (0xFE13, "3", ":"), + (0xFE14, "3", ";"), + (0xFE15, "3", "!"), + (0xFE16, "3", "?"), + (0xFE17, "M", "〖"), + (0xFE18, "M", "〗"), + (0xFE19, "X"), + (0xFE20, "V"), + (0xFE30, "X"), + (0xFE31, "M", "—"), + (0xFE32, "M", "–"), + (0xFE33, "3", "_"), + (0xFE35, "3", "("), + (0xFE36, "3", ")"), + (0xFE37, "3", "{"), + (0xFE38, "3", "}"), + (0xFE39, "M", "〔"), + (0xFE3A, "M", "〕"), + (0xFE3B, "M", "【"), + (0xFE3C, "M", "】"), + (0xFE3D, "M", "《"), + (0xFE3E, "M", "》"), + (0xFE3F, "M", "〈"), + (0xFE40, "M", "〉"), + (0xFE41, "M", "「"), + (0xFE42, "M", "」"), + (0xFE43, "M", "『"), + (0xFE44, "M", "』"), + (0xFE45, "V"), + (0xFE47, "3", "["), + (0xFE48, "3", "]"), + (0xFE49, "3", " ̅"), + (0xFE4D, "3", "_"), + (0xFE50, "3", ","), + (0xFE51, "M", "、"), + (0xFE52, "X"), + (0xFE54, "3", ";"), + (0xFE55, "3", ":"), + (0xFE56, "3", "?"), + (0xFE57, "3", "!"), + (0xFE58, "M", "—"), + (0xFE59, "3", "("), + (0xFE5A, "3", ")"), + (0xFE5B, "3", "{"), + (0xFE5C, "3", "}"), + (0xFE5D, "M", "〔"), + (0xFE5E, "M", "〕"), + (0xFE5F, "3", "#"), + (0xFE60, "3", "&"), + (0xFE61, "3", "*"), + ] + + +def _seg_50() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFE62, "3", "+"), + (0xFE63, "M", "-"), + (0xFE64, "3", "<"), + (0xFE65, "3", ">"), + (0xFE66, "3", "="), + (0xFE67, "X"), + (0xFE68, "3", "\\"), + (0xFE69, "3", "$"), + (0xFE6A, "3", "%"), + (0xFE6B, "3", "@"), + (0xFE6C, "X"), + (0xFE70, "3", " ً"), + (0xFE71, "M", "ـً"), + (0xFE72, "3", " ٌ"), + (0xFE73, "V"), + (0xFE74, "3", " ٍ"), + (0xFE75, "X"), + (0xFE76, "3", " َ"), + (0xFE77, "M", "ـَ"), + (0xFE78, "3", " ُ"), + (0xFE79, "M", "ـُ"), + (0xFE7A, "3", " ِ"), + (0xFE7B, "M", "ـِ"), + (0xFE7C, "3", " ّ"), + (0xFE7D, "M", "ـّ"), + (0xFE7E, "3", " ْ"), + (0xFE7F, "M", "ـْ"), + (0xFE80, "M", "ء"), + (0xFE81, "M", "آ"), + (0xFE83, "M", "أ"), + (0xFE85, "M", "ؤ"), + (0xFE87, "M", "إ"), + (0xFE89, "M", "ئ"), + (0xFE8D, "M", "ا"), + (0xFE8F, "M", "ب"), + (0xFE93, "M", "ة"), + (0xFE95, "M", "ت"), + (0xFE99, "M", "ث"), + (0xFE9D, "M", "ج"), + (0xFEA1, "M", "ح"), + (0xFEA5, "M", "خ"), + (0xFEA9, "M", "د"), + (0xFEAB, "M", "ذ"), + (0xFEAD, "M", "ر"), + (0xFEAF, "M", "ز"), + (0xFEB1, "M", "س"), + (0xFEB5, "M", "ش"), + (0xFEB9, "M", "ص"), + (0xFEBD, "M", "ض"), + (0xFEC1, "M", "ط"), + (0xFEC5, "M", "ظ"), + (0xFEC9, "M", "ع"), + (0xFECD, "M", "غ"), + (0xFED1, "M", "ف"), + (0xFED5, "M", "ق"), + (0xFED9, "M", "ك"), + (0xFEDD, "M", "ل"), + (0xFEE1, "M", "م"), + (0xFEE5, "M", "ن"), + (0xFEE9, "M", "ه"), + (0xFEED, "M", "و"), + (0xFEEF, "M", "ى"), + (0xFEF1, "M", "ي"), + (0xFEF5, "M", "لآ"), + (0xFEF7, "M", "لأ"), + (0xFEF9, "M", "لإ"), + (0xFEFB, "M", "لا"), + (0xFEFD, "X"), + (0xFEFF, "I"), + (0xFF00, "X"), + (0xFF01, "3", "!"), + (0xFF02, "3", '"'), + (0xFF03, "3", "#"), + (0xFF04, "3", "$"), + (0xFF05, "3", "%"), + (0xFF06, "3", "&"), + (0xFF07, "3", "'"), + (0xFF08, "3", "("), + (0xFF09, "3", ")"), + (0xFF0A, "3", "*"), + (0xFF0B, "3", "+"), + (0xFF0C, "3", ","), + (0xFF0D, "M", "-"), + (0xFF0E, "M", "."), + (0xFF0F, "3", "/"), + (0xFF10, "M", "0"), + (0xFF11, "M", "1"), + (0xFF12, "M", "2"), + (0xFF13, "M", "3"), + (0xFF14, "M", "4"), + (0xFF15, "M", "5"), + (0xFF16, "M", "6"), + (0xFF17, "M", "7"), + (0xFF18, "M", "8"), + (0xFF19, "M", "9"), + (0xFF1A, "3", ":"), + (0xFF1B, "3", ";"), + (0xFF1C, "3", "<"), + (0xFF1D, "3", "="), + (0xFF1E, "3", ">"), + ] + + +def _seg_51() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFF1F, "3", "?"), + (0xFF20, "3", "@"), + (0xFF21, "M", "a"), + (0xFF22, "M", "b"), + (0xFF23, "M", "c"), + (0xFF24, "M", "d"), + (0xFF25, "M", "e"), + (0xFF26, "M", "f"), + (0xFF27, "M", "g"), + (0xFF28, "M", "h"), + (0xFF29, "M", "i"), + (0xFF2A, "M", "j"), + (0xFF2B, "M", "k"), + (0xFF2C, "M", "l"), + (0xFF2D, "M", "m"), + (0xFF2E, "M", "n"), + (0xFF2F, "M", "o"), + (0xFF30, "M", "p"), + (0xFF31, "M", "q"), + (0xFF32, "M", "r"), + (0xFF33, "M", "s"), + (0xFF34, "M", "t"), + (0xFF35, "M", "u"), + (0xFF36, "M", "v"), + (0xFF37, "M", "w"), + (0xFF38, "M", "x"), + (0xFF39, "M", "y"), + (0xFF3A, "M", "z"), + (0xFF3B, "3", "["), + (0xFF3C, "3", "\\"), + (0xFF3D, "3", "]"), + (0xFF3E, "3", "^"), + (0xFF3F, "3", "_"), + (0xFF40, "3", "`"), + (0xFF41, "M", "a"), + (0xFF42, "M", "b"), + (0xFF43, "M", "c"), + (0xFF44, "M", "d"), + (0xFF45, "M", "e"), + (0xFF46, "M", "f"), + (0xFF47, "M", "g"), + (0xFF48, "M", "h"), + (0xFF49, "M", "i"), + (0xFF4A, "M", "j"), + (0xFF4B, "M", "k"), + (0xFF4C, "M", "l"), + (0xFF4D, "M", "m"), + (0xFF4E, "M", "n"), + (0xFF4F, "M", "o"), + (0xFF50, "M", "p"), + (0xFF51, "M", "q"), + (0xFF52, "M", "r"), + (0xFF53, "M", "s"), + (0xFF54, "M", "t"), + (0xFF55, "M", "u"), + (0xFF56, "M", "v"), + (0xFF57, "M", "w"), + (0xFF58, "M", "x"), + (0xFF59, "M", "y"), + (0xFF5A, "M", "z"), + (0xFF5B, "3", "{"), + (0xFF5C, "3", "|"), + (0xFF5D, "3", "}"), + (0xFF5E, "3", "~"), + (0xFF5F, "M", "⦅"), + (0xFF60, "M", "⦆"), + (0xFF61, "M", "."), + (0xFF62, "M", "「"), + (0xFF63, "M", "」"), + (0xFF64, "M", "、"), + (0xFF65, "M", "・"), + (0xFF66, "M", "ヲ"), + (0xFF67, "M", "ァ"), + (0xFF68, "M", "ィ"), + (0xFF69, "M", "ゥ"), + (0xFF6A, "M", "ェ"), + (0xFF6B, "M", "ォ"), + (0xFF6C, "M", "ャ"), + (0xFF6D, "M", "ュ"), + (0xFF6E, "M", "ョ"), + (0xFF6F, "M", "ッ"), + (0xFF70, "M", "ー"), + (0xFF71, "M", "ア"), + (0xFF72, "M", "イ"), + (0xFF73, "M", "ウ"), + (0xFF74, "M", "エ"), + (0xFF75, "M", "オ"), + (0xFF76, "M", "カ"), + (0xFF77, "M", "キ"), + (0xFF78, "M", "ク"), + (0xFF79, "M", "ケ"), + (0xFF7A, "M", "コ"), + (0xFF7B, "M", "サ"), + (0xFF7C, "M", "シ"), + (0xFF7D, "M", "ス"), + (0xFF7E, "M", "セ"), + (0xFF7F, "M", "ソ"), + (0xFF80, "M", "タ"), + (0xFF81, "M", "チ"), + (0xFF82, "M", "ツ"), + ] + + +def _seg_52() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFF83, "M", "テ"), + (0xFF84, "M", "ト"), + (0xFF85, "M", "ナ"), + (0xFF86, "M", "ニ"), + (0xFF87, "M", "ヌ"), + (0xFF88, "M", "ネ"), + (0xFF89, "M", "ノ"), + (0xFF8A, "M", "ハ"), + (0xFF8B, "M", "ヒ"), + (0xFF8C, "M", "フ"), + (0xFF8D, "M", "ヘ"), + (0xFF8E, "M", "ホ"), + (0xFF8F, "M", "マ"), + (0xFF90, "M", "ミ"), + (0xFF91, "M", "ム"), + (0xFF92, "M", "メ"), + (0xFF93, "M", "モ"), + (0xFF94, "M", "ヤ"), + (0xFF95, "M", "ユ"), + (0xFF96, "M", "ヨ"), + (0xFF97, "M", "ラ"), + (0xFF98, "M", "リ"), + (0xFF99, "M", "ル"), + (0xFF9A, "M", "レ"), + (0xFF9B, "M", "ロ"), + (0xFF9C, "M", "ワ"), + (0xFF9D, "M", "ン"), + (0xFF9E, "M", "゙"), + (0xFF9F, "M", "゚"), + (0xFFA0, "X"), + (0xFFA1, "M", "ᄀ"), + (0xFFA2, "M", "ᄁ"), + (0xFFA3, "M", "ᆪ"), + (0xFFA4, "M", "ᄂ"), + (0xFFA5, "M", "ᆬ"), + (0xFFA6, "M", "ᆭ"), + (0xFFA7, "M", "ᄃ"), + (0xFFA8, "M", "ᄄ"), + (0xFFA9, "M", "ᄅ"), + (0xFFAA, "M", "ᆰ"), + (0xFFAB, "M", "ᆱ"), + (0xFFAC, "M", "ᆲ"), + (0xFFAD, "M", "ᆳ"), + (0xFFAE, "M", "ᆴ"), + (0xFFAF, "M", "ᆵ"), + (0xFFB0, "M", "ᄚ"), + (0xFFB1, "M", "ᄆ"), + (0xFFB2, "M", "ᄇ"), + (0xFFB3, "M", "ᄈ"), + (0xFFB4, "M", "ᄡ"), + (0xFFB5, "M", "ᄉ"), + (0xFFB6, "M", "ᄊ"), + (0xFFB7, "M", "ᄋ"), + (0xFFB8, "M", "ᄌ"), + (0xFFB9, "M", "ᄍ"), + (0xFFBA, "M", "ᄎ"), + (0xFFBB, "M", "ᄏ"), + (0xFFBC, "M", "ᄐ"), + (0xFFBD, "M", "ᄑ"), + (0xFFBE, "M", "ᄒ"), + (0xFFBF, "X"), + (0xFFC2, "M", "ᅡ"), + (0xFFC3, "M", "ᅢ"), + (0xFFC4, "M", "ᅣ"), + (0xFFC5, "M", "ᅤ"), + (0xFFC6, "M", "ᅥ"), + (0xFFC7, "M", "ᅦ"), + (0xFFC8, "X"), + (0xFFCA, "M", "ᅧ"), + (0xFFCB, "M", "ᅨ"), + (0xFFCC, "M", "ᅩ"), + (0xFFCD, "M", "ᅪ"), + (0xFFCE, "M", "ᅫ"), + (0xFFCF, "M", "ᅬ"), + (0xFFD0, "X"), + (0xFFD2, "M", "ᅭ"), + (0xFFD3, "M", "ᅮ"), + (0xFFD4, "M", "ᅯ"), + (0xFFD5, "M", "ᅰ"), + (0xFFD6, "M", "ᅱ"), + (0xFFD7, "M", "ᅲ"), + (0xFFD8, "X"), + (0xFFDA, "M", "ᅳ"), + (0xFFDB, "M", "ᅴ"), + (0xFFDC, "M", "ᅵ"), + (0xFFDD, "X"), + (0xFFE0, "M", "¢"), + (0xFFE1, "M", "£"), + (0xFFE2, "M", "¬"), + (0xFFE3, "3", " ̄"), + (0xFFE4, "M", "¦"), + (0xFFE5, "M", "¥"), + (0xFFE6, "M", "₩"), + (0xFFE7, "X"), + (0xFFE8, "M", "│"), + (0xFFE9, "M", "←"), + (0xFFEA, "M", "↑"), + (0xFFEB, "M", "→"), + (0xFFEC, "M", "↓"), + (0xFFED, "M", "■"), + ] + + +def _seg_53() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0xFFEE, "M", "○"), + (0xFFEF, "X"), + (0x10000, "V"), + (0x1000C, "X"), + (0x1000D, "V"), + (0x10027, "X"), + (0x10028, "V"), + (0x1003B, "X"), + (0x1003C, "V"), + (0x1003E, "X"), + (0x1003F, "V"), + (0x1004E, "X"), + (0x10050, "V"), + (0x1005E, "X"), + (0x10080, "V"), + (0x100FB, "X"), + (0x10100, "V"), + (0x10103, "X"), + (0x10107, "V"), + (0x10134, "X"), + (0x10137, "V"), + (0x1018F, "X"), + (0x10190, "V"), + (0x1019D, "X"), + (0x101A0, "V"), + (0x101A1, "X"), + (0x101D0, "V"), + (0x101FE, "X"), + (0x10280, "V"), + (0x1029D, "X"), + (0x102A0, "V"), + (0x102D1, "X"), + (0x102E0, "V"), + (0x102FC, "X"), + (0x10300, "V"), + (0x10324, "X"), + (0x1032D, "V"), + (0x1034B, "X"), + (0x10350, "V"), + (0x1037B, "X"), + (0x10380, "V"), + (0x1039E, "X"), + (0x1039F, "V"), + (0x103C4, "X"), + (0x103C8, "V"), + (0x103D6, "X"), + (0x10400, "M", "𐐨"), + (0x10401, "M", "𐐩"), + (0x10402, "M", "𐐪"), + (0x10403, "M", "𐐫"), + (0x10404, "M", "𐐬"), + (0x10405, "M", "𐐭"), + (0x10406, "M", "𐐮"), + (0x10407, "M", "𐐯"), + (0x10408, "M", "𐐰"), + (0x10409, "M", "𐐱"), + (0x1040A, "M", "𐐲"), + (0x1040B, "M", "𐐳"), + (0x1040C, "M", "𐐴"), + (0x1040D, "M", "𐐵"), + (0x1040E, "M", "𐐶"), + (0x1040F, "M", "𐐷"), + (0x10410, "M", "𐐸"), + (0x10411, "M", "𐐹"), + (0x10412, "M", "𐐺"), + (0x10413, "M", "𐐻"), + (0x10414, "M", "𐐼"), + (0x10415, "M", "𐐽"), + (0x10416, "M", "𐐾"), + (0x10417, "M", "𐐿"), + (0x10418, "M", "𐑀"), + (0x10419, "M", "𐑁"), + (0x1041A, "M", "𐑂"), + (0x1041B, "M", "𐑃"), + (0x1041C, "M", "𐑄"), + (0x1041D, "M", "𐑅"), + (0x1041E, "M", "𐑆"), + (0x1041F, "M", "𐑇"), + (0x10420, "M", "𐑈"), + (0x10421, "M", "𐑉"), + (0x10422, "M", "𐑊"), + (0x10423, "M", "𐑋"), + (0x10424, "M", "𐑌"), + (0x10425, "M", "𐑍"), + (0x10426, "M", "𐑎"), + (0x10427, "M", "𐑏"), + (0x10428, "V"), + (0x1049E, "X"), + (0x104A0, "V"), + (0x104AA, "X"), + (0x104B0, "M", "𐓘"), + (0x104B1, "M", "𐓙"), + (0x104B2, "M", "𐓚"), + (0x104B3, "M", "𐓛"), + (0x104B4, "M", "𐓜"), + (0x104B5, "M", "𐓝"), + (0x104B6, "M", "𐓞"), + (0x104B7, "M", "𐓟"), + (0x104B8, "M", "𐓠"), + (0x104B9, "M", "𐓡"), + ] + + +def _seg_54() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x104BA, "M", "𐓢"), + (0x104BB, "M", "𐓣"), + (0x104BC, "M", "𐓤"), + (0x104BD, "M", "𐓥"), + (0x104BE, "M", "𐓦"), + (0x104BF, "M", "𐓧"), + (0x104C0, "M", "𐓨"), + (0x104C1, "M", "𐓩"), + (0x104C2, "M", "𐓪"), + (0x104C3, "M", "𐓫"), + (0x104C4, "M", "𐓬"), + (0x104C5, "M", "𐓭"), + (0x104C6, "M", "𐓮"), + (0x104C7, "M", "𐓯"), + (0x104C8, "M", "𐓰"), + (0x104C9, "M", "𐓱"), + (0x104CA, "M", "𐓲"), + (0x104CB, "M", "𐓳"), + (0x104CC, "M", "𐓴"), + (0x104CD, "M", "𐓵"), + (0x104CE, "M", "𐓶"), + (0x104CF, "M", "𐓷"), + (0x104D0, "M", "𐓸"), + (0x104D1, "M", "𐓹"), + (0x104D2, "M", "𐓺"), + (0x104D3, "M", "𐓻"), + (0x104D4, "X"), + (0x104D8, "V"), + (0x104FC, "X"), + (0x10500, "V"), + (0x10528, "X"), + (0x10530, "V"), + (0x10564, "X"), + (0x1056F, "V"), + (0x10570, "M", "𐖗"), + (0x10571, "M", "𐖘"), + (0x10572, "M", "𐖙"), + (0x10573, "M", "𐖚"), + (0x10574, "M", "𐖛"), + (0x10575, "M", "𐖜"), + (0x10576, "M", "𐖝"), + (0x10577, "M", "𐖞"), + (0x10578, "M", "𐖟"), + (0x10579, "M", "𐖠"), + (0x1057A, "M", "𐖡"), + (0x1057B, "X"), + (0x1057C, "M", "𐖣"), + (0x1057D, "M", "𐖤"), + (0x1057E, "M", "𐖥"), + (0x1057F, "M", "𐖦"), + (0x10580, "M", "𐖧"), + (0x10581, "M", "𐖨"), + (0x10582, "M", "𐖩"), + (0x10583, "M", "𐖪"), + (0x10584, "M", "𐖫"), + (0x10585, "M", "𐖬"), + (0x10586, "M", "𐖭"), + (0x10587, "M", "𐖮"), + (0x10588, "M", "𐖯"), + (0x10589, "M", "𐖰"), + (0x1058A, "M", "𐖱"), + (0x1058B, "X"), + (0x1058C, "M", "𐖳"), + (0x1058D, "M", "𐖴"), + (0x1058E, "M", "𐖵"), + (0x1058F, "M", "𐖶"), + (0x10590, "M", "𐖷"), + (0x10591, "M", "𐖸"), + (0x10592, "M", "𐖹"), + (0x10593, "X"), + (0x10594, "M", "𐖻"), + (0x10595, "M", "𐖼"), + (0x10596, "X"), + (0x10597, "V"), + (0x105A2, "X"), + (0x105A3, "V"), + (0x105B2, "X"), + (0x105B3, "V"), + (0x105BA, "X"), + (0x105BB, "V"), + (0x105BD, "X"), + (0x10600, "V"), + (0x10737, "X"), + (0x10740, "V"), + (0x10756, "X"), + (0x10760, "V"), + (0x10768, "X"), + (0x10780, "V"), + (0x10781, "M", "ː"), + (0x10782, "M", "ˑ"), + (0x10783, "M", "æ"), + (0x10784, "M", "ʙ"), + (0x10785, "M", "ɓ"), + (0x10786, "X"), + (0x10787, "M", "ʣ"), + (0x10788, "M", "ꭦ"), + (0x10789, "M", "ʥ"), + (0x1078A, "M", "ʤ"), + (0x1078B, "M", "ɖ"), + (0x1078C, "M", "ɗ"), + ] + + +def _seg_55() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1078D, "M", "ᶑ"), + (0x1078E, "M", "ɘ"), + (0x1078F, "M", "ɞ"), + (0x10790, "M", "ʩ"), + (0x10791, "M", "ɤ"), + (0x10792, "M", "ɢ"), + (0x10793, "M", "ɠ"), + (0x10794, "M", "ʛ"), + (0x10795, "M", "ħ"), + (0x10796, "M", "ʜ"), + (0x10797, "M", "ɧ"), + (0x10798, "M", "ʄ"), + (0x10799, "M", "ʪ"), + (0x1079A, "M", "ʫ"), + (0x1079B, "M", "ɬ"), + (0x1079C, "M", "𝼄"), + (0x1079D, "M", "ꞎ"), + (0x1079E, "M", "ɮ"), + (0x1079F, "M", "𝼅"), + (0x107A0, "M", "ʎ"), + (0x107A1, "M", "𝼆"), + (0x107A2, "M", "ø"), + (0x107A3, "M", "ɶ"), + (0x107A4, "M", "ɷ"), + (0x107A5, "M", "q"), + (0x107A6, "M", "ɺ"), + (0x107A7, "M", "𝼈"), + (0x107A8, "M", "ɽ"), + (0x107A9, "M", "ɾ"), + (0x107AA, "M", "ʀ"), + (0x107AB, "M", "ʨ"), + (0x107AC, "M", "ʦ"), + (0x107AD, "M", "ꭧ"), + (0x107AE, "M", "ʧ"), + (0x107AF, "M", "ʈ"), + (0x107B0, "M", "ⱱ"), + (0x107B1, "X"), + (0x107B2, "M", "ʏ"), + (0x107B3, "M", "ʡ"), + (0x107B4, "M", "ʢ"), + (0x107B5, "M", "ʘ"), + (0x107B6, "M", "ǀ"), + (0x107B7, "M", "ǁ"), + (0x107B8, "M", "ǂ"), + (0x107B9, "M", "𝼊"), + (0x107BA, "M", "𝼞"), + (0x107BB, "X"), + (0x10800, "V"), + (0x10806, "X"), + (0x10808, "V"), + (0x10809, "X"), + (0x1080A, "V"), + (0x10836, "X"), + (0x10837, "V"), + (0x10839, "X"), + (0x1083C, "V"), + (0x1083D, "X"), + (0x1083F, "V"), + (0x10856, "X"), + (0x10857, "V"), + (0x1089F, "X"), + (0x108A7, "V"), + (0x108B0, "X"), + (0x108E0, "V"), + (0x108F3, "X"), + (0x108F4, "V"), + (0x108F6, "X"), + (0x108FB, "V"), + (0x1091C, "X"), + (0x1091F, "V"), + (0x1093A, "X"), + (0x1093F, "V"), + (0x10940, "X"), + (0x10980, "V"), + (0x109B8, "X"), + (0x109BC, "V"), + (0x109D0, "X"), + (0x109D2, "V"), + (0x10A04, "X"), + (0x10A05, "V"), + (0x10A07, "X"), + (0x10A0C, "V"), + (0x10A14, "X"), + (0x10A15, "V"), + (0x10A18, "X"), + (0x10A19, "V"), + (0x10A36, "X"), + (0x10A38, "V"), + (0x10A3B, "X"), + (0x10A3F, "V"), + (0x10A49, "X"), + (0x10A50, "V"), + (0x10A59, "X"), + (0x10A60, "V"), + (0x10AA0, "X"), + (0x10AC0, "V"), + (0x10AE7, "X"), + (0x10AEB, "V"), + (0x10AF7, "X"), + (0x10B00, "V"), + ] + + +def _seg_56() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x10B36, "X"), + (0x10B39, "V"), + (0x10B56, "X"), + (0x10B58, "V"), + (0x10B73, "X"), + (0x10B78, "V"), + (0x10B92, "X"), + (0x10B99, "V"), + (0x10B9D, "X"), + (0x10BA9, "V"), + (0x10BB0, "X"), + (0x10C00, "V"), + (0x10C49, "X"), + (0x10C80, "M", "𐳀"), + (0x10C81, "M", "𐳁"), + (0x10C82, "M", "𐳂"), + (0x10C83, "M", "𐳃"), + (0x10C84, "M", "𐳄"), + (0x10C85, "M", "𐳅"), + (0x10C86, "M", "𐳆"), + (0x10C87, "M", "𐳇"), + (0x10C88, "M", "𐳈"), + (0x10C89, "M", "𐳉"), + (0x10C8A, "M", "𐳊"), + (0x10C8B, "M", "𐳋"), + (0x10C8C, "M", "𐳌"), + (0x10C8D, "M", "𐳍"), + (0x10C8E, "M", "𐳎"), + (0x10C8F, "M", "𐳏"), + (0x10C90, "M", "𐳐"), + (0x10C91, "M", "𐳑"), + (0x10C92, "M", "𐳒"), + (0x10C93, "M", "𐳓"), + (0x10C94, "M", "𐳔"), + (0x10C95, "M", "𐳕"), + (0x10C96, "M", "𐳖"), + (0x10C97, "M", "𐳗"), + (0x10C98, "M", "𐳘"), + (0x10C99, "M", "𐳙"), + (0x10C9A, "M", "𐳚"), + (0x10C9B, "M", "𐳛"), + (0x10C9C, "M", "𐳜"), + (0x10C9D, "M", "𐳝"), + (0x10C9E, "M", "𐳞"), + (0x10C9F, "M", "𐳟"), + (0x10CA0, "M", "𐳠"), + (0x10CA1, "M", "𐳡"), + (0x10CA2, "M", "𐳢"), + (0x10CA3, "M", "𐳣"), + (0x10CA4, "M", "𐳤"), + (0x10CA5, "M", "𐳥"), + (0x10CA6, "M", "𐳦"), + (0x10CA7, "M", "𐳧"), + (0x10CA8, "M", "𐳨"), + (0x10CA9, "M", "𐳩"), + (0x10CAA, "M", "𐳪"), + (0x10CAB, "M", "𐳫"), + (0x10CAC, "M", "𐳬"), + (0x10CAD, "M", "𐳭"), + (0x10CAE, "M", "𐳮"), + (0x10CAF, "M", "𐳯"), + (0x10CB0, "M", "𐳰"), + (0x10CB1, "M", "𐳱"), + (0x10CB2, "M", "𐳲"), + (0x10CB3, "X"), + (0x10CC0, "V"), + (0x10CF3, "X"), + (0x10CFA, "V"), + (0x10D28, "X"), + (0x10D30, "V"), + (0x10D3A, "X"), + (0x10E60, "V"), + (0x10E7F, "X"), + (0x10E80, "V"), + (0x10EAA, "X"), + (0x10EAB, "V"), + (0x10EAE, "X"), + (0x10EB0, "V"), + (0x10EB2, "X"), + (0x10EFD, "V"), + (0x10F28, "X"), + (0x10F30, "V"), + (0x10F5A, "X"), + (0x10F70, "V"), + (0x10F8A, "X"), + (0x10FB0, "V"), + (0x10FCC, "X"), + (0x10FE0, "V"), + (0x10FF7, "X"), + (0x11000, "V"), + (0x1104E, "X"), + (0x11052, "V"), + (0x11076, "X"), + (0x1107F, "V"), + (0x110BD, "X"), + (0x110BE, "V"), + (0x110C3, "X"), + (0x110D0, "V"), + (0x110E9, "X"), + (0x110F0, "V"), + ] + + +def _seg_57() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x110FA, "X"), + (0x11100, "V"), + (0x11135, "X"), + (0x11136, "V"), + (0x11148, "X"), + (0x11150, "V"), + (0x11177, "X"), + (0x11180, "V"), + (0x111E0, "X"), + (0x111E1, "V"), + (0x111F5, "X"), + (0x11200, "V"), + (0x11212, "X"), + (0x11213, "V"), + (0x11242, "X"), + (0x11280, "V"), + (0x11287, "X"), + (0x11288, "V"), + (0x11289, "X"), + (0x1128A, "V"), + (0x1128E, "X"), + (0x1128F, "V"), + (0x1129E, "X"), + (0x1129F, "V"), + (0x112AA, "X"), + (0x112B0, "V"), + (0x112EB, "X"), + (0x112F0, "V"), + (0x112FA, "X"), + (0x11300, "V"), + (0x11304, "X"), + (0x11305, "V"), + (0x1130D, "X"), + (0x1130F, "V"), + (0x11311, "X"), + (0x11313, "V"), + (0x11329, "X"), + (0x1132A, "V"), + (0x11331, "X"), + (0x11332, "V"), + (0x11334, "X"), + (0x11335, "V"), + (0x1133A, "X"), + (0x1133B, "V"), + (0x11345, "X"), + (0x11347, "V"), + (0x11349, "X"), + (0x1134B, "V"), + (0x1134E, "X"), + (0x11350, "V"), + (0x11351, "X"), + (0x11357, "V"), + (0x11358, "X"), + (0x1135D, "V"), + (0x11364, "X"), + (0x11366, "V"), + (0x1136D, "X"), + (0x11370, "V"), + (0x11375, "X"), + (0x11400, "V"), + (0x1145C, "X"), + (0x1145D, "V"), + (0x11462, "X"), + (0x11480, "V"), + (0x114C8, "X"), + (0x114D0, "V"), + (0x114DA, "X"), + (0x11580, "V"), + (0x115B6, "X"), + (0x115B8, "V"), + (0x115DE, "X"), + (0x11600, "V"), + (0x11645, "X"), + (0x11650, "V"), + (0x1165A, "X"), + (0x11660, "V"), + (0x1166D, "X"), + (0x11680, "V"), + (0x116BA, "X"), + (0x116C0, "V"), + (0x116CA, "X"), + (0x11700, "V"), + (0x1171B, "X"), + (0x1171D, "V"), + (0x1172C, "X"), + (0x11730, "V"), + (0x11747, "X"), + (0x11800, "V"), + (0x1183C, "X"), + (0x118A0, "M", "𑣀"), + (0x118A1, "M", "𑣁"), + (0x118A2, "M", "𑣂"), + (0x118A3, "M", "𑣃"), + (0x118A4, "M", "𑣄"), + (0x118A5, "M", "𑣅"), + (0x118A6, "M", "𑣆"), + (0x118A7, "M", "𑣇"), + (0x118A8, "M", "𑣈"), + (0x118A9, "M", "𑣉"), + (0x118AA, "M", "𑣊"), + ] + + +def _seg_58() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x118AB, "M", "𑣋"), + (0x118AC, "M", "𑣌"), + (0x118AD, "M", "𑣍"), + (0x118AE, "M", "𑣎"), + (0x118AF, "M", "𑣏"), + (0x118B0, "M", "𑣐"), + (0x118B1, "M", "𑣑"), + (0x118B2, "M", "𑣒"), + (0x118B3, "M", "𑣓"), + (0x118B4, "M", "𑣔"), + (0x118B5, "M", "𑣕"), + (0x118B6, "M", "𑣖"), + (0x118B7, "M", "𑣗"), + (0x118B8, "M", "𑣘"), + (0x118B9, "M", "𑣙"), + (0x118BA, "M", "𑣚"), + (0x118BB, "M", "𑣛"), + (0x118BC, "M", "𑣜"), + (0x118BD, "M", "𑣝"), + (0x118BE, "M", "𑣞"), + (0x118BF, "M", "𑣟"), + (0x118C0, "V"), + (0x118F3, "X"), + (0x118FF, "V"), + (0x11907, "X"), + (0x11909, "V"), + (0x1190A, "X"), + (0x1190C, "V"), + (0x11914, "X"), + (0x11915, "V"), + (0x11917, "X"), + (0x11918, "V"), + (0x11936, "X"), + (0x11937, "V"), + (0x11939, "X"), + (0x1193B, "V"), + (0x11947, "X"), + (0x11950, "V"), + (0x1195A, "X"), + (0x119A0, "V"), + (0x119A8, "X"), + (0x119AA, "V"), + (0x119D8, "X"), + (0x119DA, "V"), + (0x119E5, "X"), + (0x11A00, "V"), + (0x11A48, "X"), + (0x11A50, "V"), + (0x11AA3, "X"), + (0x11AB0, "V"), + (0x11AF9, "X"), + (0x11B00, "V"), + (0x11B0A, "X"), + (0x11C00, "V"), + (0x11C09, "X"), + (0x11C0A, "V"), + (0x11C37, "X"), + (0x11C38, "V"), + (0x11C46, "X"), + (0x11C50, "V"), + (0x11C6D, "X"), + (0x11C70, "V"), + (0x11C90, "X"), + (0x11C92, "V"), + (0x11CA8, "X"), + (0x11CA9, "V"), + (0x11CB7, "X"), + (0x11D00, "V"), + (0x11D07, "X"), + (0x11D08, "V"), + (0x11D0A, "X"), + (0x11D0B, "V"), + (0x11D37, "X"), + (0x11D3A, "V"), + (0x11D3B, "X"), + (0x11D3C, "V"), + (0x11D3E, "X"), + (0x11D3F, "V"), + (0x11D48, "X"), + (0x11D50, "V"), + (0x11D5A, "X"), + (0x11D60, "V"), + (0x11D66, "X"), + (0x11D67, "V"), + (0x11D69, "X"), + (0x11D6A, "V"), + (0x11D8F, "X"), + (0x11D90, "V"), + (0x11D92, "X"), + (0x11D93, "V"), + (0x11D99, "X"), + (0x11DA0, "V"), + (0x11DAA, "X"), + (0x11EE0, "V"), + (0x11EF9, "X"), + (0x11F00, "V"), + (0x11F11, "X"), + (0x11F12, "V"), + (0x11F3B, "X"), + (0x11F3E, "V"), + ] + + +def _seg_59() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x11F5A, "X"), + (0x11FB0, "V"), + (0x11FB1, "X"), + (0x11FC0, "V"), + (0x11FF2, "X"), + (0x11FFF, "V"), + (0x1239A, "X"), + (0x12400, "V"), + (0x1246F, "X"), + (0x12470, "V"), + (0x12475, "X"), + (0x12480, "V"), + (0x12544, "X"), + (0x12F90, "V"), + (0x12FF3, "X"), + (0x13000, "V"), + (0x13430, "X"), + (0x13440, "V"), + (0x13456, "X"), + (0x14400, "V"), + (0x14647, "X"), + (0x16800, "V"), + (0x16A39, "X"), + (0x16A40, "V"), + (0x16A5F, "X"), + (0x16A60, "V"), + (0x16A6A, "X"), + (0x16A6E, "V"), + (0x16ABF, "X"), + (0x16AC0, "V"), + (0x16ACA, "X"), + (0x16AD0, "V"), + (0x16AEE, "X"), + (0x16AF0, "V"), + (0x16AF6, "X"), + (0x16B00, "V"), + (0x16B46, "X"), + (0x16B50, "V"), + (0x16B5A, "X"), + (0x16B5B, "V"), + (0x16B62, "X"), + (0x16B63, "V"), + (0x16B78, "X"), + (0x16B7D, "V"), + (0x16B90, "X"), + (0x16E40, "M", "𖹠"), + (0x16E41, "M", "𖹡"), + (0x16E42, "M", "𖹢"), + (0x16E43, "M", "𖹣"), + (0x16E44, "M", "𖹤"), + (0x16E45, "M", "𖹥"), + (0x16E46, "M", "𖹦"), + (0x16E47, "M", "𖹧"), + (0x16E48, "M", "𖹨"), + (0x16E49, "M", "𖹩"), + (0x16E4A, "M", "𖹪"), + (0x16E4B, "M", "𖹫"), + (0x16E4C, "M", "𖹬"), + (0x16E4D, "M", "𖹭"), + (0x16E4E, "M", "𖹮"), + (0x16E4F, "M", "𖹯"), + (0x16E50, "M", "𖹰"), + (0x16E51, "M", "𖹱"), + (0x16E52, "M", "𖹲"), + (0x16E53, "M", "𖹳"), + (0x16E54, "M", "𖹴"), + (0x16E55, "M", "𖹵"), + (0x16E56, "M", "𖹶"), + (0x16E57, "M", "𖹷"), + (0x16E58, "M", "𖹸"), + (0x16E59, "M", "𖹹"), + (0x16E5A, "M", "𖹺"), + (0x16E5B, "M", "𖹻"), + (0x16E5C, "M", "𖹼"), + (0x16E5D, "M", "𖹽"), + (0x16E5E, "M", "𖹾"), + (0x16E5F, "M", "𖹿"), + (0x16E60, "V"), + (0x16E9B, "X"), + (0x16F00, "V"), + (0x16F4B, "X"), + (0x16F4F, "V"), + (0x16F88, "X"), + (0x16F8F, "V"), + (0x16FA0, "X"), + (0x16FE0, "V"), + (0x16FE5, "X"), + (0x16FF0, "V"), + (0x16FF2, "X"), + (0x17000, "V"), + (0x187F8, "X"), + (0x18800, "V"), + (0x18CD6, "X"), + (0x18D00, "V"), + (0x18D09, "X"), + (0x1AFF0, "V"), + (0x1AFF4, "X"), + (0x1AFF5, "V"), + (0x1AFFC, "X"), + (0x1AFFD, "V"), + ] + + +def _seg_60() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1AFFF, "X"), + (0x1B000, "V"), + (0x1B123, "X"), + (0x1B132, "V"), + (0x1B133, "X"), + (0x1B150, "V"), + (0x1B153, "X"), + (0x1B155, "V"), + (0x1B156, "X"), + (0x1B164, "V"), + (0x1B168, "X"), + (0x1B170, "V"), + (0x1B2FC, "X"), + (0x1BC00, "V"), + (0x1BC6B, "X"), + (0x1BC70, "V"), + (0x1BC7D, "X"), + (0x1BC80, "V"), + (0x1BC89, "X"), + (0x1BC90, "V"), + (0x1BC9A, "X"), + (0x1BC9C, "V"), + (0x1BCA0, "I"), + (0x1BCA4, "X"), + (0x1CF00, "V"), + (0x1CF2E, "X"), + (0x1CF30, "V"), + (0x1CF47, "X"), + (0x1CF50, "V"), + (0x1CFC4, "X"), + (0x1D000, "V"), + (0x1D0F6, "X"), + (0x1D100, "V"), + (0x1D127, "X"), + (0x1D129, "V"), + (0x1D15E, "M", "𝅗𝅥"), + (0x1D15F, "M", "𝅘𝅥"), + (0x1D160, "M", "𝅘𝅥𝅮"), + (0x1D161, "M", "𝅘𝅥𝅯"), + (0x1D162, "M", "𝅘𝅥𝅰"), + (0x1D163, "M", "𝅘𝅥𝅱"), + (0x1D164, "M", "𝅘𝅥𝅲"), + (0x1D165, "V"), + (0x1D173, "X"), + (0x1D17B, "V"), + (0x1D1BB, "M", "𝆹𝅥"), + (0x1D1BC, "M", "𝆺𝅥"), + (0x1D1BD, "M", "𝆹𝅥𝅮"), + (0x1D1BE, "M", "𝆺𝅥𝅮"), + (0x1D1BF, "M", "𝆹𝅥𝅯"), + (0x1D1C0, "M", "𝆺𝅥𝅯"), + (0x1D1C1, "V"), + (0x1D1EB, "X"), + (0x1D200, "V"), + (0x1D246, "X"), + (0x1D2C0, "V"), + (0x1D2D4, "X"), + (0x1D2E0, "V"), + (0x1D2F4, "X"), + (0x1D300, "V"), + (0x1D357, "X"), + (0x1D360, "V"), + (0x1D379, "X"), + (0x1D400, "M", "a"), + (0x1D401, "M", "b"), + (0x1D402, "M", "c"), + (0x1D403, "M", "d"), + (0x1D404, "M", "e"), + (0x1D405, "M", "f"), + (0x1D406, "M", "g"), + (0x1D407, "M", "h"), + (0x1D408, "M", "i"), + (0x1D409, "M", "j"), + (0x1D40A, "M", "k"), + (0x1D40B, "M", "l"), + (0x1D40C, "M", "m"), + (0x1D40D, "M", "n"), + (0x1D40E, "M", "o"), + (0x1D40F, "M", "p"), + (0x1D410, "M", "q"), + (0x1D411, "M", "r"), + (0x1D412, "M", "s"), + (0x1D413, "M", "t"), + (0x1D414, "M", "u"), + (0x1D415, "M", "v"), + (0x1D416, "M", "w"), + (0x1D417, "M", "x"), + (0x1D418, "M", "y"), + (0x1D419, "M", "z"), + (0x1D41A, "M", "a"), + (0x1D41B, "M", "b"), + (0x1D41C, "M", "c"), + (0x1D41D, "M", "d"), + (0x1D41E, "M", "e"), + (0x1D41F, "M", "f"), + (0x1D420, "M", "g"), + (0x1D421, "M", "h"), + (0x1D422, "M", "i"), + (0x1D423, "M", "j"), + (0x1D424, "M", "k"), + ] + + +def _seg_61() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D425, "M", "l"), + (0x1D426, "M", "m"), + (0x1D427, "M", "n"), + (0x1D428, "M", "o"), + (0x1D429, "M", "p"), + (0x1D42A, "M", "q"), + (0x1D42B, "M", "r"), + (0x1D42C, "M", "s"), + (0x1D42D, "M", "t"), + (0x1D42E, "M", "u"), + (0x1D42F, "M", "v"), + (0x1D430, "M", "w"), + (0x1D431, "M", "x"), + (0x1D432, "M", "y"), + (0x1D433, "M", "z"), + (0x1D434, "M", "a"), + (0x1D435, "M", "b"), + (0x1D436, "M", "c"), + (0x1D437, "M", "d"), + (0x1D438, "M", "e"), + (0x1D439, "M", "f"), + (0x1D43A, "M", "g"), + (0x1D43B, "M", "h"), + (0x1D43C, "M", "i"), + (0x1D43D, "M", "j"), + (0x1D43E, "M", "k"), + (0x1D43F, "M", "l"), + (0x1D440, "M", "m"), + (0x1D441, "M", "n"), + (0x1D442, "M", "o"), + (0x1D443, "M", "p"), + (0x1D444, "M", "q"), + (0x1D445, "M", "r"), + (0x1D446, "M", "s"), + (0x1D447, "M", "t"), + (0x1D448, "M", "u"), + (0x1D449, "M", "v"), + (0x1D44A, "M", "w"), + (0x1D44B, "M", "x"), + (0x1D44C, "M", "y"), + (0x1D44D, "M", "z"), + (0x1D44E, "M", "a"), + (0x1D44F, "M", "b"), + (0x1D450, "M", "c"), + (0x1D451, "M", "d"), + (0x1D452, "M", "e"), + (0x1D453, "M", "f"), + (0x1D454, "M", "g"), + (0x1D455, "X"), + (0x1D456, "M", "i"), + (0x1D457, "M", "j"), + (0x1D458, "M", "k"), + (0x1D459, "M", "l"), + (0x1D45A, "M", "m"), + (0x1D45B, "M", "n"), + (0x1D45C, "M", "o"), + (0x1D45D, "M", "p"), + (0x1D45E, "M", "q"), + (0x1D45F, "M", "r"), + (0x1D460, "M", "s"), + (0x1D461, "M", "t"), + (0x1D462, "M", "u"), + (0x1D463, "M", "v"), + (0x1D464, "M", "w"), + (0x1D465, "M", "x"), + (0x1D466, "M", "y"), + (0x1D467, "M", "z"), + (0x1D468, "M", "a"), + (0x1D469, "M", "b"), + (0x1D46A, "M", "c"), + (0x1D46B, "M", "d"), + (0x1D46C, "M", "e"), + (0x1D46D, "M", "f"), + (0x1D46E, "M", "g"), + (0x1D46F, "M", "h"), + (0x1D470, "M", "i"), + (0x1D471, "M", "j"), + (0x1D472, "M", "k"), + (0x1D473, "M", "l"), + (0x1D474, "M", "m"), + (0x1D475, "M", "n"), + (0x1D476, "M", "o"), + (0x1D477, "M", "p"), + (0x1D478, "M", "q"), + (0x1D479, "M", "r"), + (0x1D47A, "M", "s"), + (0x1D47B, "M", "t"), + (0x1D47C, "M", "u"), + (0x1D47D, "M", "v"), + (0x1D47E, "M", "w"), + (0x1D47F, "M", "x"), + (0x1D480, "M", "y"), + (0x1D481, "M", "z"), + (0x1D482, "M", "a"), + (0x1D483, "M", "b"), + (0x1D484, "M", "c"), + (0x1D485, "M", "d"), + (0x1D486, "M", "e"), + (0x1D487, "M", "f"), + (0x1D488, "M", "g"), + ] + + +def _seg_62() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D489, "M", "h"), + (0x1D48A, "M", "i"), + (0x1D48B, "M", "j"), + (0x1D48C, "M", "k"), + (0x1D48D, "M", "l"), + (0x1D48E, "M", "m"), + (0x1D48F, "M", "n"), + (0x1D490, "M", "o"), + (0x1D491, "M", "p"), + (0x1D492, "M", "q"), + (0x1D493, "M", "r"), + (0x1D494, "M", "s"), + (0x1D495, "M", "t"), + (0x1D496, "M", "u"), + (0x1D497, "M", "v"), + (0x1D498, "M", "w"), + (0x1D499, "M", "x"), + (0x1D49A, "M", "y"), + (0x1D49B, "M", "z"), + (0x1D49C, "M", "a"), + (0x1D49D, "X"), + (0x1D49E, "M", "c"), + (0x1D49F, "M", "d"), + (0x1D4A0, "X"), + (0x1D4A2, "M", "g"), + (0x1D4A3, "X"), + (0x1D4A5, "M", "j"), + (0x1D4A6, "M", "k"), + (0x1D4A7, "X"), + (0x1D4A9, "M", "n"), + (0x1D4AA, "M", "o"), + (0x1D4AB, "M", "p"), + (0x1D4AC, "M", "q"), + (0x1D4AD, "X"), + (0x1D4AE, "M", "s"), + (0x1D4AF, "M", "t"), + (0x1D4B0, "M", "u"), + (0x1D4B1, "M", "v"), + (0x1D4B2, "M", "w"), + (0x1D4B3, "M", "x"), + (0x1D4B4, "M", "y"), + (0x1D4B5, "M", "z"), + (0x1D4B6, "M", "a"), + (0x1D4B7, "M", "b"), + (0x1D4B8, "M", "c"), + (0x1D4B9, "M", "d"), + (0x1D4BA, "X"), + (0x1D4BB, "M", "f"), + (0x1D4BC, "X"), + (0x1D4BD, "M", "h"), + (0x1D4BE, "M", "i"), + (0x1D4BF, "M", "j"), + (0x1D4C0, "M", "k"), + (0x1D4C1, "M", "l"), + (0x1D4C2, "M", "m"), + (0x1D4C3, "M", "n"), + (0x1D4C4, "X"), + (0x1D4C5, "M", "p"), + (0x1D4C6, "M", "q"), + (0x1D4C7, "M", "r"), + (0x1D4C8, "M", "s"), + (0x1D4C9, "M", "t"), + (0x1D4CA, "M", "u"), + (0x1D4CB, "M", "v"), + (0x1D4CC, "M", "w"), + (0x1D4CD, "M", "x"), + (0x1D4CE, "M", "y"), + (0x1D4CF, "M", "z"), + (0x1D4D0, "M", "a"), + (0x1D4D1, "M", "b"), + (0x1D4D2, "M", "c"), + (0x1D4D3, "M", "d"), + (0x1D4D4, "M", "e"), + (0x1D4D5, "M", "f"), + (0x1D4D6, "M", "g"), + (0x1D4D7, "M", "h"), + (0x1D4D8, "M", "i"), + (0x1D4D9, "M", "j"), + (0x1D4DA, "M", "k"), + (0x1D4DB, "M", "l"), + (0x1D4DC, "M", "m"), + (0x1D4DD, "M", "n"), + (0x1D4DE, "M", "o"), + (0x1D4DF, "M", "p"), + (0x1D4E0, "M", "q"), + (0x1D4E1, "M", "r"), + (0x1D4E2, "M", "s"), + (0x1D4E3, "M", "t"), + (0x1D4E4, "M", "u"), + (0x1D4E5, "M", "v"), + (0x1D4E6, "M", "w"), + (0x1D4E7, "M", "x"), + (0x1D4E8, "M", "y"), + (0x1D4E9, "M", "z"), + (0x1D4EA, "M", "a"), + (0x1D4EB, "M", "b"), + (0x1D4EC, "M", "c"), + (0x1D4ED, "M", "d"), + (0x1D4EE, "M", "e"), + (0x1D4EF, "M", "f"), + ] + + +def _seg_63() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D4F0, "M", "g"), + (0x1D4F1, "M", "h"), + (0x1D4F2, "M", "i"), + (0x1D4F3, "M", "j"), + (0x1D4F4, "M", "k"), + (0x1D4F5, "M", "l"), + (0x1D4F6, "M", "m"), + (0x1D4F7, "M", "n"), + (0x1D4F8, "M", "o"), + (0x1D4F9, "M", "p"), + (0x1D4FA, "M", "q"), + (0x1D4FB, "M", "r"), + (0x1D4FC, "M", "s"), + (0x1D4FD, "M", "t"), + (0x1D4FE, "M", "u"), + (0x1D4FF, "M", "v"), + (0x1D500, "M", "w"), + (0x1D501, "M", "x"), + (0x1D502, "M", "y"), + (0x1D503, "M", "z"), + (0x1D504, "M", "a"), + (0x1D505, "M", "b"), + (0x1D506, "X"), + (0x1D507, "M", "d"), + (0x1D508, "M", "e"), + (0x1D509, "M", "f"), + (0x1D50A, "M", "g"), + (0x1D50B, "X"), + (0x1D50D, "M", "j"), + (0x1D50E, "M", "k"), + (0x1D50F, "M", "l"), + (0x1D510, "M", "m"), + (0x1D511, "M", "n"), + (0x1D512, "M", "o"), + (0x1D513, "M", "p"), + (0x1D514, "M", "q"), + (0x1D515, "X"), + (0x1D516, "M", "s"), + (0x1D517, "M", "t"), + (0x1D518, "M", "u"), + (0x1D519, "M", "v"), + (0x1D51A, "M", "w"), + (0x1D51B, "M", "x"), + (0x1D51C, "M", "y"), + (0x1D51D, "X"), + (0x1D51E, "M", "a"), + (0x1D51F, "M", "b"), + (0x1D520, "M", "c"), + (0x1D521, "M", "d"), + (0x1D522, "M", "e"), + (0x1D523, "M", "f"), + (0x1D524, "M", "g"), + (0x1D525, "M", "h"), + (0x1D526, "M", "i"), + (0x1D527, "M", "j"), + (0x1D528, "M", "k"), + (0x1D529, "M", "l"), + (0x1D52A, "M", "m"), + (0x1D52B, "M", "n"), + (0x1D52C, "M", "o"), + (0x1D52D, "M", "p"), + (0x1D52E, "M", "q"), + (0x1D52F, "M", "r"), + (0x1D530, "M", "s"), + (0x1D531, "M", "t"), + (0x1D532, "M", "u"), + (0x1D533, "M", "v"), + (0x1D534, "M", "w"), + (0x1D535, "M", "x"), + (0x1D536, "M", "y"), + (0x1D537, "M", "z"), + (0x1D538, "M", "a"), + (0x1D539, "M", "b"), + (0x1D53A, "X"), + (0x1D53B, "M", "d"), + (0x1D53C, "M", "e"), + (0x1D53D, "M", "f"), + (0x1D53E, "M", "g"), + (0x1D53F, "X"), + (0x1D540, "M", "i"), + (0x1D541, "M", "j"), + (0x1D542, "M", "k"), + (0x1D543, "M", "l"), + (0x1D544, "M", "m"), + (0x1D545, "X"), + (0x1D546, "M", "o"), + (0x1D547, "X"), + (0x1D54A, "M", "s"), + (0x1D54B, "M", "t"), + (0x1D54C, "M", "u"), + (0x1D54D, "M", "v"), + (0x1D54E, "M", "w"), + (0x1D54F, "M", "x"), + (0x1D550, "M", "y"), + (0x1D551, "X"), + (0x1D552, "M", "a"), + (0x1D553, "M", "b"), + (0x1D554, "M", "c"), + (0x1D555, "M", "d"), + (0x1D556, "M", "e"), + ] + + +def _seg_64() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D557, "M", "f"), + (0x1D558, "M", "g"), + (0x1D559, "M", "h"), + (0x1D55A, "M", "i"), + (0x1D55B, "M", "j"), + (0x1D55C, "M", "k"), + (0x1D55D, "M", "l"), + (0x1D55E, "M", "m"), + (0x1D55F, "M", "n"), + (0x1D560, "M", "o"), + (0x1D561, "M", "p"), + (0x1D562, "M", "q"), + (0x1D563, "M", "r"), + (0x1D564, "M", "s"), + (0x1D565, "M", "t"), + (0x1D566, "M", "u"), + (0x1D567, "M", "v"), + (0x1D568, "M", "w"), + (0x1D569, "M", "x"), + (0x1D56A, "M", "y"), + (0x1D56B, "M", "z"), + (0x1D56C, "M", "a"), + (0x1D56D, "M", "b"), + (0x1D56E, "M", "c"), + (0x1D56F, "M", "d"), + (0x1D570, "M", "e"), + (0x1D571, "M", "f"), + (0x1D572, "M", "g"), + (0x1D573, "M", "h"), + (0x1D574, "M", "i"), + (0x1D575, "M", "j"), + (0x1D576, "M", "k"), + (0x1D577, "M", "l"), + (0x1D578, "M", "m"), + (0x1D579, "M", "n"), + (0x1D57A, "M", "o"), + (0x1D57B, "M", "p"), + (0x1D57C, "M", "q"), + (0x1D57D, "M", "r"), + (0x1D57E, "M", "s"), + (0x1D57F, "M", "t"), + (0x1D580, "M", "u"), + (0x1D581, "M", "v"), + (0x1D582, "M", "w"), + (0x1D583, "M", "x"), + (0x1D584, "M", "y"), + (0x1D585, "M", "z"), + (0x1D586, "M", "a"), + (0x1D587, "M", "b"), + (0x1D588, "M", "c"), + (0x1D589, "M", "d"), + (0x1D58A, "M", "e"), + (0x1D58B, "M", "f"), + (0x1D58C, "M", "g"), + (0x1D58D, "M", "h"), + (0x1D58E, "M", "i"), + (0x1D58F, "M", "j"), + (0x1D590, "M", "k"), + (0x1D591, "M", "l"), + (0x1D592, "M", "m"), + (0x1D593, "M", "n"), + (0x1D594, "M", "o"), + (0x1D595, "M", "p"), + (0x1D596, "M", "q"), + (0x1D597, "M", "r"), + (0x1D598, "M", "s"), + (0x1D599, "M", "t"), + (0x1D59A, "M", "u"), + (0x1D59B, "M", "v"), + (0x1D59C, "M", "w"), + (0x1D59D, "M", "x"), + (0x1D59E, "M", "y"), + (0x1D59F, "M", "z"), + (0x1D5A0, "M", "a"), + (0x1D5A1, "M", "b"), + (0x1D5A2, "M", "c"), + (0x1D5A3, "M", "d"), + (0x1D5A4, "M", "e"), + (0x1D5A5, "M", "f"), + (0x1D5A6, "M", "g"), + (0x1D5A7, "M", "h"), + (0x1D5A8, "M", "i"), + (0x1D5A9, "M", "j"), + (0x1D5AA, "M", "k"), + (0x1D5AB, "M", "l"), + (0x1D5AC, "M", "m"), + (0x1D5AD, "M", "n"), + (0x1D5AE, "M", "o"), + (0x1D5AF, "M", "p"), + (0x1D5B0, "M", "q"), + (0x1D5B1, "M", "r"), + (0x1D5B2, "M", "s"), + (0x1D5B3, "M", "t"), + (0x1D5B4, "M", "u"), + (0x1D5B5, "M", "v"), + (0x1D5B6, "M", "w"), + (0x1D5B7, "M", "x"), + (0x1D5B8, "M", "y"), + (0x1D5B9, "M", "z"), + (0x1D5BA, "M", "a"), + ] + + +def _seg_65() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D5BB, "M", "b"), + (0x1D5BC, "M", "c"), + (0x1D5BD, "M", "d"), + (0x1D5BE, "M", "e"), + (0x1D5BF, "M", "f"), + (0x1D5C0, "M", "g"), + (0x1D5C1, "M", "h"), + (0x1D5C2, "M", "i"), + (0x1D5C3, "M", "j"), + (0x1D5C4, "M", "k"), + (0x1D5C5, "M", "l"), + (0x1D5C6, "M", "m"), + (0x1D5C7, "M", "n"), + (0x1D5C8, "M", "o"), + (0x1D5C9, "M", "p"), + (0x1D5CA, "M", "q"), + (0x1D5CB, "M", "r"), + (0x1D5CC, "M", "s"), + (0x1D5CD, "M", "t"), + (0x1D5CE, "M", "u"), + (0x1D5CF, "M", "v"), + (0x1D5D0, "M", "w"), + (0x1D5D1, "M", "x"), + (0x1D5D2, "M", "y"), + (0x1D5D3, "M", "z"), + (0x1D5D4, "M", "a"), + (0x1D5D5, "M", "b"), + (0x1D5D6, "M", "c"), + (0x1D5D7, "M", "d"), + (0x1D5D8, "M", "e"), + (0x1D5D9, "M", "f"), + (0x1D5DA, "M", "g"), + (0x1D5DB, "M", "h"), + (0x1D5DC, "M", "i"), + (0x1D5DD, "M", "j"), + (0x1D5DE, "M", "k"), + (0x1D5DF, "M", "l"), + (0x1D5E0, "M", "m"), + (0x1D5E1, "M", "n"), + (0x1D5E2, "M", "o"), + (0x1D5E3, "M", "p"), + (0x1D5E4, "M", "q"), + (0x1D5E5, "M", "r"), + (0x1D5E6, "M", "s"), + (0x1D5E7, "M", "t"), + (0x1D5E8, "M", "u"), + (0x1D5E9, "M", "v"), + (0x1D5EA, "M", "w"), + (0x1D5EB, "M", "x"), + (0x1D5EC, "M", "y"), + (0x1D5ED, "M", "z"), + (0x1D5EE, "M", "a"), + (0x1D5EF, "M", "b"), + (0x1D5F0, "M", "c"), + (0x1D5F1, "M", "d"), + (0x1D5F2, "M", "e"), + (0x1D5F3, "M", "f"), + (0x1D5F4, "M", "g"), + (0x1D5F5, "M", "h"), + (0x1D5F6, "M", "i"), + (0x1D5F7, "M", "j"), + (0x1D5F8, "M", "k"), + (0x1D5F9, "M", "l"), + (0x1D5FA, "M", "m"), + (0x1D5FB, "M", "n"), + (0x1D5FC, "M", "o"), + (0x1D5FD, "M", "p"), + (0x1D5FE, "M", "q"), + (0x1D5FF, "M", "r"), + (0x1D600, "M", "s"), + (0x1D601, "M", "t"), + (0x1D602, "M", "u"), + (0x1D603, "M", "v"), + (0x1D604, "M", "w"), + (0x1D605, "M", "x"), + (0x1D606, "M", "y"), + (0x1D607, "M", "z"), + (0x1D608, "M", "a"), + (0x1D609, "M", "b"), + (0x1D60A, "M", "c"), + (0x1D60B, "M", "d"), + (0x1D60C, "M", "e"), + (0x1D60D, "M", "f"), + (0x1D60E, "M", "g"), + (0x1D60F, "M", "h"), + (0x1D610, "M", "i"), + (0x1D611, "M", "j"), + (0x1D612, "M", "k"), + (0x1D613, "M", "l"), + (0x1D614, "M", "m"), + (0x1D615, "M", "n"), + (0x1D616, "M", "o"), + (0x1D617, "M", "p"), + (0x1D618, "M", "q"), + (0x1D619, "M", "r"), + (0x1D61A, "M", "s"), + (0x1D61B, "M", "t"), + (0x1D61C, "M", "u"), + (0x1D61D, "M", "v"), + (0x1D61E, "M", "w"), + ] + + +def _seg_66() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D61F, "M", "x"), + (0x1D620, "M", "y"), + (0x1D621, "M", "z"), + (0x1D622, "M", "a"), + (0x1D623, "M", "b"), + (0x1D624, "M", "c"), + (0x1D625, "M", "d"), + (0x1D626, "M", "e"), + (0x1D627, "M", "f"), + (0x1D628, "M", "g"), + (0x1D629, "M", "h"), + (0x1D62A, "M", "i"), + (0x1D62B, "M", "j"), + (0x1D62C, "M", "k"), + (0x1D62D, "M", "l"), + (0x1D62E, "M", "m"), + (0x1D62F, "M", "n"), + (0x1D630, "M", "o"), + (0x1D631, "M", "p"), + (0x1D632, "M", "q"), + (0x1D633, "M", "r"), + (0x1D634, "M", "s"), + (0x1D635, "M", "t"), + (0x1D636, "M", "u"), + (0x1D637, "M", "v"), + (0x1D638, "M", "w"), + (0x1D639, "M", "x"), + (0x1D63A, "M", "y"), + (0x1D63B, "M", "z"), + (0x1D63C, "M", "a"), + (0x1D63D, "M", "b"), + (0x1D63E, "M", "c"), + (0x1D63F, "M", "d"), + (0x1D640, "M", "e"), + (0x1D641, "M", "f"), + (0x1D642, "M", "g"), + (0x1D643, "M", "h"), + (0x1D644, "M", "i"), + (0x1D645, "M", "j"), + (0x1D646, "M", "k"), + (0x1D647, "M", "l"), + (0x1D648, "M", "m"), + (0x1D649, "M", "n"), + (0x1D64A, "M", "o"), + (0x1D64B, "M", "p"), + (0x1D64C, "M", "q"), + (0x1D64D, "M", "r"), + (0x1D64E, "M", "s"), + (0x1D64F, "M", "t"), + (0x1D650, "M", "u"), + (0x1D651, "M", "v"), + (0x1D652, "M", "w"), + (0x1D653, "M", "x"), + (0x1D654, "M", "y"), + (0x1D655, "M", "z"), + (0x1D656, "M", "a"), + (0x1D657, "M", "b"), + (0x1D658, "M", "c"), + (0x1D659, "M", "d"), + (0x1D65A, "M", "e"), + (0x1D65B, "M", "f"), + (0x1D65C, "M", "g"), + (0x1D65D, "M", "h"), + (0x1D65E, "M", "i"), + (0x1D65F, "M", "j"), + (0x1D660, "M", "k"), + (0x1D661, "M", "l"), + (0x1D662, "M", "m"), + (0x1D663, "M", "n"), + (0x1D664, "M", "o"), + (0x1D665, "M", "p"), + (0x1D666, "M", "q"), + (0x1D667, "M", "r"), + (0x1D668, "M", "s"), + (0x1D669, "M", "t"), + (0x1D66A, "M", "u"), + (0x1D66B, "M", "v"), + (0x1D66C, "M", "w"), + (0x1D66D, "M", "x"), + (0x1D66E, "M", "y"), + (0x1D66F, "M", "z"), + (0x1D670, "M", "a"), + (0x1D671, "M", "b"), + (0x1D672, "M", "c"), + (0x1D673, "M", "d"), + (0x1D674, "M", "e"), + (0x1D675, "M", "f"), + (0x1D676, "M", "g"), + (0x1D677, "M", "h"), + (0x1D678, "M", "i"), + (0x1D679, "M", "j"), + (0x1D67A, "M", "k"), + (0x1D67B, "M", "l"), + (0x1D67C, "M", "m"), + (0x1D67D, "M", "n"), + (0x1D67E, "M", "o"), + (0x1D67F, "M", "p"), + (0x1D680, "M", "q"), + (0x1D681, "M", "r"), + (0x1D682, "M", "s"), + ] + + +def _seg_67() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D683, "M", "t"), + (0x1D684, "M", "u"), + (0x1D685, "M", "v"), + (0x1D686, "M", "w"), + (0x1D687, "M", "x"), + (0x1D688, "M", "y"), + (0x1D689, "M", "z"), + (0x1D68A, "M", "a"), + (0x1D68B, "M", "b"), + (0x1D68C, "M", "c"), + (0x1D68D, "M", "d"), + (0x1D68E, "M", "e"), + (0x1D68F, "M", "f"), + (0x1D690, "M", "g"), + (0x1D691, "M", "h"), + (0x1D692, "M", "i"), + (0x1D693, "M", "j"), + (0x1D694, "M", "k"), + (0x1D695, "M", "l"), + (0x1D696, "M", "m"), + (0x1D697, "M", "n"), + (0x1D698, "M", "o"), + (0x1D699, "M", "p"), + (0x1D69A, "M", "q"), + (0x1D69B, "M", "r"), + (0x1D69C, "M", "s"), + (0x1D69D, "M", "t"), + (0x1D69E, "M", "u"), + (0x1D69F, "M", "v"), + (0x1D6A0, "M", "w"), + (0x1D6A1, "M", "x"), + (0x1D6A2, "M", "y"), + (0x1D6A3, "M", "z"), + (0x1D6A4, "M", "ı"), + (0x1D6A5, "M", "ȷ"), + (0x1D6A6, "X"), + (0x1D6A8, "M", "α"), + (0x1D6A9, "M", "β"), + (0x1D6AA, "M", "γ"), + (0x1D6AB, "M", "δ"), + (0x1D6AC, "M", "ε"), + (0x1D6AD, "M", "ζ"), + (0x1D6AE, "M", "η"), + (0x1D6AF, "M", "θ"), + (0x1D6B0, "M", "ι"), + (0x1D6B1, "M", "κ"), + (0x1D6B2, "M", "λ"), + (0x1D6B3, "M", "μ"), + (0x1D6B4, "M", "ν"), + (0x1D6B5, "M", "ξ"), + (0x1D6B6, "M", "ο"), + (0x1D6B7, "M", "π"), + (0x1D6B8, "M", "ρ"), + (0x1D6B9, "M", "θ"), + (0x1D6BA, "M", "σ"), + (0x1D6BB, "M", "τ"), + (0x1D6BC, "M", "υ"), + (0x1D6BD, "M", "φ"), + (0x1D6BE, "M", "χ"), + (0x1D6BF, "M", "ψ"), + (0x1D6C0, "M", "ω"), + (0x1D6C1, "M", "∇"), + (0x1D6C2, "M", "α"), + (0x1D6C3, "M", "β"), + (0x1D6C4, "M", "γ"), + (0x1D6C5, "M", "δ"), + (0x1D6C6, "M", "ε"), + (0x1D6C7, "M", "ζ"), + (0x1D6C8, "M", "η"), + (0x1D6C9, "M", "θ"), + (0x1D6CA, "M", "ι"), + (0x1D6CB, "M", "κ"), + (0x1D6CC, "M", "λ"), + (0x1D6CD, "M", "μ"), + (0x1D6CE, "M", "ν"), + (0x1D6CF, "M", "ξ"), + (0x1D6D0, "M", "ο"), + (0x1D6D1, "M", "π"), + (0x1D6D2, "M", "ρ"), + (0x1D6D3, "M", "σ"), + (0x1D6D5, "M", "τ"), + (0x1D6D6, "M", "υ"), + (0x1D6D7, "M", "φ"), + (0x1D6D8, "M", "χ"), + (0x1D6D9, "M", "ψ"), + (0x1D6DA, "M", "ω"), + (0x1D6DB, "M", "∂"), + (0x1D6DC, "M", "ε"), + (0x1D6DD, "M", "θ"), + (0x1D6DE, "M", "κ"), + (0x1D6DF, "M", "φ"), + (0x1D6E0, "M", "ρ"), + (0x1D6E1, "M", "π"), + (0x1D6E2, "M", "α"), + (0x1D6E3, "M", "β"), + (0x1D6E4, "M", "γ"), + (0x1D6E5, "M", "δ"), + (0x1D6E6, "M", "ε"), + (0x1D6E7, "M", "ζ"), + (0x1D6E8, "M", "η"), + ] + + +def _seg_68() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D6E9, "M", "θ"), + (0x1D6EA, "M", "ι"), + (0x1D6EB, "M", "κ"), + (0x1D6EC, "M", "λ"), + (0x1D6ED, "M", "μ"), + (0x1D6EE, "M", "ν"), + (0x1D6EF, "M", "ξ"), + (0x1D6F0, "M", "ο"), + (0x1D6F1, "M", "π"), + (0x1D6F2, "M", "ρ"), + (0x1D6F3, "M", "θ"), + (0x1D6F4, "M", "σ"), + (0x1D6F5, "M", "τ"), + (0x1D6F6, "M", "υ"), + (0x1D6F7, "M", "φ"), + (0x1D6F8, "M", "χ"), + (0x1D6F9, "M", "ψ"), + (0x1D6FA, "M", "ω"), + (0x1D6FB, "M", "∇"), + (0x1D6FC, "M", "α"), + (0x1D6FD, "M", "β"), + (0x1D6FE, "M", "γ"), + (0x1D6FF, "M", "δ"), + (0x1D700, "M", "ε"), + (0x1D701, "M", "ζ"), + (0x1D702, "M", "η"), + (0x1D703, "M", "θ"), + (0x1D704, "M", "ι"), + (0x1D705, "M", "κ"), + (0x1D706, "M", "λ"), + (0x1D707, "M", "μ"), + (0x1D708, "M", "ν"), + (0x1D709, "M", "ξ"), + (0x1D70A, "M", "ο"), + (0x1D70B, "M", "π"), + (0x1D70C, "M", "ρ"), + (0x1D70D, "M", "σ"), + (0x1D70F, "M", "τ"), + (0x1D710, "M", "υ"), + (0x1D711, "M", "φ"), + (0x1D712, "M", "χ"), + (0x1D713, "M", "ψ"), + (0x1D714, "M", "ω"), + (0x1D715, "M", "∂"), + (0x1D716, "M", "ε"), + (0x1D717, "M", "θ"), + (0x1D718, "M", "κ"), + (0x1D719, "M", "φ"), + (0x1D71A, "M", "ρ"), + (0x1D71B, "M", "π"), + (0x1D71C, "M", "α"), + (0x1D71D, "M", "β"), + (0x1D71E, "M", "γ"), + (0x1D71F, "M", "δ"), + (0x1D720, "M", "ε"), + (0x1D721, "M", "ζ"), + (0x1D722, "M", "η"), + (0x1D723, "M", "θ"), + (0x1D724, "M", "ι"), + (0x1D725, "M", "κ"), + (0x1D726, "M", "λ"), + (0x1D727, "M", "μ"), + (0x1D728, "M", "ν"), + (0x1D729, "M", "ξ"), + (0x1D72A, "M", "ο"), + (0x1D72B, "M", "π"), + (0x1D72C, "M", "ρ"), + (0x1D72D, "M", "θ"), + (0x1D72E, "M", "σ"), + (0x1D72F, "M", "τ"), + (0x1D730, "M", "υ"), + (0x1D731, "M", "φ"), + (0x1D732, "M", "χ"), + (0x1D733, "M", "ψ"), + (0x1D734, "M", "ω"), + (0x1D735, "M", "∇"), + (0x1D736, "M", "α"), + (0x1D737, "M", "β"), + (0x1D738, "M", "γ"), + (0x1D739, "M", "δ"), + (0x1D73A, "M", "ε"), + (0x1D73B, "M", "ζ"), + (0x1D73C, "M", "η"), + (0x1D73D, "M", "θ"), + (0x1D73E, "M", "ι"), + (0x1D73F, "M", "κ"), + (0x1D740, "M", "λ"), + (0x1D741, "M", "μ"), + (0x1D742, "M", "ν"), + (0x1D743, "M", "ξ"), + (0x1D744, "M", "ο"), + (0x1D745, "M", "π"), + (0x1D746, "M", "ρ"), + (0x1D747, "M", "σ"), + (0x1D749, "M", "τ"), + (0x1D74A, "M", "υ"), + (0x1D74B, "M", "φ"), + (0x1D74C, "M", "χ"), + (0x1D74D, "M", "ψ"), + (0x1D74E, "M", "ω"), + ] + + +def _seg_69() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D74F, "M", "∂"), + (0x1D750, "M", "ε"), + (0x1D751, "M", "θ"), + (0x1D752, "M", "κ"), + (0x1D753, "M", "φ"), + (0x1D754, "M", "ρ"), + (0x1D755, "M", "π"), + (0x1D756, "M", "α"), + (0x1D757, "M", "β"), + (0x1D758, "M", "γ"), + (0x1D759, "M", "δ"), + (0x1D75A, "M", "ε"), + (0x1D75B, "M", "ζ"), + (0x1D75C, "M", "η"), + (0x1D75D, "M", "θ"), + (0x1D75E, "M", "ι"), + (0x1D75F, "M", "κ"), + (0x1D760, "M", "λ"), + (0x1D761, "M", "μ"), + (0x1D762, "M", "ν"), + (0x1D763, "M", "ξ"), + (0x1D764, "M", "ο"), + (0x1D765, "M", "π"), + (0x1D766, "M", "ρ"), + (0x1D767, "M", "θ"), + (0x1D768, "M", "σ"), + (0x1D769, "M", "τ"), + (0x1D76A, "M", "υ"), + (0x1D76B, "M", "φ"), + (0x1D76C, "M", "χ"), + (0x1D76D, "M", "ψ"), + (0x1D76E, "M", "ω"), + (0x1D76F, "M", "∇"), + (0x1D770, "M", "α"), + (0x1D771, "M", "β"), + (0x1D772, "M", "γ"), + (0x1D773, "M", "δ"), + (0x1D774, "M", "ε"), + (0x1D775, "M", "ζ"), + (0x1D776, "M", "η"), + (0x1D777, "M", "θ"), + (0x1D778, "M", "ι"), + (0x1D779, "M", "κ"), + (0x1D77A, "M", "λ"), + (0x1D77B, "M", "μ"), + (0x1D77C, "M", "ν"), + (0x1D77D, "M", "ξ"), + (0x1D77E, "M", "ο"), + (0x1D77F, "M", "π"), + (0x1D780, "M", "ρ"), + (0x1D781, "M", "σ"), + (0x1D783, "M", "τ"), + (0x1D784, "M", "υ"), + (0x1D785, "M", "φ"), + (0x1D786, "M", "χ"), + (0x1D787, "M", "ψ"), + (0x1D788, "M", "ω"), + (0x1D789, "M", "∂"), + (0x1D78A, "M", "ε"), + (0x1D78B, "M", "θ"), + (0x1D78C, "M", "κ"), + (0x1D78D, "M", "φ"), + (0x1D78E, "M", "ρ"), + (0x1D78F, "M", "π"), + (0x1D790, "M", "α"), + (0x1D791, "M", "β"), + (0x1D792, "M", "γ"), + (0x1D793, "M", "δ"), + (0x1D794, "M", "ε"), + (0x1D795, "M", "ζ"), + (0x1D796, "M", "η"), + (0x1D797, "M", "θ"), + (0x1D798, "M", "ι"), + (0x1D799, "M", "κ"), + (0x1D79A, "M", "λ"), + (0x1D79B, "M", "μ"), + (0x1D79C, "M", "ν"), + (0x1D79D, "M", "ξ"), + (0x1D79E, "M", "ο"), + (0x1D79F, "M", "π"), + (0x1D7A0, "M", "ρ"), + (0x1D7A1, "M", "θ"), + (0x1D7A2, "M", "σ"), + (0x1D7A3, "M", "τ"), + (0x1D7A4, "M", "υ"), + (0x1D7A5, "M", "φ"), + (0x1D7A6, "M", "χ"), + (0x1D7A7, "M", "ψ"), + (0x1D7A8, "M", "ω"), + (0x1D7A9, "M", "∇"), + (0x1D7AA, "M", "α"), + (0x1D7AB, "M", "β"), + (0x1D7AC, "M", "γ"), + (0x1D7AD, "M", "δ"), + (0x1D7AE, "M", "ε"), + (0x1D7AF, "M", "ζ"), + (0x1D7B0, "M", "η"), + (0x1D7B1, "M", "θ"), + (0x1D7B2, "M", "ι"), + (0x1D7B3, "M", "κ"), + ] + + +def _seg_70() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1D7B4, "M", "λ"), + (0x1D7B5, "M", "μ"), + (0x1D7B6, "M", "ν"), + (0x1D7B7, "M", "ξ"), + (0x1D7B8, "M", "ο"), + (0x1D7B9, "M", "π"), + (0x1D7BA, "M", "ρ"), + (0x1D7BB, "M", "σ"), + (0x1D7BD, "M", "τ"), + (0x1D7BE, "M", "υ"), + (0x1D7BF, "M", "φ"), + (0x1D7C0, "M", "χ"), + (0x1D7C1, "M", "ψ"), + (0x1D7C2, "M", "ω"), + (0x1D7C3, "M", "∂"), + (0x1D7C4, "M", "ε"), + (0x1D7C5, "M", "θ"), + (0x1D7C6, "M", "κ"), + (0x1D7C7, "M", "φ"), + (0x1D7C8, "M", "ρ"), + (0x1D7C9, "M", "π"), + (0x1D7CA, "M", "ϝ"), + (0x1D7CC, "X"), + (0x1D7CE, "M", "0"), + (0x1D7CF, "M", "1"), + (0x1D7D0, "M", "2"), + (0x1D7D1, "M", "3"), + (0x1D7D2, "M", "4"), + (0x1D7D3, "M", "5"), + (0x1D7D4, "M", "6"), + (0x1D7D5, "M", "7"), + (0x1D7D6, "M", "8"), + (0x1D7D7, "M", "9"), + (0x1D7D8, "M", "0"), + (0x1D7D9, "M", "1"), + (0x1D7DA, "M", "2"), + (0x1D7DB, "M", "3"), + (0x1D7DC, "M", "4"), + (0x1D7DD, "M", "5"), + (0x1D7DE, "M", "6"), + (0x1D7DF, "M", "7"), + (0x1D7E0, "M", "8"), + (0x1D7E1, "M", "9"), + (0x1D7E2, "M", "0"), + (0x1D7E3, "M", "1"), + (0x1D7E4, "M", "2"), + (0x1D7E5, "M", "3"), + (0x1D7E6, "M", "4"), + (0x1D7E7, "M", "5"), + (0x1D7E8, "M", "6"), + (0x1D7E9, "M", "7"), + (0x1D7EA, "M", "8"), + (0x1D7EB, "M", "9"), + (0x1D7EC, "M", "0"), + (0x1D7ED, "M", "1"), + (0x1D7EE, "M", "2"), + (0x1D7EF, "M", "3"), + (0x1D7F0, "M", "4"), + (0x1D7F1, "M", "5"), + (0x1D7F2, "M", "6"), + (0x1D7F3, "M", "7"), + (0x1D7F4, "M", "8"), + (0x1D7F5, "M", "9"), + (0x1D7F6, "M", "0"), + (0x1D7F7, "M", "1"), + (0x1D7F8, "M", "2"), + (0x1D7F9, "M", "3"), + (0x1D7FA, "M", "4"), + (0x1D7FB, "M", "5"), + (0x1D7FC, "M", "6"), + (0x1D7FD, "M", "7"), + (0x1D7FE, "M", "8"), + (0x1D7FF, "M", "9"), + (0x1D800, "V"), + (0x1DA8C, "X"), + (0x1DA9B, "V"), + (0x1DAA0, "X"), + (0x1DAA1, "V"), + (0x1DAB0, "X"), + (0x1DF00, "V"), + (0x1DF1F, "X"), + (0x1DF25, "V"), + (0x1DF2B, "X"), + (0x1E000, "V"), + (0x1E007, "X"), + (0x1E008, "V"), + (0x1E019, "X"), + (0x1E01B, "V"), + (0x1E022, "X"), + (0x1E023, "V"), + (0x1E025, "X"), + (0x1E026, "V"), + (0x1E02B, "X"), + (0x1E030, "M", "а"), + (0x1E031, "M", "б"), + (0x1E032, "M", "в"), + (0x1E033, "M", "г"), + (0x1E034, "M", "д"), + (0x1E035, "M", "е"), + (0x1E036, "M", "ж"), + ] + + +def _seg_71() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1E037, "M", "з"), + (0x1E038, "M", "и"), + (0x1E039, "M", "к"), + (0x1E03A, "M", "л"), + (0x1E03B, "M", "м"), + (0x1E03C, "M", "о"), + (0x1E03D, "M", "п"), + (0x1E03E, "M", "р"), + (0x1E03F, "M", "с"), + (0x1E040, "M", "т"), + (0x1E041, "M", "у"), + (0x1E042, "M", "ф"), + (0x1E043, "M", "х"), + (0x1E044, "M", "ц"), + (0x1E045, "M", "ч"), + (0x1E046, "M", "ш"), + (0x1E047, "M", "ы"), + (0x1E048, "M", "э"), + (0x1E049, "M", "ю"), + (0x1E04A, "M", "ꚉ"), + (0x1E04B, "M", "ә"), + (0x1E04C, "M", "і"), + (0x1E04D, "M", "ј"), + (0x1E04E, "M", "ө"), + (0x1E04F, "M", "ү"), + (0x1E050, "M", "ӏ"), + (0x1E051, "M", "а"), + (0x1E052, "M", "б"), + (0x1E053, "M", "в"), + (0x1E054, "M", "г"), + (0x1E055, "M", "д"), + (0x1E056, "M", "е"), + (0x1E057, "M", "ж"), + (0x1E058, "M", "з"), + (0x1E059, "M", "и"), + (0x1E05A, "M", "к"), + (0x1E05B, "M", "л"), + (0x1E05C, "M", "о"), + (0x1E05D, "M", "п"), + (0x1E05E, "M", "с"), + (0x1E05F, "M", "у"), + (0x1E060, "M", "ф"), + (0x1E061, "M", "х"), + (0x1E062, "M", "ц"), + (0x1E063, "M", "ч"), + (0x1E064, "M", "ш"), + (0x1E065, "M", "ъ"), + (0x1E066, "M", "ы"), + (0x1E067, "M", "ґ"), + (0x1E068, "M", "і"), + (0x1E069, "M", "ѕ"), + (0x1E06A, "M", "џ"), + (0x1E06B, "M", "ҫ"), + (0x1E06C, "M", "ꙑ"), + (0x1E06D, "M", "ұ"), + (0x1E06E, "X"), + (0x1E08F, "V"), + (0x1E090, "X"), + (0x1E100, "V"), + (0x1E12D, "X"), + (0x1E130, "V"), + (0x1E13E, "X"), + (0x1E140, "V"), + (0x1E14A, "X"), + (0x1E14E, "V"), + (0x1E150, "X"), + (0x1E290, "V"), + (0x1E2AF, "X"), + (0x1E2C0, "V"), + (0x1E2FA, "X"), + (0x1E2FF, "V"), + (0x1E300, "X"), + (0x1E4D0, "V"), + (0x1E4FA, "X"), + (0x1E7E0, "V"), + (0x1E7E7, "X"), + (0x1E7E8, "V"), + (0x1E7EC, "X"), + (0x1E7ED, "V"), + (0x1E7EF, "X"), + (0x1E7F0, "V"), + (0x1E7FF, "X"), + (0x1E800, "V"), + (0x1E8C5, "X"), + (0x1E8C7, "V"), + (0x1E8D7, "X"), + (0x1E900, "M", "𞤢"), + (0x1E901, "M", "𞤣"), + (0x1E902, "M", "𞤤"), + (0x1E903, "M", "𞤥"), + (0x1E904, "M", "𞤦"), + (0x1E905, "M", "𞤧"), + (0x1E906, "M", "𞤨"), + (0x1E907, "M", "𞤩"), + (0x1E908, "M", "𞤪"), + (0x1E909, "M", "𞤫"), + (0x1E90A, "M", "𞤬"), + (0x1E90B, "M", "𞤭"), + (0x1E90C, "M", "𞤮"), + (0x1E90D, "M", "𞤯"), + ] + + +def _seg_72() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1E90E, "M", "𞤰"), + (0x1E90F, "M", "𞤱"), + (0x1E910, "M", "𞤲"), + (0x1E911, "M", "𞤳"), + (0x1E912, "M", "𞤴"), + (0x1E913, "M", "𞤵"), + (0x1E914, "M", "𞤶"), + (0x1E915, "M", "𞤷"), + (0x1E916, "M", "𞤸"), + (0x1E917, "M", "𞤹"), + (0x1E918, "M", "𞤺"), + (0x1E919, "M", "𞤻"), + (0x1E91A, "M", "𞤼"), + (0x1E91B, "M", "𞤽"), + (0x1E91C, "M", "𞤾"), + (0x1E91D, "M", "𞤿"), + (0x1E91E, "M", "𞥀"), + (0x1E91F, "M", "𞥁"), + (0x1E920, "M", "𞥂"), + (0x1E921, "M", "𞥃"), + (0x1E922, "V"), + (0x1E94C, "X"), + (0x1E950, "V"), + (0x1E95A, "X"), + (0x1E95E, "V"), + (0x1E960, "X"), + (0x1EC71, "V"), + (0x1ECB5, "X"), + (0x1ED01, "V"), + (0x1ED3E, "X"), + (0x1EE00, "M", "ا"), + (0x1EE01, "M", "ب"), + (0x1EE02, "M", "ج"), + (0x1EE03, "M", "د"), + (0x1EE04, "X"), + (0x1EE05, "M", "و"), + (0x1EE06, "M", "ز"), + (0x1EE07, "M", "ح"), + (0x1EE08, "M", "ط"), + (0x1EE09, "M", "ي"), + (0x1EE0A, "M", "ك"), + (0x1EE0B, "M", "ل"), + (0x1EE0C, "M", "م"), + (0x1EE0D, "M", "ن"), + (0x1EE0E, "M", "س"), + (0x1EE0F, "M", "ع"), + (0x1EE10, "M", "ف"), + (0x1EE11, "M", "ص"), + (0x1EE12, "M", "ق"), + (0x1EE13, "M", "ر"), + (0x1EE14, "M", "ش"), + (0x1EE15, "M", "ت"), + (0x1EE16, "M", "ث"), + (0x1EE17, "M", "خ"), + (0x1EE18, "M", "ذ"), + (0x1EE19, "M", "ض"), + (0x1EE1A, "M", "ظ"), + (0x1EE1B, "M", "غ"), + (0x1EE1C, "M", "ٮ"), + (0x1EE1D, "M", "ں"), + (0x1EE1E, "M", "ڡ"), + (0x1EE1F, "M", "ٯ"), + (0x1EE20, "X"), + (0x1EE21, "M", "ب"), + (0x1EE22, "M", "ج"), + (0x1EE23, "X"), + (0x1EE24, "M", "ه"), + (0x1EE25, "X"), + (0x1EE27, "M", "ح"), + (0x1EE28, "X"), + (0x1EE29, "M", "ي"), + (0x1EE2A, "M", "ك"), + (0x1EE2B, "M", "ل"), + (0x1EE2C, "M", "م"), + (0x1EE2D, "M", "ن"), + (0x1EE2E, "M", "س"), + (0x1EE2F, "M", "ع"), + (0x1EE30, "M", "ف"), + (0x1EE31, "M", "ص"), + (0x1EE32, "M", "ق"), + (0x1EE33, "X"), + (0x1EE34, "M", "ش"), + (0x1EE35, "M", "ت"), + (0x1EE36, "M", "ث"), + (0x1EE37, "M", "خ"), + (0x1EE38, "X"), + (0x1EE39, "M", "ض"), + (0x1EE3A, "X"), + (0x1EE3B, "M", "غ"), + (0x1EE3C, "X"), + (0x1EE42, "M", "ج"), + (0x1EE43, "X"), + (0x1EE47, "M", "ح"), + (0x1EE48, "X"), + (0x1EE49, "M", "ي"), + (0x1EE4A, "X"), + (0x1EE4B, "M", "ل"), + (0x1EE4C, "X"), + (0x1EE4D, "M", "ن"), + (0x1EE4E, "M", "س"), + ] + + +def _seg_73() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1EE4F, "M", "ع"), + (0x1EE50, "X"), + (0x1EE51, "M", "ص"), + (0x1EE52, "M", "ق"), + (0x1EE53, "X"), + (0x1EE54, "M", "ش"), + (0x1EE55, "X"), + (0x1EE57, "M", "خ"), + (0x1EE58, "X"), + (0x1EE59, "M", "ض"), + (0x1EE5A, "X"), + (0x1EE5B, "M", "غ"), + (0x1EE5C, "X"), + (0x1EE5D, "M", "ں"), + (0x1EE5E, "X"), + (0x1EE5F, "M", "ٯ"), + (0x1EE60, "X"), + (0x1EE61, "M", "ب"), + (0x1EE62, "M", "ج"), + (0x1EE63, "X"), + (0x1EE64, "M", "ه"), + (0x1EE65, "X"), + (0x1EE67, "M", "ح"), + (0x1EE68, "M", "ط"), + (0x1EE69, "M", "ي"), + (0x1EE6A, "M", "ك"), + (0x1EE6B, "X"), + (0x1EE6C, "M", "م"), + (0x1EE6D, "M", "ن"), + (0x1EE6E, "M", "س"), + (0x1EE6F, "M", "ع"), + (0x1EE70, "M", "ف"), + (0x1EE71, "M", "ص"), + (0x1EE72, "M", "ق"), + (0x1EE73, "X"), + (0x1EE74, "M", "ش"), + (0x1EE75, "M", "ت"), + (0x1EE76, "M", "ث"), + (0x1EE77, "M", "خ"), + (0x1EE78, "X"), + (0x1EE79, "M", "ض"), + (0x1EE7A, "M", "ظ"), + (0x1EE7B, "M", "غ"), + (0x1EE7C, "M", "ٮ"), + (0x1EE7D, "X"), + (0x1EE7E, "M", "ڡ"), + (0x1EE7F, "X"), + (0x1EE80, "M", "ا"), + (0x1EE81, "M", "ب"), + (0x1EE82, "M", "ج"), + (0x1EE83, "M", "د"), + (0x1EE84, "M", "ه"), + (0x1EE85, "M", "و"), + (0x1EE86, "M", "ز"), + (0x1EE87, "M", "ح"), + (0x1EE88, "M", "ط"), + (0x1EE89, "M", "ي"), + (0x1EE8A, "X"), + (0x1EE8B, "M", "ل"), + (0x1EE8C, "M", "م"), + (0x1EE8D, "M", "ن"), + (0x1EE8E, "M", "س"), + (0x1EE8F, "M", "ع"), + (0x1EE90, "M", "ف"), + (0x1EE91, "M", "ص"), + (0x1EE92, "M", "ق"), + (0x1EE93, "M", "ر"), + (0x1EE94, "M", "ش"), + (0x1EE95, "M", "ت"), + (0x1EE96, "M", "ث"), + (0x1EE97, "M", "خ"), + (0x1EE98, "M", "ذ"), + (0x1EE99, "M", "ض"), + (0x1EE9A, "M", "ظ"), + (0x1EE9B, "M", "غ"), + (0x1EE9C, "X"), + (0x1EEA1, "M", "ب"), + (0x1EEA2, "M", "ج"), + (0x1EEA3, "M", "د"), + (0x1EEA4, "X"), + (0x1EEA5, "M", "و"), + (0x1EEA6, "M", "ز"), + (0x1EEA7, "M", "ح"), + (0x1EEA8, "M", "ط"), + (0x1EEA9, "M", "ي"), + (0x1EEAA, "X"), + (0x1EEAB, "M", "ل"), + (0x1EEAC, "M", "م"), + (0x1EEAD, "M", "ن"), + (0x1EEAE, "M", "س"), + (0x1EEAF, "M", "ع"), + (0x1EEB0, "M", "ف"), + (0x1EEB1, "M", "ص"), + (0x1EEB2, "M", "ق"), + (0x1EEB3, "M", "ر"), + (0x1EEB4, "M", "ش"), + (0x1EEB5, "M", "ت"), + (0x1EEB6, "M", "ث"), + (0x1EEB7, "M", "خ"), + (0x1EEB8, "M", "ذ"), + ] + + +def _seg_74() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1EEB9, "M", "ض"), + (0x1EEBA, "M", "ظ"), + (0x1EEBB, "M", "غ"), + (0x1EEBC, "X"), + (0x1EEF0, "V"), + (0x1EEF2, "X"), + (0x1F000, "V"), + (0x1F02C, "X"), + (0x1F030, "V"), + (0x1F094, "X"), + (0x1F0A0, "V"), + (0x1F0AF, "X"), + (0x1F0B1, "V"), + (0x1F0C0, "X"), + (0x1F0C1, "V"), + (0x1F0D0, "X"), + (0x1F0D1, "V"), + (0x1F0F6, "X"), + (0x1F101, "3", "0,"), + (0x1F102, "3", "1,"), + (0x1F103, "3", "2,"), + (0x1F104, "3", "3,"), + (0x1F105, "3", "4,"), + (0x1F106, "3", "5,"), + (0x1F107, "3", "6,"), + (0x1F108, "3", "7,"), + (0x1F109, "3", "8,"), + (0x1F10A, "3", "9,"), + (0x1F10B, "V"), + (0x1F110, "3", "(a)"), + (0x1F111, "3", "(b)"), + (0x1F112, "3", "(c)"), + (0x1F113, "3", "(d)"), + (0x1F114, "3", "(e)"), + (0x1F115, "3", "(f)"), + (0x1F116, "3", "(g)"), + (0x1F117, "3", "(h)"), + (0x1F118, "3", "(i)"), + (0x1F119, "3", "(j)"), + (0x1F11A, "3", "(k)"), + (0x1F11B, "3", "(l)"), + (0x1F11C, "3", "(m)"), + (0x1F11D, "3", "(n)"), + (0x1F11E, "3", "(o)"), + (0x1F11F, "3", "(p)"), + (0x1F120, "3", "(q)"), + (0x1F121, "3", "(r)"), + (0x1F122, "3", "(s)"), + (0x1F123, "3", "(t)"), + (0x1F124, "3", "(u)"), + (0x1F125, "3", "(v)"), + (0x1F126, "3", "(w)"), + (0x1F127, "3", "(x)"), + (0x1F128, "3", "(y)"), + (0x1F129, "3", "(z)"), + (0x1F12A, "M", "〔s〕"), + (0x1F12B, "M", "c"), + (0x1F12C, "M", "r"), + (0x1F12D, "M", "cd"), + (0x1F12E, "M", "wz"), + (0x1F12F, "V"), + (0x1F130, "M", "a"), + (0x1F131, "M", "b"), + (0x1F132, "M", "c"), + (0x1F133, "M", "d"), + (0x1F134, "M", "e"), + (0x1F135, "M", "f"), + (0x1F136, "M", "g"), + (0x1F137, "M", "h"), + (0x1F138, "M", "i"), + (0x1F139, "M", "j"), + (0x1F13A, "M", "k"), + (0x1F13B, "M", "l"), + (0x1F13C, "M", "m"), + (0x1F13D, "M", "n"), + (0x1F13E, "M", "o"), + (0x1F13F, "M", "p"), + (0x1F140, "M", "q"), + (0x1F141, "M", "r"), + (0x1F142, "M", "s"), + (0x1F143, "M", "t"), + (0x1F144, "M", "u"), + (0x1F145, "M", "v"), + (0x1F146, "M", "w"), + (0x1F147, "M", "x"), + (0x1F148, "M", "y"), + (0x1F149, "M", "z"), + (0x1F14A, "M", "hv"), + (0x1F14B, "M", "mv"), + (0x1F14C, "M", "sd"), + (0x1F14D, "M", "ss"), + (0x1F14E, "M", "ppv"), + (0x1F14F, "M", "wc"), + (0x1F150, "V"), + (0x1F16A, "M", "mc"), + (0x1F16B, "M", "md"), + (0x1F16C, "M", "mr"), + (0x1F16D, "V"), + (0x1F190, "M", "dj"), + (0x1F191, "V"), + ] + + +def _seg_75() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1F1AE, "X"), + (0x1F1E6, "V"), + (0x1F200, "M", "ほか"), + (0x1F201, "M", "ココ"), + (0x1F202, "M", "サ"), + (0x1F203, "X"), + (0x1F210, "M", "手"), + (0x1F211, "M", "字"), + (0x1F212, "M", "双"), + (0x1F213, "M", "デ"), + (0x1F214, "M", "二"), + (0x1F215, "M", "多"), + (0x1F216, "M", "解"), + (0x1F217, "M", "天"), + (0x1F218, "M", "交"), + (0x1F219, "M", "映"), + (0x1F21A, "M", "無"), + (0x1F21B, "M", "料"), + (0x1F21C, "M", "前"), + (0x1F21D, "M", "後"), + (0x1F21E, "M", "再"), + (0x1F21F, "M", "新"), + (0x1F220, "M", "初"), + (0x1F221, "M", "終"), + (0x1F222, "M", "生"), + (0x1F223, "M", "販"), + (0x1F224, "M", "声"), + (0x1F225, "M", "吹"), + (0x1F226, "M", "演"), + (0x1F227, "M", "投"), + (0x1F228, "M", "捕"), + (0x1F229, "M", "一"), + (0x1F22A, "M", "三"), + (0x1F22B, "M", "遊"), + (0x1F22C, "M", "左"), + (0x1F22D, "M", "中"), + (0x1F22E, "M", "右"), + (0x1F22F, "M", "指"), + (0x1F230, "M", "走"), + (0x1F231, "M", "打"), + (0x1F232, "M", "禁"), + (0x1F233, "M", "空"), + (0x1F234, "M", "合"), + (0x1F235, "M", "満"), + (0x1F236, "M", "有"), + (0x1F237, "M", "月"), + (0x1F238, "M", "申"), + (0x1F239, "M", "割"), + (0x1F23A, "M", "営"), + (0x1F23B, "M", "配"), + (0x1F23C, "X"), + (0x1F240, "M", "〔本〕"), + (0x1F241, "M", "〔三〕"), + (0x1F242, "M", "〔二〕"), + (0x1F243, "M", "〔安〕"), + (0x1F244, "M", "〔点〕"), + (0x1F245, "M", "〔打〕"), + (0x1F246, "M", "〔盗〕"), + (0x1F247, "M", "〔勝〕"), + (0x1F248, "M", "〔敗〕"), + (0x1F249, "X"), + (0x1F250, "M", "得"), + (0x1F251, "M", "可"), + (0x1F252, "X"), + (0x1F260, "V"), + (0x1F266, "X"), + (0x1F300, "V"), + (0x1F6D8, "X"), + (0x1F6DC, "V"), + (0x1F6ED, "X"), + (0x1F6F0, "V"), + (0x1F6FD, "X"), + (0x1F700, "V"), + (0x1F777, "X"), + (0x1F77B, "V"), + (0x1F7DA, "X"), + (0x1F7E0, "V"), + (0x1F7EC, "X"), + (0x1F7F0, "V"), + (0x1F7F1, "X"), + (0x1F800, "V"), + (0x1F80C, "X"), + (0x1F810, "V"), + (0x1F848, "X"), + (0x1F850, "V"), + (0x1F85A, "X"), + (0x1F860, "V"), + (0x1F888, "X"), + (0x1F890, "V"), + (0x1F8AE, "X"), + (0x1F8B0, "V"), + (0x1F8B2, "X"), + (0x1F900, "V"), + (0x1FA54, "X"), + (0x1FA60, "V"), + (0x1FA6E, "X"), + (0x1FA70, "V"), + (0x1FA7D, "X"), + (0x1FA80, "V"), + (0x1FA89, "X"), + ] + + +def _seg_76() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x1FA90, "V"), + (0x1FABE, "X"), + (0x1FABF, "V"), + (0x1FAC6, "X"), + (0x1FACE, "V"), + (0x1FADC, "X"), + (0x1FAE0, "V"), + (0x1FAE9, "X"), + (0x1FAF0, "V"), + (0x1FAF9, "X"), + (0x1FB00, "V"), + (0x1FB93, "X"), + (0x1FB94, "V"), + (0x1FBCB, "X"), + (0x1FBF0, "M", "0"), + (0x1FBF1, "M", "1"), + (0x1FBF2, "M", "2"), + (0x1FBF3, "M", "3"), + (0x1FBF4, "M", "4"), + (0x1FBF5, "M", "5"), + (0x1FBF6, "M", "6"), + (0x1FBF7, "M", "7"), + (0x1FBF8, "M", "8"), + (0x1FBF9, "M", "9"), + (0x1FBFA, "X"), + (0x20000, "V"), + (0x2A6E0, "X"), + (0x2A700, "V"), + (0x2B73A, "X"), + (0x2B740, "V"), + (0x2B81E, "X"), + (0x2B820, "V"), + (0x2CEA2, "X"), + (0x2CEB0, "V"), + (0x2EBE1, "X"), + (0x2EBF0, "V"), + (0x2EE5E, "X"), + (0x2F800, "M", "丽"), + (0x2F801, "M", "丸"), + (0x2F802, "M", "乁"), + (0x2F803, "M", "𠄢"), + (0x2F804, "M", "你"), + (0x2F805, "M", "侮"), + (0x2F806, "M", "侻"), + (0x2F807, "M", "倂"), + (0x2F808, "M", "偺"), + (0x2F809, "M", "備"), + (0x2F80A, "M", "僧"), + (0x2F80B, "M", "像"), + (0x2F80C, "M", "㒞"), + (0x2F80D, "M", "𠘺"), + (0x2F80E, "M", "免"), + (0x2F80F, "M", "兔"), + (0x2F810, "M", "兤"), + (0x2F811, "M", "具"), + (0x2F812, "M", "𠔜"), + (0x2F813, "M", "㒹"), + (0x2F814, "M", "內"), + (0x2F815, "M", "再"), + (0x2F816, "M", "𠕋"), + (0x2F817, "M", "冗"), + (0x2F818, "M", "冤"), + (0x2F819, "M", "仌"), + (0x2F81A, "M", "冬"), + (0x2F81B, "M", "况"), + (0x2F81C, "M", "𩇟"), + (0x2F81D, "M", "凵"), + (0x2F81E, "M", "刃"), + (0x2F81F, "M", "㓟"), + (0x2F820, "M", "刻"), + (0x2F821, "M", "剆"), + (0x2F822, "M", "割"), + (0x2F823, "M", "剷"), + (0x2F824, "M", "㔕"), + (0x2F825, "M", "勇"), + (0x2F826, "M", "勉"), + (0x2F827, "M", "勤"), + (0x2F828, "M", "勺"), + (0x2F829, "M", "包"), + (0x2F82A, "M", "匆"), + (0x2F82B, "M", "北"), + (0x2F82C, "M", "卉"), + (0x2F82D, "M", "卑"), + (0x2F82E, "M", "博"), + (0x2F82F, "M", "即"), + (0x2F830, "M", "卽"), + (0x2F831, "M", "卿"), + (0x2F834, "M", "𠨬"), + (0x2F835, "M", "灰"), + (0x2F836, "M", "及"), + (0x2F837, "M", "叟"), + (0x2F838, "M", "𠭣"), + (0x2F839, "M", "叫"), + (0x2F83A, "M", "叱"), + (0x2F83B, "M", "吆"), + (0x2F83C, "M", "咞"), + (0x2F83D, "M", "吸"), + (0x2F83E, "M", "呈"), + (0x2F83F, "M", "周"), + (0x2F840, "M", "咢"), + ] + + +def _seg_77() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F841, "M", "哶"), + (0x2F842, "M", "唐"), + (0x2F843, "M", "啓"), + (0x2F844, "M", "啣"), + (0x2F845, "M", "善"), + (0x2F847, "M", "喙"), + (0x2F848, "M", "喫"), + (0x2F849, "M", "喳"), + (0x2F84A, "M", "嗂"), + (0x2F84B, "M", "圖"), + (0x2F84C, "M", "嘆"), + (0x2F84D, "M", "圗"), + (0x2F84E, "M", "噑"), + (0x2F84F, "M", "噴"), + (0x2F850, "M", "切"), + (0x2F851, "M", "壮"), + (0x2F852, "M", "城"), + (0x2F853, "M", "埴"), + (0x2F854, "M", "堍"), + (0x2F855, "M", "型"), + (0x2F856, "M", "堲"), + (0x2F857, "M", "報"), + (0x2F858, "M", "墬"), + (0x2F859, "M", "𡓤"), + (0x2F85A, "M", "売"), + (0x2F85B, "M", "壷"), + (0x2F85C, "M", "夆"), + (0x2F85D, "M", "多"), + (0x2F85E, "M", "夢"), + (0x2F85F, "M", "奢"), + (0x2F860, "M", "𡚨"), + (0x2F861, "M", "𡛪"), + (0x2F862, "M", "姬"), + (0x2F863, "M", "娛"), + (0x2F864, "M", "娧"), + (0x2F865, "M", "姘"), + (0x2F866, "M", "婦"), + (0x2F867, "M", "㛮"), + (0x2F868, "X"), + (0x2F869, "M", "嬈"), + (0x2F86A, "M", "嬾"), + (0x2F86C, "M", "𡧈"), + (0x2F86D, "M", "寃"), + (0x2F86E, "M", "寘"), + (0x2F86F, "M", "寧"), + (0x2F870, "M", "寳"), + (0x2F871, "M", "𡬘"), + (0x2F872, "M", "寿"), + (0x2F873, "M", "将"), + (0x2F874, "X"), + (0x2F875, "M", "尢"), + (0x2F876, "M", "㞁"), + (0x2F877, "M", "屠"), + (0x2F878, "M", "屮"), + (0x2F879, "M", "峀"), + (0x2F87A, "M", "岍"), + (0x2F87B, "M", "𡷤"), + (0x2F87C, "M", "嵃"), + (0x2F87D, "M", "𡷦"), + (0x2F87E, "M", "嵮"), + (0x2F87F, "M", "嵫"), + (0x2F880, "M", "嵼"), + (0x2F881, "M", "巡"), + (0x2F882, "M", "巢"), + (0x2F883, "M", "㠯"), + (0x2F884, "M", "巽"), + (0x2F885, "M", "帨"), + (0x2F886, "M", "帽"), + (0x2F887, "M", "幩"), + (0x2F888, "M", "㡢"), + (0x2F889, "M", "𢆃"), + (0x2F88A, "M", "㡼"), + (0x2F88B, "M", "庰"), + (0x2F88C, "M", "庳"), + (0x2F88D, "M", "庶"), + (0x2F88E, "M", "廊"), + (0x2F88F, "M", "𪎒"), + (0x2F890, "M", "廾"), + (0x2F891, "M", "𢌱"), + (0x2F893, "M", "舁"), + (0x2F894, "M", "弢"), + (0x2F896, "M", "㣇"), + (0x2F897, "M", "𣊸"), + (0x2F898, "M", "𦇚"), + (0x2F899, "M", "形"), + (0x2F89A, "M", "彫"), + (0x2F89B, "M", "㣣"), + (0x2F89C, "M", "徚"), + (0x2F89D, "M", "忍"), + (0x2F89E, "M", "志"), + (0x2F89F, "M", "忹"), + (0x2F8A0, "M", "悁"), + (0x2F8A1, "M", "㤺"), + (0x2F8A2, "M", "㤜"), + (0x2F8A3, "M", "悔"), + (0x2F8A4, "M", "𢛔"), + (0x2F8A5, "M", "惇"), + (0x2F8A6, "M", "慈"), + (0x2F8A7, "M", "慌"), + (0x2F8A8, "M", "慎"), + ] + + +def _seg_78() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F8A9, "M", "慌"), + (0x2F8AA, "M", "慺"), + (0x2F8AB, "M", "憎"), + (0x2F8AC, "M", "憲"), + (0x2F8AD, "M", "憤"), + (0x2F8AE, "M", "憯"), + (0x2F8AF, "M", "懞"), + (0x2F8B0, "M", "懲"), + (0x2F8B1, "M", "懶"), + (0x2F8B2, "M", "成"), + (0x2F8B3, "M", "戛"), + (0x2F8B4, "M", "扝"), + (0x2F8B5, "M", "抱"), + (0x2F8B6, "M", "拔"), + (0x2F8B7, "M", "捐"), + (0x2F8B8, "M", "𢬌"), + (0x2F8B9, "M", "挽"), + (0x2F8BA, "M", "拼"), + (0x2F8BB, "M", "捨"), + (0x2F8BC, "M", "掃"), + (0x2F8BD, "M", "揤"), + (0x2F8BE, "M", "𢯱"), + (0x2F8BF, "M", "搢"), + (0x2F8C0, "M", "揅"), + (0x2F8C1, "M", "掩"), + (0x2F8C2, "M", "㨮"), + (0x2F8C3, "M", "摩"), + (0x2F8C4, "M", "摾"), + (0x2F8C5, "M", "撝"), + (0x2F8C6, "M", "摷"), + (0x2F8C7, "M", "㩬"), + (0x2F8C8, "M", "敏"), + (0x2F8C9, "M", "敬"), + (0x2F8CA, "M", "𣀊"), + (0x2F8CB, "M", "旣"), + (0x2F8CC, "M", "書"), + (0x2F8CD, "M", "晉"), + (0x2F8CE, "M", "㬙"), + (0x2F8CF, "M", "暑"), + (0x2F8D0, "M", "㬈"), + (0x2F8D1, "M", "㫤"), + (0x2F8D2, "M", "冒"), + (0x2F8D3, "M", "冕"), + (0x2F8D4, "M", "最"), + (0x2F8D5, "M", "暜"), + (0x2F8D6, "M", "肭"), + (0x2F8D7, "M", "䏙"), + (0x2F8D8, "M", "朗"), + (0x2F8D9, "M", "望"), + (0x2F8DA, "M", "朡"), + (0x2F8DB, "M", "杞"), + (0x2F8DC, "M", "杓"), + (0x2F8DD, "M", "𣏃"), + (0x2F8DE, "M", "㭉"), + (0x2F8DF, "M", "柺"), + (0x2F8E0, "M", "枅"), + (0x2F8E1, "M", "桒"), + (0x2F8E2, "M", "梅"), + (0x2F8E3, "M", "𣑭"), + (0x2F8E4, "M", "梎"), + (0x2F8E5, "M", "栟"), + (0x2F8E6, "M", "椔"), + (0x2F8E7, "M", "㮝"), + (0x2F8E8, "M", "楂"), + (0x2F8E9, "M", "榣"), + (0x2F8EA, "M", "槪"), + (0x2F8EB, "M", "檨"), + (0x2F8EC, "M", "𣚣"), + (0x2F8ED, "M", "櫛"), + (0x2F8EE, "M", "㰘"), + (0x2F8EF, "M", "次"), + (0x2F8F0, "M", "𣢧"), + (0x2F8F1, "M", "歔"), + (0x2F8F2, "M", "㱎"), + (0x2F8F3, "M", "歲"), + (0x2F8F4, "M", "殟"), + (0x2F8F5, "M", "殺"), + (0x2F8F6, "M", "殻"), + (0x2F8F7, "M", "𣪍"), + (0x2F8F8, "M", "𡴋"), + (0x2F8F9, "M", "𣫺"), + (0x2F8FA, "M", "汎"), + (0x2F8FB, "M", "𣲼"), + (0x2F8FC, "M", "沿"), + (0x2F8FD, "M", "泍"), + (0x2F8FE, "M", "汧"), + (0x2F8FF, "M", "洖"), + (0x2F900, "M", "派"), + (0x2F901, "M", "海"), + (0x2F902, "M", "流"), + (0x2F903, "M", "浩"), + (0x2F904, "M", "浸"), + (0x2F905, "M", "涅"), + (0x2F906, "M", "𣴞"), + (0x2F907, "M", "洴"), + (0x2F908, "M", "港"), + (0x2F909, "M", "湮"), + (0x2F90A, "M", "㴳"), + (0x2F90B, "M", "滋"), + (0x2F90C, "M", "滇"), + ] + + +def _seg_79() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F90D, "M", "𣻑"), + (0x2F90E, "M", "淹"), + (0x2F90F, "M", "潮"), + (0x2F910, "M", "𣽞"), + (0x2F911, "M", "𣾎"), + (0x2F912, "M", "濆"), + (0x2F913, "M", "瀹"), + (0x2F914, "M", "瀞"), + (0x2F915, "M", "瀛"), + (0x2F916, "M", "㶖"), + (0x2F917, "M", "灊"), + (0x2F918, "M", "災"), + (0x2F919, "M", "灷"), + (0x2F91A, "M", "炭"), + (0x2F91B, "M", "𠔥"), + (0x2F91C, "M", "煅"), + (0x2F91D, "M", "𤉣"), + (0x2F91E, "M", "熜"), + (0x2F91F, "X"), + (0x2F920, "M", "爨"), + (0x2F921, "M", "爵"), + (0x2F922, "M", "牐"), + (0x2F923, "M", "𤘈"), + (0x2F924, "M", "犀"), + (0x2F925, "M", "犕"), + (0x2F926, "M", "𤜵"), + (0x2F927, "M", "𤠔"), + (0x2F928, "M", "獺"), + (0x2F929, "M", "王"), + (0x2F92A, "M", "㺬"), + (0x2F92B, "M", "玥"), + (0x2F92C, "M", "㺸"), + (0x2F92E, "M", "瑇"), + (0x2F92F, "M", "瑜"), + (0x2F930, "M", "瑱"), + (0x2F931, "M", "璅"), + (0x2F932, "M", "瓊"), + (0x2F933, "M", "㼛"), + (0x2F934, "M", "甤"), + (0x2F935, "M", "𤰶"), + (0x2F936, "M", "甾"), + (0x2F937, "M", "𤲒"), + (0x2F938, "M", "異"), + (0x2F939, "M", "𢆟"), + (0x2F93A, "M", "瘐"), + (0x2F93B, "M", "𤾡"), + (0x2F93C, "M", "𤾸"), + (0x2F93D, "M", "𥁄"), + (0x2F93E, "M", "㿼"), + (0x2F93F, "M", "䀈"), + (0x2F940, "M", "直"), + (0x2F941, "M", "𥃳"), + (0x2F942, "M", "𥃲"), + (0x2F943, "M", "𥄙"), + (0x2F944, "M", "𥄳"), + (0x2F945, "M", "眞"), + (0x2F946, "M", "真"), + (0x2F948, "M", "睊"), + (0x2F949, "M", "䀹"), + (0x2F94A, "M", "瞋"), + (0x2F94B, "M", "䁆"), + (0x2F94C, "M", "䂖"), + (0x2F94D, "M", "𥐝"), + (0x2F94E, "M", "硎"), + (0x2F94F, "M", "碌"), + (0x2F950, "M", "磌"), + (0x2F951, "M", "䃣"), + (0x2F952, "M", "𥘦"), + (0x2F953, "M", "祖"), + (0x2F954, "M", "𥚚"), + (0x2F955, "M", "𥛅"), + (0x2F956, "M", "福"), + (0x2F957, "M", "秫"), + (0x2F958, "M", "䄯"), + (0x2F959, "M", "穀"), + (0x2F95A, "M", "穊"), + (0x2F95B, "M", "穏"), + (0x2F95C, "M", "𥥼"), + (0x2F95D, "M", "𥪧"), + (0x2F95F, "X"), + (0x2F960, "M", "䈂"), + (0x2F961, "M", "𥮫"), + (0x2F962, "M", "篆"), + (0x2F963, "M", "築"), + (0x2F964, "M", "䈧"), + (0x2F965, "M", "𥲀"), + (0x2F966, "M", "糒"), + (0x2F967, "M", "䊠"), + (0x2F968, "M", "糨"), + (0x2F969, "M", "糣"), + (0x2F96A, "M", "紀"), + (0x2F96B, "M", "𥾆"), + (0x2F96C, "M", "絣"), + (0x2F96D, "M", "䌁"), + (0x2F96E, "M", "緇"), + (0x2F96F, "M", "縂"), + (0x2F970, "M", "繅"), + (0x2F971, "M", "䌴"), + (0x2F972, "M", "𦈨"), + (0x2F973, "M", "𦉇"), + ] + + +def _seg_80() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F974, "M", "䍙"), + (0x2F975, "M", "𦋙"), + (0x2F976, "M", "罺"), + (0x2F977, "M", "𦌾"), + (0x2F978, "M", "羕"), + (0x2F979, "M", "翺"), + (0x2F97A, "M", "者"), + (0x2F97B, "M", "𦓚"), + (0x2F97C, "M", "𦔣"), + (0x2F97D, "M", "聠"), + (0x2F97E, "M", "𦖨"), + (0x2F97F, "M", "聰"), + (0x2F980, "M", "𣍟"), + (0x2F981, "M", "䏕"), + (0x2F982, "M", "育"), + (0x2F983, "M", "脃"), + (0x2F984, "M", "䐋"), + (0x2F985, "M", "脾"), + (0x2F986, "M", "媵"), + (0x2F987, "M", "𦞧"), + (0x2F988, "M", "𦞵"), + (0x2F989, "M", "𣎓"), + (0x2F98A, "M", "𣎜"), + (0x2F98B, "M", "舁"), + (0x2F98C, "M", "舄"), + (0x2F98D, "M", "辞"), + (0x2F98E, "M", "䑫"), + (0x2F98F, "M", "芑"), + (0x2F990, "M", "芋"), + (0x2F991, "M", "芝"), + (0x2F992, "M", "劳"), + (0x2F993, "M", "花"), + (0x2F994, "M", "芳"), + (0x2F995, "M", "芽"), + (0x2F996, "M", "苦"), + (0x2F997, "M", "𦬼"), + (0x2F998, "M", "若"), + (0x2F999, "M", "茝"), + (0x2F99A, "M", "荣"), + (0x2F99B, "M", "莭"), + (0x2F99C, "M", "茣"), + (0x2F99D, "M", "莽"), + (0x2F99E, "M", "菧"), + (0x2F99F, "M", "著"), + (0x2F9A0, "M", "荓"), + (0x2F9A1, "M", "菊"), + (0x2F9A2, "M", "菌"), + (0x2F9A3, "M", "菜"), + (0x2F9A4, "M", "𦰶"), + (0x2F9A5, "M", "𦵫"), + (0x2F9A6, "M", "𦳕"), + (0x2F9A7, "M", "䔫"), + (0x2F9A8, "M", "蓱"), + (0x2F9A9, "M", "蓳"), + (0x2F9AA, "M", "蔖"), + (0x2F9AB, "M", "𧏊"), + (0x2F9AC, "M", "蕤"), + (0x2F9AD, "M", "𦼬"), + (0x2F9AE, "M", "䕝"), + (0x2F9AF, "M", "䕡"), + (0x2F9B0, "M", "𦾱"), + (0x2F9B1, "M", "𧃒"), + (0x2F9B2, "M", "䕫"), + (0x2F9B3, "M", "虐"), + (0x2F9B4, "M", "虜"), + (0x2F9B5, "M", "虧"), + (0x2F9B6, "M", "虩"), + (0x2F9B7, "M", "蚩"), + (0x2F9B8, "M", "蚈"), + (0x2F9B9, "M", "蜎"), + (0x2F9BA, "M", "蛢"), + (0x2F9BB, "M", "蝹"), + (0x2F9BC, "M", "蜨"), + (0x2F9BD, "M", "蝫"), + (0x2F9BE, "M", "螆"), + (0x2F9BF, "X"), + (0x2F9C0, "M", "蟡"), + (0x2F9C1, "M", "蠁"), + (0x2F9C2, "M", "䗹"), + (0x2F9C3, "M", "衠"), + (0x2F9C4, "M", "衣"), + (0x2F9C5, "M", "𧙧"), + (0x2F9C6, "M", "裗"), + (0x2F9C7, "M", "裞"), + (0x2F9C8, "M", "䘵"), + (0x2F9C9, "M", "裺"), + (0x2F9CA, "M", "㒻"), + (0x2F9CB, "M", "𧢮"), + (0x2F9CC, "M", "𧥦"), + (0x2F9CD, "M", "䚾"), + (0x2F9CE, "M", "䛇"), + (0x2F9CF, "M", "誠"), + (0x2F9D0, "M", "諭"), + (0x2F9D1, "M", "變"), + (0x2F9D2, "M", "豕"), + (0x2F9D3, "M", "𧲨"), + (0x2F9D4, "M", "貫"), + (0x2F9D5, "M", "賁"), + (0x2F9D6, "M", "贛"), + (0x2F9D7, "M", "起"), + ] + + +def _seg_81() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: + return [ + (0x2F9D8, "M", "𧼯"), + (0x2F9D9, "M", "𠠄"), + (0x2F9DA, "M", "跋"), + (0x2F9DB, "M", "趼"), + (0x2F9DC, "M", "跰"), + (0x2F9DD, "M", "𠣞"), + (0x2F9DE, "M", "軔"), + (0x2F9DF, "M", "輸"), + (0x2F9E0, "M", "𨗒"), + (0x2F9E1, "M", "𨗭"), + (0x2F9E2, "M", "邔"), + (0x2F9E3, "M", "郱"), + (0x2F9E4, "M", "鄑"), + (0x2F9E5, "M", "𨜮"), + (0x2F9E6, "M", "鄛"), + (0x2F9E7, "M", "鈸"), + (0x2F9E8, "M", "鋗"), + (0x2F9E9, "M", "鋘"), + (0x2F9EA, "M", "鉼"), + (0x2F9EB, "M", "鏹"), + (0x2F9EC, "M", "鐕"), + (0x2F9ED, "M", "𨯺"), + (0x2F9EE, "M", "開"), + (0x2F9EF, "M", "䦕"), + (0x2F9F0, "M", "閷"), + (0x2F9F1, "M", "𨵷"), + (0x2F9F2, "M", "䧦"), + (0x2F9F3, "M", "雃"), + (0x2F9F4, "M", "嶲"), + (0x2F9F5, "M", "霣"), + (0x2F9F6, "M", "𩅅"), + (0x2F9F7, "M", "𩈚"), + (0x2F9F8, "M", "䩮"), + (0x2F9F9, "M", "䩶"), + (0x2F9FA, "M", "韠"), + (0x2F9FB, "M", "𩐊"), + (0x2F9FC, "M", "䪲"), + (0x2F9FD, "M", "𩒖"), + (0x2F9FE, "M", "頋"), + (0x2FA00, "M", "頩"), + (0x2FA01, "M", "𩖶"), + (0x2FA02, "M", "飢"), + (0x2FA03, "M", "䬳"), + (0x2FA04, "M", "餩"), + (0x2FA05, "M", "馧"), + (0x2FA06, "M", "駂"), + (0x2FA07, "M", "駾"), + (0x2FA08, "M", "䯎"), + (0x2FA09, "M", "𩬰"), + (0x2FA0A, "M", "鬒"), + (0x2FA0B, "M", "鱀"), + (0x2FA0C, "M", "鳽"), + (0x2FA0D, "M", "䳎"), + (0x2FA0E, "M", "䳭"), + (0x2FA0F, "M", "鵧"), + (0x2FA10, "M", "𪃎"), + (0x2FA11, "M", "䳸"), + (0x2FA12, "M", "𪄅"), + (0x2FA13, "M", "𪈎"), + (0x2FA14, "M", "𪊑"), + (0x2FA15, "M", "麻"), + (0x2FA16, "M", "䵖"), + (0x2FA17, "M", "黹"), + (0x2FA18, "M", "黾"), + (0x2FA19, "M", "鼅"), + (0x2FA1A, "M", "鼏"), + (0x2FA1B, "M", "鼖"), + (0x2FA1C, "M", "鼻"), + (0x2FA1D, "M", "𪘀"), + (0x2FA1E, "X"), + (0x30000, "V"), + (0x3134B, "X"), + (0x31350, "V"), + (0x323B0, "X"), + (0xE0100, "I"), + (0xE01F0, "X"), + ] + + +uts46data = tuple( + _seg_0() + + _seg_1() + + _seg_2() + + _seg_3() + + _seg_4() + + _seg_5() + + _seg_6() + + _seg_7() + + _seg_8() + + _seg_9() + + _seg_10() + + _seg_11() + + _seg_12() + + _seg_13() + + _seg_14() + + _seg_15() + + _seg_16() + + _seg_17() + + _seg_18() + + _seg_19() + + _seg_20() + + _seg_21() + + _seg_22() + + _seg_23() + + _seg_24() + + _seg_25() + + _seg_26() + + _seg_27() + + _seg_28() + + _seg_29() + + _seg_30() + + _seg_31() + + _seg_32() + + _seg_33() + + _seg_34() + + _seg_35() + + _seg_36() + + _seg_37() + + _seg_38() + + _seg_39() + + _seg_40() + + _seg_41() + + _seg_42() + + _seg_43() + + _seg_44() + + _seg_45() + + _seg_46() + + _seg_47() + + _seg_48() + + _seg_49() + + _seg_50() + + _seg_51() + + _seg_52() + + _seg_53() + + _seg_54() + + _seg_55() + + _seg_56() + + _seg_57() + + _seg_58() + + _seg_59() + + _seg_60() + + _seg_61() + + _seg_62() + + _seg_63() + + _seg_64() + + _seg_65() + + _seg_66() + + _seg_67() + + _seg_68() + + _seg_69() + + _seg_70() + + _seg_71() + + _seg_72() + + _seg_73() + + _seg_74() + + _seg_75() + + _seg_76() + + _seg_77() + + _seg_78() + + _seg_79() + + _seg_80() + + _seg_81() +) # type: Tuple[Union[Tuple[int, str], Tuple[int, str, str]], ...] diff --git a/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/LICENSE b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..33b1352017fa3939ee32c08e027f57deefb9470f --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2014-2022, imageio developers +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/METADATA b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..62f66512a286ea0c1f48f6280bcd23faaa667cb4 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/METADATA @@ -0,0 +1,142 @@ +Metadata-Version: 2.1 +Name: imageio +Version: 2.37.0 +Summary: Library for reading and writing a wide range of image, video, scientific, and volumetric data formats. +Home-page: https://github.com/imageio/imageio +Download-URL: http://pypi.python.org/pypi/imageio +Author: imageio contributors +Author-email: almar.klein@gmail.com +License: BSD-2-Clause +Keywords: image video volume imread imwrite io animation ffmpeg +Platform: any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Science/Research +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Provides: imageio +Requires-Python: >=3.9 +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: pillow>=8.3.2 +Provides-Extra: all-plugins +Requires-Dist: astropy; extra == "all-plugins" +Requires-Dist: av; extra == "all-plugins" +Requires-Dist: imageio-ffmpeg; extra == "all-plugins" +Requires-Dist: numpy>2; extra == "all-plugins" +Requires-Dist: pillow-heif; extra == "all-plugins" +Requires-Dist: psutil; extra == "all-plugins" +Requires-Dist: rawpy; extra == "all-plugins" +Requires-Dist: tifffile; extra == "all-plugins" +Provides-Extra: all-plugins-pypy +Requires-Dist: av; extra == "all-plugins-pypy" +Requires-Dist: imageio-ffmpeg; extra == "all-plugins-pypy" +Requires-Dist: pillow-heif; extra == "all-plugins-pypy" +Requires-Dist: psutil; extra == "all-plugins-pypy" +Requires-Dist: tifffile; extra == "all-plugins-pypy" +Provides-Extra: bsdf +Provides-Extra: build +Requires-Dist: wheel; extra == "build" +Provides-Extra: dev +Requires-Dist: pytest; extra == "dev" +Requires-Dist: pytest-cov; extra == "dev" +Requires-Dist: fsspec[github]; extra == "dev" +Requires-Dist: black; extra == "dev" +Requires-Dist: flake8; extra == "dev" +Provides-Extra: dicom +Provides-Extra: docs +Requires-Dist: sphinx<6; extra == "docs" +Requires-Dist: numpydoc; extra == "docs" +Requires-Dist: pydata-sphinx-theme; extra == "docs" +Provides-Extra: feisem +Provides-Extra: ffmpeg +Requires-Dist: imageio-ffmpeg; extra == "ffmpeg" +Requires-Dist: psutil; extra == "ffmpeg" +Provides-Extra: fits +Requires-Dist: astropy; extra == "fits" +Provides-Extra: freeimage +Provides-Extra: full +Requires-Dist: astropy; extra == "full" +Requires-Dist: av; extra == "full" +Requires-Dist: black; extra == "full" +Requires-Dist: flake8; extra == "full" +Requires-Dist: fsspec[github]; extra == "full" +Requires-Dist: gdal; extra == "full" +Requires-Dist: imageio-ffmpeg; extra == "full" +Requires-Dist: itk; extra == "full" +Requires-Dist: numpy>2; extra == "full" +Requires-Dist: numpydoc; extra == "full" +Requires-Dist: pillow-heif; extra == "full" +Requires-Dist: psutil; extra == "full" +Requires-Dist: pydata-sphinx-theme; extra == "full" +Requires-Dist: pytest; extra == "full" +Requires-Dist: pytest-cov; extra == "full" +Requires-Dist: rawpy; extra == "full" +Requires-Dist: sphinx<6; extra == "full" +Requires-Dist: tifffile; extra == "full" +Requires-Dist: wheel; extra == "full" +Provides-Extra: gdal +Requires-Dist: gdal; extra == "gdal" +Provides-Extra: itk +Requires-Dist: itk; extra == "itk" +Provides-Extra: linting +Requires-Dist: black; extra == "linting" +Requires-Dist: flake8; extra == "linting" +Provides-Extra: lytro +Provides-Extra: numpy +Provides-Extra: pillow +Provides-Extra: pillow-heif +Requires-Dist: pillow-heif; extra == "pillow-heif" +Provides-Extra: pyav +Requires-Dist: av; extra == "pyav" +Provides-Extra: rawpy +Requires-Dist: rawpy; extra == "rawpy" +Requires-Dist: numpy>2; extra == "rawpy" +Provides-Extra: simpleitk +Provides-Extra: spe +Provides-Extra: swf +Provides-Extra: test +Requires-Dist: pytest; extra == "test" +Requires-Dist: pytest-cov; extra == "test" +Requires-Dist: fsspec[github]; extra == "test" +Provides-Extra: tifffile +Requires-Dist: tifffile; extra == "tifffile" + + +.. image:: https://github.com/imageio/imageio/workflows/CI/badge.svg + :target: https://github.com/imageio/imageio/actions + + +Imageio is a Python library that provides an easy interface to read and +write a wide range of image data, including animated images, volumetric +data, and scientific formats. It is cross-platform, runs on Python 3.9+, +and is easy to install. + +Main website: https://imageio.readthedocs.io/ + + +Release notes: https://github.com/imageio/imageio/blob/master/CHANGELOG.md + +Example: + +.. code-block:: python + + >>> import imageio + >>> im = imageio.imread('imageio:astronaut.png') + >>> im.shape # im is a numpy array + (512, 512, 3) + >>> imageio.imwrite('astronaut-gray.jpg', im[:, :, 0]) + +See the `API Reference `_ +or `examples `_ +for more information. diff --git a/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/RECORD b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bf22c5349fe0bb97b6e0e82be1e38feeea08db5c --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/RECORD @@ -0,0 +1,116 @@ +../../Scripts/imageio_download_bin.exe,sha256=mK4GEPitBwr2U_DBZ-hrehKx6iT9HOki0701EJoQtGU,108443 +../../Scripts/imageio_remove_bin.exe,sha256=yQ3YbvHTk_Jf7nC5FdhCJbNOWaMzo34TBAx-LdBI_ho,108439 +imageio-2.37.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +imageio-2.37.0.dist-info/LICENSE,sha256=rlmepQpJTvtyXkIKqzXR91kgDP5BhrbGSjC6Sds_0GQ,1307 +imageio-2.37.0.dist-info/METADATA,sha256=Gdtdu5UVCepo14mgXJFMii_9WVxfgXHpalIVCccaMkg,5197 +imageio-2.37.0.dist-info/RECORD,, +imageio-2.37.0.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92 +imageio-2.37.0.dist-info/entry_points.txt,sha256=0-yB6XGfrx1OMPw_xigPramTcwi5M4jX6L5Edrz0OoU,130 +imageio-2.37.0.dist-info/top_level.txt,sha256=iSUjc-wEw-xbMTvMOSKg85n0-E7Ms--Mo4FLMC-J2YM,8 +imageio/__init__.py,sha256=EXKZMIL6MLLQ_aMuXONkxVSCBcM9bagNtrqauzwzLyI,3272 +imageio/__main__.py,sha256=s5nidb9wRZ6AbimHTPHULt3sTXPx4mqNil67KJHZvd4,5393 +imageio/__pycache__/__init__.cpython-312.pyc,, +imageio/__pycache__/__main__.cpython-312.pyc,, +imageio/__pycache__/freeze.cpython-312.pyc,, +imageio/__pycache__/testing.cpython-312.pyc,, +imageio/__pycache__/typing.cpython-312.pyc,, +imageio/__pycache__/v2.cpython-312.pyc,, +imageio/__pycache__/v3.cpython-312.pyc,, +imageio/config/__init__.py,sha256=8NOpL5ePrkiioJb9hRBw3rydc4iNZkMwp7VdQlP4jDc,307 +imageio/config/__pycache__/__init__.cpython-312.pyc,, +imageio/config/__pycache__/extensions.cpython-312.pyc,, +imageio/config/__pycache__/plugins.cpython-312.pyc,, +imageio/config/extensions.py,sha256=_-jpfdRI8PtELEfqlKGEZNhjO27yp6TuZ2clUFehzn8,47022 +imageio/config/extensions.pyi,sha256=sLrA-wt09kPHBDJP79tGtEOX7XTcEEjRzA70O8BCsD0,605 +imageio/config/plugins.py,sha256=fh4AiZof4Z_chpixhCi37OHZEnNalt58v6CprgEmlOE,20277 +imageio/config/plugins.pyi,sha256=pzH8pacqU5uldsvYOee_nhd2Hkk3mR8VQBtjeVnkkHY,706 +imageio/core/__init__.py,sha256=PSkGH8K76ntSWhwM4j7W49UmCSZf_OGaSl9fNbQP7uQ,639 +imageio/core/__pycache__/__init__.cpython-312.pyc,, +imageio/core/__pycache__/fetching.cpython-312.pyc,, +imageio/core/__pycache__/findlib.cpython-312.pyc,, +imageio/core/__pycache__/format.cpython-312.pyc,, +imageio/core/__pycache__/imopen.cpython-312.pyc,, +imageio/core/__pycache__/legacy_plugin_wrapper.cpython-312.pyc,, +imageio/core/__pycache__/request.cpython-312.pyc,, +imageio/core/__pycache__/util.cpython-312.pyc,, +imageio/core/__pycache__/v3_plugin_api.cpython-312.pyc,, +imageio/core/fetching.py,sha256=r81yBsJMqkwAXeVAuQuAzbk9etWxQUEUe4__UUjpQpc,9176 +imageio/core/findlib.py,sha256=Zrhs0rEyp8p8iSIuCoBco0dCaB5dxJVZ4lRgv82Sqm0,5552 +imageio/core/format.py,sha256=glQcJOZHEOST3u0jOa338ZxJBX_daEe6xl7-UKxuU6E,30917 +imageio/core/format.pyi,sha256=5BZF-xwp5BmG8C5ahfL48z_a2MITN0509Uf6f1phZRw,3336 +imageio/core/imopen.py,sha256=SA4OJj93B09CHsKSILdH1w3zdVWvRSopNWlGlS0f4t0,9752 +imageio/core/imopen.pyi,sha256=8jLI2tKUTqFe79mccw95fRAIanJPHi6gQmzB2ClESlk,2215 +imageio/core/legacy_plugin_wrapper.py,sha256=CYGXhJY-18HkVYqyzlepM7NcZ9VLvBjFjNj64HOBqBM,12136 +imageio/core/legacy_plugin_wrapper.pyi,sha256=ENmdth_Avp2yTzuyInGWT2QXgAv72RrFRd6QH71LVqU,1064 +imageio/core/request.py,sha256=udbseSPuVNuv8AAam2j5Q6UNXngAhVq15T2l020amKY,27047 +imageio/core/request.pyi,sha256=ivqAXs3UfxhuXQfg8qsAtEVymCsppPwadztFzSXpIAo,2315 +imageio/core/util.py,sha256=lTVJMIbxF-6fInx0ExLuCeMDSVMfSUiSc6WTdP0bt3M,18739 +imageio/core/v3_plugin_api.py,sha256=w8wUjlT7_N6aU76DYGF3ubYYfUHTyfStvK5_xosZLPQ,15560 +imageio/freeze.py,sha256=hi9MNZz-ridgQBWcAqnd92sULek2lgmBSTmuott5lus,170 +imageio/plugins/__init__.py,sha256=GSxtio0ph5QHP2asdLvyzW8lVfiRqOii8kaqYsBO9CE,3469 +imageio/plugins/__pycache__/__init__.cpython-312.pyc,, +imageio/plugins/__pycache__/_bsdf.cpython-312.pyc,, +imageio/plugins/__pycache__/_dicom.cpython-312.pyc,, +imageio/plugins/__pycache__/_freeimage.cpython-312.pyc,, +imageio/plugins/__pycache__/_swf.cpython-312.pyc,, +imageio/plugins/__pycache__/_tifffile.cpython-312.pyc,, +imageio/plugins/__pycache__/bsdf.cpython-312.pyc,, +imageio/plugins/__pycache__/dicom.cpython-312.pyc,, +imageio/plugins/__pycache__/example.cpython-312.pyc,, +imageio/plugins/__pycache__/feisem.cpython-312.pyc,, +imageio/plugins/__pycache__/ffmpeg.cpython-312.pyc,, +imageio/plugins/__pycache__/fits.cpython-312.pyc,, +imageio/plugins/__pycache__/freeimage.cpython-312.pyc,, +imageio/plugins/__pycache__/freeimagemulti.cpython-312.pyc,, +imageio/plugins/__pycache__/gdal.cpython-312.pyc,, +imageio/plugins/__pycache__/grab.cpython-312.pyc,, +imageio/plugins/__pycache__/lytro.cpython-312.pyc,, +imageio/plugins/__pycache__/npz.cpython-312.pyc,, +imageio/plugins/__pycache__/opencv.cpython-312.pyc,, +imageio/plugins/__pycache__/pillow.cpython-312.pyc,, +imageio/plugins/__pycache__/pillow_info.cpython-312.pyc,, +imageio/plugins/__pycache__/pillow_legacy.cpython-312.pyc,, +imageio/plugins/__pycache__/pillowmulti.cpython-312.pyc,, +imageio/plugins/__pycache__/pyav.cpython-312.pyc,, +imageio/plugins/__pycache__/rawpy.cpython-312.pyc,, +imageio/plugins/__pycache__/simpleitk.cpython-312.pyc,, +imageio/plugins/__pycache__/spe.cpython-312.pyc,, +imageio/plugins/__pycache__/swf.cpython-312.pyc,, +imageio/plugins/__pycache__/tifffile.cpython-312.pyc,, +imageio/plugins/__pycache__/tifffile_v3.cpython-312.pyc,, +imageio/plugins/_bsdf.py,sha256=b-QjkZvz9DPDbygiKhee-47Ld2eOqxpYEdZ1mnrRPJ4,32753 +imageio/plugins/_dicom.py,sha256=NHXUH0e0gQfWpb8efxMg4hdH0O_tBPcjtlD7Djptu5o,34074 +imageio/plugins/_freeimage.py,sha256=GD25ZqqvbFnBILPRYHrTb5qbFsvXBVKv_qIE3139D68,51740 +imageio/plugins/_swf.py,sha256=kh3H2v98bgHpVagGNbhGUodh0s-weiESraX6qzMnD2k,25760 +imageio/plugins/_tifffile.py,sha256=J_j22qMzL8lRT85ykGRFGGkA5LPRi3YUz66wIH4qt90,371588 +imageio/plugins/bsdf.py,sha256=spISvLLVH319wDJ8YhYcvDTaJe2acElgWSvgqEkpd_g,12852 +imageio/plugins/dicom.py,sha256=mQYNbTyum4jVhjZQ8TU-4A5csHpQfT-BRBBCP5fu6Zs,12621 +imageio/plugins/example.py,sha256=4POb_LDQtSxHWxiflGqGKKKKrpItqLIFQeU8x7tro-c,5501 +imageio/plugins/feisem.py,sha256=AKwZv7Zac0_grnr-wnzU7R0Zf2KSUe91k06evPa1NI8,3360 +imageio/plugins/ffmpeg.py,sha256=N8Qq1TU5gr7U9IM-FCEuM9VIy1Jv875OC_XorStoOPI,29930 +imageio/plugins/fits.py,sha256=XnlmeC79sIiIPd_7IDx05-p3-b2unO4CVR0nWAA4ph0,4531 +imageio/plugins/freeimage.py,sha256=SuzYuGvCtZIiXIr51dWRTl5CATzRUqb8pNCSIg9YZv8,14645 +imageio/plugins/freeimagemulti.py,sha256=7jW3mJX-ZVnDqe2veIvU9wPY_x0EBOmPKP8ppPxRO_M,11288 +imageio/plugins/gdal.py,sha256=r2Ux7MQeHCUsmdk0aGENzGX8M5hCBU7NJomcf6G8FCU,1653 +imageio/plugins/grab.py,sha256=g6KbKVQUquHro_BW6He7NNmivVV-UtcsCJoDt3rdly0,2776 +imageio/plugins/lytro.py,sha256=V3dToE-eV6jLhtae26_uHHgOx6O1LsOo0hm7nnRptMM,25310 +imageio/plugins/npz.py,sha256=7ZQr-4lQEKbfjaF6rOmpq9pQgDTUHvkZa_NHZkJWBQo,2670 +imageio/plugins/opencv.py,sha256=C2nBQQFDXuz6LOyJ1P3-S6e_7h-pJgLow7h7w4Si2tg,11629 +imageio/plugins/pillow.py,sha256=4siuR0UENadfQgdQ2z5bFWX464KMzMcfqIEKEBDzt6M,22318 +imageio/plugins/pillow_info.py,sha256=Bt5iJtQnAh6mGViPIxhxRQPNidqay9-6BleAJZkhN1w,36624 +imageio/plugins/pillow_legacy.py,sha256=0tgk-8b5gduFjvNQN5WoK_-7EbVJ9i3-_kUVhaRLVnY,31580 +imageio/plugins/pillowmulti.py,sha256=-wsWpq0j2WXDgQGbyUuzCmw7iqSDz7e6AYqYhs46ZE8,11807 +imageio/plugins/pyav.py,sha256=R_shCM9q3QVvdKtuH53jcftLfNSL-2G0jAFKpCWxQkU,46354 +imageio/plugins/rawpy.py,sha256=o34WkwoU0LLpNDhj2kNuPS9ju6f7CBN-jKY9n0jLeDs,5948 +imageio/plugins/simpleitk.py,sha256=ldQWjkiCSZPoUnN87MtUqRIMMcIKmk8ZUeyDCQhnpG0,4107 +imageio/plugins/spe.py,sha256=UyXgHZV-3gwwU-RmJUhgDnJ843wt9H3S3Fjs84faz38,32172 +imageio/plugins/swf.py,sha256=0B9f-HF528OcHXTIF3nptoSJUu4GNId03rFLfFFOaFk,11756 +imageio/plugins/tifffile.py,sha256=m8qgNy-lJkwHwKkyp3pZn2xYsnRRwZ8FVMpM-BIs6dI,20665 +imageio/plugins/tifffile_v3.py,sha256=Vs2ngBBptUoJ6QpT9EjyNd4-dih8zzGEvcq2mRNYFXg,14335 +imageio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +imageio/testing.py,sha256=tkRPxZZpG68q_MAIux8WE8QeKbhbq6rDPVfCDsof1Ms,1597 +imageio/typing.py,sha256=qrvyFrVIs21bZCE0x802l1R-xCV4DlCNaTzPiJEZbzc,349 +imageio/v2.py,sha256=1KJ5z8Ji2nnAdy_K3vIpysG2Kg7rIcPiadNG1pwKx-E,21563 +imageio/v2.pyi,sha256=ROazbwu1rSJLBaEtXmUG2oT9BMr7ZlyyW26twgFWx5E,2250 +imageio/v3.py,sha256=ZE0IlERPT_4wryYqUOD4-LLc6dVpDZXV6N6JEQtbMiQ,9267 +imageio/v3.pyi,sha256=AtLP0IWqS-sX1qDyHPdjCCIsKGwXU5z41XOXzUj2pGQ,1344 diff --git a/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..79d5c89a71989389294854aa34e329701325f8b0 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.45.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa30161a1450bf11c7bfa6c548a23df8ff3636f5 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +imageio_download_bin = imageio.__main__:download_bin_main +imageio_remove_bin = imageio.__main__:remove_bin_main diff --git a/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a464e4cd37851148ffe3b7ae88921620c50cfe03 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio-2.37.0.dist-info/top_level.txt @@ -0,0 +1 @@ +imageio diff --git a/python_embeded/Lib/site-packages/imageio/__init__.py b/python_embeded/Lib/site-packages/imageio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..393e9c7cf5ce13b490f523a8cc981a0612b35fa6 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/__init__.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2014-2020, imageio contributors +# imageio is distributed under the terms of the (new) BSD License. + +# This docstring is used at the index of the documentation pages, and +# gets inserted into a slightly larger description (in setup.py) for +# the page on Pypi: +""" +Imageio is a Python library that provides an easy interface to read and +write a wide range of image data, including animated images, volumetric +data, and scientific formats. It is cross-platform, runs on Python 3.9+, +and is easy to install. + +Main website: https://imageio.readthedocs.io/ +""" + +# flake8: noqa + +__version__ = "2.37.0" + +import warnings + +# Load some bits from core +from .core import FormatManager, RETURN_BYTES + +# Instantiate the old format manager +formats = FormatManager() +show_formats = formats.show + +from . import v2 +from . import v3 +from . import plugins + +# import config after core to avoid circular import +from . import config + +# import all APIs into the top level (meta API) +from .v2 import ( + imread as imread_v2, + mimread, + volread, + mvolread, + imwrite, + mimwrite, + volwrite, + mvolwrite, + # aliases + get_reader as read, + get_writer as save, + imwrite as imsave, + mimwrite as mimsave, + volwrite as volsave, + mvolwrite as mvolsave, + # misc + help, + get_reader, + get_writer, +) +from .v3 import ( + imopen, + # imread, # Will take over once v3 is released + # imwrite, # Will take over once v3 is released + imiter, +) + + +def imread(uri, format=None, **kwargs): + """imread(uri, format=None, **kwargs) + + Reads an image from the specified file. Returns a numpy array, which + comes with a dict of meta data at its 'meta' attribute. + + Note that the image data is returned as-is, and may not always have + a dtype of uint8 (and thus may differ from what e.g. PIL returns). + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the image from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + kwargs : ... + Further keyword arguments are passed to the reader. See :func:`.help` + to see what arguments are available for a particular format. + """ + + warnings.warn( + "Starting with ImageIO v3 the behavior of this function will switch to that of" + " iio.v3.imread. To keep the current behavior (and make this warning disappear)" + " use `import imageio.v2 as imageio` or call `imageio.v2.imread` directly.", + DeprecationWarning, + stacklevel=2, + ) + + return imread_v2(uri, format=format, **kwargs) + + +__all__ = [ + "v2", + "v3", + "config", + "plugins", + # v3 API + "imopen", + "imread", + "imwrite", + "imiter", + # v2 API + "mimread", + "volread", + "mvolread", + "imwrite", + "mimwrite", + "volwrite", + "mvolwrite", + # v2 aliases + "read", + "save", + "imsave", + "mimsave", + "volsave", + "mvolsave", + # functions to deprecate + "help", + "get_reader", + "get_writer", + "formats", + "show_formats", +] diff --git a/python_embeded/Lib/site-packages/imageio/__main__.py b/python_embeded/Lib/site-packages/imageio/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad0ea0b5dc9976351a59f34d4e720dfc5a7c5a53 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/__main__.py @@ -0,0 +1,169 @@ +""" +Console scripts and associated helper methods for imageio. +""" + +import argparse +import os +from os import path as op +import shutil +import sys + + +from . import plugins +from .core import util + +# A list of plugins that require binaries from the imageio-binaries +# repository. These plugins must implement the `download` method. +PLUGINS_WITH_BINARIES = ["freeimage"] + + +def download_bin(plugin_names=["all"], package_dir=False): + """Download binary dependencies of plugins + + This is a convenience method for downloading the binaries + (e.g. for freeimage) from the imageio-binaries + repository. + + Parameters + ---------- + plugin_names: list + A list of imageio plugin names. If it contains "all", all + binary dependencies are downloaded. + package_dir: bool + If set to `True`, the binaries will be downloaded to the + `resources` directory of the imageio package instead of + to the users application data directory. Note that this + might require administrative rights if imageio is installed + in a system directory. + """ + if plugin_names.count("all"): + # Use all plugins + plugin_names = PLUGINS_WITH_BINARIES + + plugin_names.sort() + print("Ascertaining binaries for: {}.".format(", ".join(plugin_names))) + + if package_dir: + # Download the binaries to the `resources` directory + # of imageio. If imageio comes as an .egg, then a cache + # directory will be created by pkg_resources (requires setuptools). + # see `imageio.core.util.resource_dirs` + # and `imageio.core.utilresource_package_dir` + directory = util.resource_package_dir() + else: + directory = None + + for plg in plugin_names: + if plg not in PLUGINS_WITH_BINARIES: + msg = "Plugin {} not registered for binary download!".format(plg) + raise Exception(msg) + mod = getattr(plugins, plg) + mod.download(directory=directory) + + +def download_bin_main(): + """Argument-parsing wrapper for `download_bin`""" + description = "Download plugin binary dependencies" + phelp = ( + "Plugin name for which to download the binary. " + + "If no argument is given, all binaries are downloaded." + ) + dhelp = ( + "Download the binaries to the package directory " + + "(default is the users application data directory). " + + "This might require administrative rights." + ) + example_text = ( + "examples:\n" + + " imageio_download_bin all\n" + + " imageio_download_bin freeimage\n" + ) + parser = argparse.ArgumentParser( + description=description, + epilog=example_text, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument("plugin", type=str, nargs="*", default="all", help=phelp) + parser.add_argument( + "--package-dir", + dest="package_dir", + action="store_true", + default=False, + help=dhelp, + ) + args = parser.parse_args() + download_bin(plugin_names=args.plugin, package_dir=args.package_dir) + + +def remove_bin(plugin_names=["all"]): + """Remove binary dependencies of plugins + + This is a convenience method that removes all binaries + dependencies for plugins downloaded by imageio. + + Notes + ----- + It only makes sense to use this method if the binaries + are corrupt. + """ + if plugin_names.count("all"): + # Use all plugins + plugin_names = PLUGINS_WITH_BINARIES + + print("Removing binaries for: {}.".format(", ".join(plugin_names))) + + rdirs = util.resource_dirs() + + for plg in plugin_names: + if plg not in PLUGINS_WITH_BINARIES: + msg = "Plugin {} not registered for binary download!".format(plg) + raise Exception(msg) + + not_removed = [] + for rd in rdirs: + # plugin name is in subdirectories + for rsub in os.listdir(rd): + if rsub in plugin_names: + plgdir = op.join(rd, rsub) + try: + shutil.rmtree(plgdir) + except Exception: + not_removed.append(plgdir) + if not_removed: + nrs = ",".join(not_removed) + msg2 = ( + "These plugins files could not be removed: {}\n".format(nrs) + + "Make sure they are not used by any program and try again." + ) + raise Exception(msg2) + + +def remove_bin_main(): + """Argument-parsing wrapper for `remove_bin`""" + description = "Remove plugin binary dependencies" + phelp = ( + "Plugin name for which to remove the binary. " + + "If no argument is given, all binaries are removed." + ) + example_text = ( + "examples:\n" + + " imageio_remove_bin all\n" + + " imageio_remove_bin freeimage\n" + ) + parser = argparse.ArgumentParser( + description=description, + epilog=example_text, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument("plugin", type=str, nargs="*", default="all", help=phelp) + args = parser.parse_args() + remove_bin(plugin_names=args.plugin) + + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] == "download_bin": + download_bin_main() + elif len(sys.argv) > 1 and sys.argv[1] == "remove_bin": + remove_bin_main() + else: + raise RuntimeError("Invalid use of the imageio CLI") diff --git a/python_embeded/Lib/site-packages/imageio/freeze.py b/python_embeded/Lib/site-packages/imageio/freeze.py new file mode 100644 index 0000000000000000000000000000000000000000..3753a29df665e416030b4eb0453ed3430a4c78fc --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/freeze.py @@ -0,0 +1,11 @@ +""" +Helper functions for freezing imageio. +""" + + +def get_includes(): + return ["email", "urllib.request", "numpy", "zipfile", "io"] + + +def get_excludes(): + return [] diff --git a/python_embeded/Lib/site-packages/imageio/py.typed b/python_embeded/Lib/site-packages/imageio/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/imageio/testing.py b/python_embeded/Lib/site-packages/imageio/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..535b1386d92d5f452826d3d05f7e93059607a759 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/testing.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# Distributed under the (new) BSD License. See LICENSE.txt for more info. + +""" Functionality used for testing. This code itself is not covered in tests. +""" + +import os +import sys +import pytest + +# Get root dir +THIS_DIR = os.path.abspath(os.path.dirname(__file__)) +ROOT_DIR = THIS_DIR +for i in range(9): + ROOT_DIR = os.path.dirname(ROOT_DIR) + if os.path.isfile(os.path.join(ROOT_DIR, ".gitignore")): + break + + +# Functions to use from invoke tasks + + +def test_unit(cov_report="term"): + """Run all unit tests. Returns exit code.""" + orig_dir = os.getcwd() + os.chdir(ROOT_DIR) + try: + _clear_imageio() + _enable_faulthandler() + return pytest.main( + [ + "-v", + "--cov", + "imageio", + "--cov-config", + ".coveragerc", + "--cov-report", + cov_report, + "tests", + ] + ) + finally: + os.chdir(orig_dir) + import imageio + + print("Tests were performed on", str(imageio)) + + +# Requirements + + +def _enable_faulthandler(): + """Enable faulthandler (if we can), so that we get tracebacks + on segfaults. + """ + try: + import faulthandler + + faulthandler.enable() + print("Faulthandler enabled") + except Exception: + print("Could not enable faulthandler") + + +def _clear_imageio(): + # Remove ourselves from sys.modules to force an import + for key in list(sys.modules.keys()): + if key.startswith("imageio"): + del sys.modules[key] diff --git a/python_embeded/Lib/site-packages/imageio/typing.py b/python_embeded/Lib/site-packages/imageio/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..1e97d5b1d8079059a2e3b1f4674b878e17534f24 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/typing.py @@ -0,0 +1,17 @@ +from io import BytesIO +from typing import Union, BinaryIO +from pathlib import Path + +try: + from numpy.typing import ArrayLike +except ImportError: + # numpy<1.20 fall back to using ndarray + from numpy import ndarray as ArrayLike + +ImageResource = Union[str, bytes, BytesIO, Path, BinaryIO] + + +__all__ = [ + "ArrayLike", + "ImageResource", +] diff --git a/python_embeded/Lib/site-packages/imageio/v2.py b/python_embeded/Lib/site-packages/imageio/v2.py new file mode 100644 index 0000000000000000000000000000000000000000..db2963b7cb3a634bbb9d25ddbb0f64f95dd9391a --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/v2.py @@ -0,0 +1,676 @@ +# -*- coding: utf-8 -*- +# imageio is distributed under the terms of the (new) BSD License. + +import re +import warnings +from numbers import Number +from pathlib import Path +from typing import Dict + +import numpy as np + +from imageio.core.legacy_plugin_wrapper import LegacyPlugin +from imageio.core.util import Array +from imageio.core.v3_plugin_api import PluginV3 + +from . import formats +from .config import known_extensions, known_plugins +from .core import RETURN_BYTES +from .core.imopen import imopen + +MEMTEST_DEFAULT_MIM = "256MB" +MEMTEST_DEFAULT_MVOL = "1GB" + + +mem_re = re.compile(r"^(\d+\.?\d*)\s*([kKMGTPEZY]?i?)B?$") +sizes = {"": 1, None: 1} +for i, si in enumerate([""] + list("kMGTPEZY")): + sizes[si] = 1000**i + if si: + sizes[si.upper() + "i"] = 1024**i + + +def to_nbytes(arg, default=None): + if not arg: + arg = float("inf") + + if arg is True: + arg = default + + if isinstance(arg, Number): + return arg + + match = mem_re.match(arg) + if match is None: + raise ValueError( + "Memory size could not be parsed " + "(is your capitalisation correct?): {}".format(arg) + ) + + num, unit = match.groups() + + try: + return float(num) * sizes[unit] + except KeyError: # pragma: no cover + # Note: I don't think we can reach this + raise ValueError( + "Memory size unit not recognised " + "(is your capitalisation correct?): {}".format(unit) + ) + + +def help(name=None): + """help(name=None) + + Print the documentation of the format specified by name, or a list + of supported formats if name is omitted. + + Parameters + ---------- + name : str + Can be the name of a format, a filename extension, or a full + filename. See also the :doc:`formats page <../formats/index>`. + """ + if not name: + print(formats) + else: + print(formats[name]) + + +def decypher_format_arg(format_name: str) -> Dict[str, str]: + """Split format into plugin and format + + The V2 API aliases plugins and supported formats. This function + splits these so that they can be fed separately to `iio.imopen`. + + """ + + plugin = None + extension = None + + if format_name is None: + pass # nothing to do + elif Path(format_name).suffix.lower() in known_extensions: + extension = Path(format_name).suffix.lower() + elif format_name in known_plugins: + plugin = format_name + elif format_name.upper() in known_plugins: + plugin = format_name.upper() + elif format_name.lower() in known_extensions: + extension = format_name.lower() + elif "." + format_name.lower() in known_extensions: + extension = "." + format_name.lower() + else: + raise IndexError(f"No format known by name `{plugin}`.") + + return {"plugin": plugin, "extension": extension} + + +class LegacyReader: + def __init__(self, plugin_instance: PluginV3, **kwargs): + self.instance = plugin_instance + self.last_index = 0 + self.closed = False + + if ( + type(self.instance).__name__ == "PillowPlugin" + and kwargs.get("pilmode") is not None + ): + kwargs["mode"] = kwargs["pilmode"] + del kwargs["pilmode"] + + self.read_args = kwargs + + def close(self): + if not self.closed: + self.instance.close() + self.closed = True + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + + def __del__(self): + self.close() + + @property + def request(self): + return self.instance.request + + @property + def format(self): + raise TypeError("V3 Plugins don't have a format.") + + def get_length(self): + return self.instance.properties(index=...).n_images + + def get_data(self, index): + self.last_index = index + img = self.instance.read(index=index, **self.read_args) + metadata = self.instance.metadata(index=index, exclude_applied=False) + return Array(img, metadata) + + def get_next_data(self): + return self.get_data(self.last_index + 1) + + def set_image_index(self, index): + self.last_index = index - 1 + + def get_meta_data(self, index=None): + return self.instance.metadata(index=index, exclude_applied=False) + + def iter_data(self): + for idx, img in enumerate(self.instance.iter()): + metadata = self.instance.metadata(index=idx, exclude_applied=False) + yield Array(img, metadata) + + def __iter__(self): + return self.iter_data() + + def __len__(self): + return self.get_length() + + +class LegacyWriter: + def __init__(self, plugin_instance: PluginV3, **kwargs): + self.instance = plugin_instance + self.last_index = 0 + self.closed = False + + if type(self.instance).__name__ == "PillowPlugin" and "pilmode" in kwargs: + kwargs["mode"] = kwargs["pilmode"] + del kwargs["pilmode"] + + self.write_args = kwargs + + def close(self): + if not self.closed: + self.instance.close() + self.closed = True + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + + def __del__(self): + self.close() + + @property + def request(self): + return self.instance.request + + @property + def format(self): + raise TypeError("V3 Plugins don't have a format.") + + def append_data(self, im, meta=None): + # TODO: write metadata in the future; there is currently no + # generic way to do this with v3 plugins :( + if meta is not None: + warnings.warn( + "V3 Plugins currently don't have a uniform way to" + " write metadata, so any metadata is ignored." + ) + + # total_meta = dict() + # if meta is None: + # meta = {} + # if hasattr(im, "meta") and isinstance(im.meta, dict): + # total_meta.update(im.meta) + # total_meta.update(meta) + + return self.instance.write(im, **self.write_args) + + def set_meta_data(self, meta): + # TODO: write metadata + raise NotImplementedError( + "V3 Plugins don't have a uniform way to write metadata (yet)." + ) + + +def is_batch(ndimage): + if isinstance(ndimage, (list, tuple)): + return True + + ndimage = np.asarray(ndimage) + if ndimage.ndim <= 2: + return False + elif ndimage.ndim == 3 and ndimage.shape[2] < 5: + return False + + return True + + +def is_volume(ndimage): + ndimage = np.asarray(ndimage) + if not is_batch(ndimage): + return False + + if ndimage.ndim == 3 and ndimage.shape[2] >= 5: + return True + elif ndimage.ndim == 4 and ndimage.shape[3] < 5: + return True + else: + return False + + +# Base functions that return a reader/writer + + +def get_reader(uri, format=None, mode="?", **kwargs): + """get_reader(uri, format=None, mode='?', **kwargs) + + Returns a :class:`.Reader` object which can be used to read data + and meta data from the specified file. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the image from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + mode : {'i', 'I', 'v', 'V', '?'} + Used to give the reader a hint on what the user expects (default "?"): + "i" for an image, "I" for multiple images, "v" for a volume, + "V" for multiple volumes, "?" for don't care. + kwargs : ... + Further keyword arguments are passed to the reader. See :func:`.help` + to see what arguments are available for a particular format. + """ + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + + image_file = imopen(uri, "r" + mode, **imopen_args) + + if isinstance(image_file, LegacyPlugin): + return image_file.legacy_get_reader(**kwargs) + else: + return LegacyReader(image_file, **kwargs) + + +def get_writer(uri, format=None, mode="?", **kwargs): + """get_writer(uri, format=None, mode='?', **kwargs) + + Returns a :class:`.Writer` object which can be used to write data + and meta data to the specified file. + + Parameters + ---------- + uri : {str, pathlib.Path, file} + The resource to write the image to, e.g. a filename, pathlib.Path + or file object, see the docs for more info. + format : str + The format to use to write the file. By default imageio selects + the appropriate for you based on the filename. + mode : {'i', 'I', 'v', 'V', '?'} + Used to give the writer a hint on what the user expects (default '?'): + "i" for an image, "I" for multiple images, "v" for a volume, + "V" for multiple volumes, "?" for don't care. + kwargs : ... + Further keyword arguments are passed to the writer. See :func:`.help` + to see what arguments are available for a particular format. + """ + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + + image_file = imopen(uri, "w" + mode, **imopen_args) + if isinstance(image_file, LegacyPlugin): + return image_file.legacy_get_writer(**kwargs) + else: + return LegacyWriter(image_file, **kwargs) + + +# Images + + +def imread(uri, format=None, **kwargs): + """imread(uri, format=None, **kwargs) + + Reads an image from the specified file. Returns a numpy array, which + comes with a dict of meta data at its 'meta' attribute. + + Note that the image data is returned as-is, and may not always have + a dtype of uint8 (and thus may differ from what e.g. PIL returns). + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the image from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + kwargs : ... + Further keyword arguments are passed to the reader. See :func:`.help` + to see what arguments are available for a particular format. + """ + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + + with imopen(uri, "ri", **imopen_args) as file: + result = file.read(index=0, **kwargs) + + return result + + +def imwrite(uri, im, format=None, **kwargs): + """imwrite(uri, im, format=None, **kwargs) + + Write an image to the specified file. + + Parameters + ---------- + uri : {str, pathlib.Path, file} + The resource to write the image to, e.g. a filename, pathlib.Path + or file object, see the docs for more info. + im : numpy.ndarray + The image data. Must be NxM, NxMx3 or NxMx4. + format : str + The format to use to write the file. By default imageio selects + the appropriate for you based on the filename and its contents. + kwargs : ... + Further keyword arguments are passed to the writer. See :func:`.help` + to see what arguments are available for a particular format. + """ + + # Test image + imt = type(im) + im = np.asarray(im) + if not np.issubdtype(im.dtype, np.number): + raise ValueError("Image is not numeric, but {}.".format(imt.__name__)) + + if is_batch(im) or im.ndim < 2: + raise ValueError("Image must be 2D (grayscale, RGB, or RGBA).") + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + with imopen(uri, "wi", **imopen_args) as file: + return file.write(im, **kwargs) + + +# Multiple images + + +def mimread(uri, format=None, memtest=MEMTEST_DEFAULT_MIM, **kwargs): + """mimread(uri, format=None, memtest="256MB", **kwargs) + + Reads multiple images from the specified file. Returns a list of + numpy arrays, each with a dict of meta data at its 'meta' attribute. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the images from, e.g. a filename,pathlib.Path, + http address or file object, see the docs for more info. + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + memtest : {bool, int, float, str} + If truthy, this function will raise an error if the resulting + list of images consumes greater than the amount of memory specified. + This is to protect the system from using so much memory that it needs + to resort to swapping, and thereby stall the computer. E.g. + ``mimread('hunger_games.avi')``. + + If the argument is a number, that will be used as the threshold number + of bytes. + + If the argument is a string, it will be interpreted as a number of bytes with + SI/IEC prefixed units (e.g. '1kB', '250MiB', '80.3YB'). + + - Units are case sensitive + - k, M etc. represent a 1000-fold change, where Ki, Mi etc. represent 1024-fold + - The "B" is optional, but if present, must be capitalised + + If the argument is True, the default will be used, for compatibility reasons. + + Default: '256MB' + kwargs : ... + Further keyword arguments are passed to the reader. See :func:`.help` + to see what arguments are available for a particular format. + """ + + # used for mimread and mvolread + nbyte_limit = to_nbytes(memtest, MEMTEST_DEFAULT_MIM) + + images = list() + nbytes = 0 + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + with imopen(uri, "rI", **imopen_args) as file: + for image in file.iter(**kwargs): + images.append(image) + nbytes += image.nbytes + if nbytes > nbyte_limit: + raise RuntimeError( + "imageio.mimread() has read over {}B of " + "image data.\nStopped to avoid memory problems." + " Use imageio.get_reader(), increase threshold, or memtest=False".format( + int(nbyte_limit) + ) + ) + + if len(images) == 1 and is_batch(images[0]): + images = [*images[0]] + + return images + + +def mimwrite(uri, ims, format=None, **kwargs): + """mimwrite(uri, ims, format=None, **kwargs) + + Write multiple images to the specified file. + + Parameters + ---------- + uri : {str, pathlib.Path, file} + The resource to write the images to, e.g. a filename, pathlib.Path + or file object, see the docs for more info. + ims : sequence of numpy arrays + The image data. Each array must be NxM, NxMx3 or NxMx4. + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + kwargs : ... + Further keyword arguments are passed to the writer. See :func:`.help` + to see what arguments are available for a particular format. + """ + + if not is_batch(ims): + raise ValueError("Image data must be a sequence of ndimages.") + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + with imopen(uri, "wI", **imopen_args) as file: + return file.write(ims, is_batch=True, **kwargs) + + +# Volumes + + +def volread(uri, format=None, **kwargs): + """volread(uri, format=None, **kwargs) + + Reads a volume from the specified file. Returns a numpy array, which + comes with a dict of meta data at its 'meta' attribute. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the volume from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + kwargs : ... + Further keyword arguments are passed to the reader. See :func:`.help` + to see what arguments are available for a particular format. + """ + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + with imopen(uri, "rv", **imopen_args) as file: + return file.read(index=0, **kwargs) + + +def volwrite(uri, im, format=None, **kwargs): + """volwrite(uri, vol, format=None, **kwargs) + + Write a volume to the specified file. + + Parameters + ---------- + uri : {str, pathlib.Path, file} + The resource to write the image to, e.g. a filename, pathlib.Path + or file object, see the docs for more info. + vol : numpy.ndarray + The image data. Must be NxMxL (or NxMxLxK if each voxel is a tuple). + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + kwargs : ... + Further keyword arguments are passed to the writer. See :func:`.help` + to see what arguments are available for a particular format. + """ + + # Test image + im = np.asarray(im) + if not is_volume(im): + raise ValueError("Image must be 3D, or 4D if each voxel is a tuple.") + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + + with imopen(uri, "wv", **imopen_args) as file: + return file.write(im, is_batch=False, **kwargs) + + +# Multiple volumes + + +def mvolread(uri, format=None, memtest=MEMTEST_DEFAULT_MVOL, **kwargs): + """mvolread(uri, format=None, memtest='1GB', **kwargs) + + Reads multiple volumes from the specified file. Returns a list of + numpy arrays, each with a dict of meta data at its 'meta' attribute. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the volumes from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + memtest : {bool, int, float, str} + If truthy, this function will raise an error if the resulting + list of images consumes greater than the amount of memory specified. + This is to protect the system from using so much memory that it needs + to resort to swapping, and thereby stall the computer. E.g. + ``mimread('hunger_games.avi')``. + + If the argument is a number, that will be used as the threshold number + of bytes. + + If the argument is a string, it will be interpreted as a number of bytes with + SI/IEC prefixed units (e.g. '1kB', '250MiB', '80.3YB'). + + - Units are case sensitive + - k, M etc. represent a 1000-fold change, where Ki, Mi etc. represent 1024-fold + - The "B" is optional, but if present, must be capitalised + + If the argument is True, the default will be used, for compatibility reasons. + + Default: '1GB' + kwargs : ... + Further keyword arguments are passed to the reader. See :func:`.help` + to see what arguments are available for a particular format. + """ + + # used for mimread and mvolread + nbyte_limit = to_nbytes(memtest, MEMTEST_DEFAULT_MVOL) + + images = list() + nbytes = 0 + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + with imopen(uri, "rV", **imopen_args) as file: + for image in file.iter(**kwargs): + images.append(image) + nbytes += image.nbytes + if nbytes > nbyte_limit: + raise RuntimeError( + "imageio.mimread() has read over {}B of " + "image data.\nStopped to avoid memory problems." + " Use imageio.get_reader(), increase threshold, or memtest=False".format( + int(nbyte_limit) + ) + ) + + return images + + +def mvolwrite(uri, ims, format=None, **kwargs): + """mvolwrite(uri, vols, format=None, **kwargs) + + Write multiple volumes to the specified file. + + Parameters + ---------- + uri : {str, pathlib.Path, file} + The resource to write the volumes to, e.g. a filename, pathlib.Path + or file object, see the docs for more info. + ims : sequence of numpy arrays + The image data. Each array must be NxMxL (or NxMxLxK if each + voxel is a tuple). + format : str + The format to use to read the file. By default imageio selects + the appropriate for you based on the filename and its contents. + kwargs : ... + Further keyword arguments are passed to the writer. See :func:`.help` + to see what arguments are available for a particular format. + """ + + for im in ims: + if not is_volume(im): + raise ValueError("Image must be 3D, or 4D if each voxel is a tuple.") + + imopen_args = decypher_format_arg(format) + imopen_args["legacy_mode"] = True + with imopen(uri, "wV", **imopen_args) as file: + return file.write(ims, is_batch=True, **kwargs) + + +# aliases +read = get_reader +save = get_writer +imsave = imwrite +mimsave = mimwrite +volsave = volwrite +mvolsave = mvolwrite + +__all__ = [ + "imread", + "mimread", + "volread", + "mvolread", + "imwrite", + "mimwrite", + "volwrite", + "mvolwrite", + # misc + "help", + "get_reader", + "get_writer", + "RETURN_BYTES", +] diff --git a/python_embeded/Lib/site-packages/imageio/v2.pyi b/python_embeded/Lib/site-packages/imageio/v2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..19adc32ef07c8864679a9d70578342bfd7823037 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/v2.pyi @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +# imageio is distributed under the terms of the (new) BSD License. + +from typing import Dict, Literal, Union, List, overload + +import numpy as np + +from .core.imopen import imopen +from .core import RETURN_BYTES, Array +from .typing import ImageResource, ArrayLike +from .core.format import Format + +MEMTEST_DEFAULT_MIM = "256MB" +MEMTEST_DEFAULT_MVOL = "1GB" + +def to_nbytes(arg: float = None, default=None) -> float: ... +def help(name=None) -> None: ... +def decypher_format_arg(format_name: Union[str, None]) -> Dict[str, str]: ... +def get_reader( + uri: ImageResource, format: Format = None, mode: str = "?", **kwargs +) -> Format.Reader: ... +def get_writer( + uri: ImageResource, format: Format = None, mode: str = "?", **kwargs +) -> Format.Writer: ... +def imread(uri: ImageResource, format: Format = None, **kwargs) -> Array: ... +@overload +def imwrite( + uri: Literal[""], im: ArrayLike, format: Format = None, **kwargs +) -> bytes: ... +@overload +def imwrite( + uri: ImageResource, im: ArrayLike, format: Format = None, **kwargs +) -> None: ... +def mimread( + uri: ImageResource, format: Format = None, memtest=MEMTEST_DEFAULT_MIM, **kwargs +) -> List[Array]: ... +@overload +def mimwrite( + uri: Literal[""], ims: List[ArrayLike], format: Format = None, **kwargs +) -> bytes: ... +@overload +def mimwrite( + uri: ImageResource, ims: List[ArrayLike], format: Format = None, **kwargs +) -> None: ... +def volread(uri: ImageResource, format: Format = None, **kwargs) -> Array: ... +@overload +def volwrite( + uri: Literal[""], im: ArrayLike, format: Format = None, **kwargs +) -> bytes: ... +@overload +def volwrite( + uri: ImageResource, im: ArrayLike, format: Format = None, **kwargs +) -> None: ... +def mvolread( + uri: ImageResource, + format: Format = None, + memtest: float = MEMTEST_DEFAULT_MVOL, + **kwargs +) -> List[Array]: ... +@overload +def mvolwrite( + uri: Literal[""], ims: List[ArrayLike], format: Format = None, **kwargs +) -> bytes: ... +@overload +def mvolwrite( + uri: ImageResource, ims: List[ArrayLike], format: Format = None, **kwargs +) -> None: ... + +# aliases +read = get_reader +save = get_writer +imsave = imwrite +mimsave = mimwrite +volsave = volwrite +mvolsave = mvolwrite diff --git a/python_embeded/Lib/site-packages/imageio/v3.py b/python_embeded/Lib/site-packages/imageio/v3.py new file mode 100644 index 0000000000000000000000000000000000000000..65d36e57fbf6f935981cbeeb710f078df8872206 --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/v3.py @@ -0,0 +1,259 @@ +import numpy as np + +from .core.imopen import imopen + + +def imread(uri, *, index=None, plugin=None, extension=None, format_hint=None, **kwargs): + """Read an ndimage from a URI. + + Opens the given URI and reads an ndimage from it. The exact behavior + depends on both the file type and plugin used to open the file. To learn + about the exact behavior, check the documentation of the relevant plugin. + Typically, imread attempts to read all data stored in the URI. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the image from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + index : {int, Ellipsis, None} + If the ImageResource contains multiple ndimages, and index is an + integer, select the index-th ndimage from among them and return it. If + index is an ellipsis (...), read all ndimages in the file and stack them + along a new batch dimension. If index is None, let the plugin decide. + plugin : {str, None} + The plugin to use. If set to None (default) imread will perform a + search for a matching plugin. If not None, this takes priority over + the provided format hint (if present). + extension : str + If not None, treat the provided ImageResource as if it had the given + extension. This affects the order in which backends are considered. + format_hint : str + Deprecated. Use `extension` instead. + **kwargs : + Additional keyword arguments will be passed to the plugin's read call. + + Returns + ------- + image : ndimage + The ndimage located at the given URI. + """ + + plugin_kwargs = { + "legacy_mode": False, + "plugin": plugin, + "format_hint": format_hint, + "extension": extension, + } + + call_kwargs = kwargs + if index is not None: + call_kwargs["index"] = index + + with imopen(uri, "r", **plugin_kwargs) as img_file: + return np.asarray(img_file.read(**call_kwargs)) + + +def imiter(uri, *, plugin=None, extension=None, format_hint=None, **kwargs): + """Read a sequence of ndimages from a URI. + + Returns an iterable that yields ndimages from the given URI. The exact + behavior depends on both, the file type and plugin used to open the file. + To learn about the exact behavior, check the documentation of the relevant + plugin. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the image from, e.g. a filename, pathlib.Path, + http address or file object, see the docs for more info. + plugin : {str, None} + The plugin to use. If set to None (default) imiter will perform a + search for a matching plugin. If not None, this takes priority over + the provided format hint (if present). + extension : str + If not None, treat the provided ImageResource as if it had the given + extension. This affects the order in which backends are considered. + format_hint : str + Deprecated. Use `extension` instead. + **kwargs : + Additional keyword arguments will be passed to the plugin's ``iter`` + call. + + Yields + ------ + image : ndimage + The next ndimage located at the given URI. + + """ + + with imopen( + uri, + "r", + legacy_mode=False, + plugin=plugin, + format_hint=format_hint, + extension=extension, + ) as img_file: + for image in img_file.iter(**kwargs): + # Note: casting to ndarray here to ensure compatibility + # with the v2.9 API + yield np.asarray(image) + + +def imwrite(uri, image, *, plugin=None, extension=None, format_hint=None, **kwargs): + """Write an ndimage to the given URI. + + The exact behavior depends on the file type and plugin used. To learn about + the exact behavior, check the documentation of the relevant plugin. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to save the image to, e.g. a filename, pathlib.Path, + http address or file object, check the docs for more info. + image : np.ndarray + The image to write to disk. + plugin : {str, None} + The plugin to use. If set to None (default) imwrite will perform a + search for a matching plugin. If not None, this takes priority over + the provided format hint (if present). + extension : str + If not None, treat the provided ImageResource as if it had the given + extension. This affects the order in which backends are considered, and + may also influence the format used when encoding. + format_hint : str + Deprecated. Use `extension` instead. + **kwargs : + Additional keyword arguments will be passed to the plugin's ``write`` + call. + + Returns + ------- + encoded_image : None or Bytes + Returns ``None`` in all cases, except when ``uri`` is set to ````. + In this case it returns the encoded ndimage as a bytes string. + + """ + + with imopen( + uri, + "w", + legacy_mode=False, + plugin=plugin, + format_hint=format_hint, + extension=extension, + ) as img_file: + encoded = img_file.write(image, **kwargs) + + return encoded + + +def improps(uri, *, index=None, plugin=None, extension=None, **kwargs): + """Read standardized metadata. + + Opens the given URI and reads the properties of an ndimage from it. The + properties represent standardized metadata. This means that they will have + the same name regardless of the format being read or plugin/backend being + used. Further, any field will be, where possible, populated with a sensible + default (may be `None`) if the ImageResource does not declare a value in its + metadata. + + Parameters + ---------- + index : int + If the ImageResource contains multiple ndimages, and index is an + integer, select the index-th ndimage from among them and return its + properties. If index is an ellipsis (...), read all ndimages in the file + and stack them along a new batch dimension and return their properties. + If index is None, let the plugin decide. + plugin : {str, None} + The plugin to be used. If None, performs a search for a matching + plugin. + extension : str + If not None, treat the provided ImageResource as if it had the given + extension. This affects the order in which backends are considered. + **kwargs : + Additional keyword arguments will be passed to the plugin's ``properties`` + call. + + Returns + ------- + properties : ImageProperties + A dataclass filled with standardized image metadata. + + Notes + ----- + Where possible, this will avoid loading pixel data. + + See Also + -------- + imageio.core.v3_plugin_api.ImageProperties + + """ + + plugin_kwargs = {"legacy_mode": False, "plugin": plugin, "extension": extension} + + call_kwargs = kwargs + if index is not None: + call_kwargs["index"] = index + + with imopen(uri, "r", **plugin_kwargs) as img_file: + properties = img_file.properties(**call_kwargs) + + return properties + + +def immeta( + uri, *, index=None, plugin=None, extension=None, exclude_applied=True, **kwargs +): + """Read format-specific metadata. + + Opens the given URI and reads metadata for an ndimage from it. The contents + of the returned metadata dictionary is specific to both the image format and + plugin used to open the ImageResource. To learn about the exact behavior, + check the documentation of the relevant plugin. Typically, immeta returns a + dictionary specific to the image format, where keys match metadata field + names and values are a field's contents. + + Parameters + ---------- + uri : {str, pathlib.Path, bytes, file} + The resource to load the image from, e.g. a filename, pathlib.Path, http + address or file object, see the docs for more info. + index : {int, None} + If the ImageResource contains multiple ndimages, and index is an + integer, select the index-th ndimage from among them and return its + metadata. If index is an ellipsis (...), return global metadata. If + index is None, let the plugin decide the default. + plugin : {str, None} + The plugin to be used. If None (default), performs a search for a + matching plugin. + extension : str + If not None, treat the provided ImageResource as if it had the given + extension. This affects the order in which backends are considered. + **kwargs : + Additional keyword arguments will be passed to the plugin's metadata + method. + + Returns + ------- + image : ndimage + The ndimage located at the given URI. + + """ + + plugin_kwargs = {"legacy_mode": False, "plugin": plugin, "extension": extension} + + call_kwargs = kwargs + call_kwargs["exclude_applied"] = exclude_applied + if index is not None: + call_kwargs["index"] = index + + with imopen(uri, "r", **plugin_kwargs) as img_file: + metadata = img_file.metadata(**call_kwargs) + + return metadata + + +__all__ = ["imopen", "imread", "imwrite", "imiter", "improps", "immeta"] diff --git a/python_embeded/Lib/site-packages/imageio/v3.pyi b/python_embeded/Lib/site-packages/imageio/v3.pyi new file mode 100644 index 0000000000000000000000000000000000000000..339e33e12f67af086b671ccf4f2e638ae914799e --- /dev/null +++ b/python_embeded/Lib/site-packages/imageio/v3.pyi @@ -0,0 +1,62 @@ +from typing import Any, Dict, Iterator, List, Literal, Optional, Union, overload + +import numpy as np + +from .core.imopen import imopen as imopen +from .core.v3_plugin_api import ImageProperties +from .typing import ArrayLike, ImageResource + +def imread( + uri: ImageResource, + *, + index: Optional[int] = 0, + plugin: str = None, + extension: str = None, + format_hint: str = None, + **kwargs +) -> np.ndarray: ... +def imiter( + uri: ImageResource, + *, + plugin: str = None, + extension: str = None, + format_hint: str = None, + **kwargs +) -> Iterator[np.ndarray]: ... +@overload +def imwrite( + uri: Literal[""], + image: Union[ArrayLike, List[ArrayLike]], + *, + plugin: str = None, + extension: str = None, + format_hint: str = None, + **kwargs +) -> bytes: ... +@overload +def imwrite( + uri: ImageResource, + image: Union[ArrayLike, List[ArrayLike]], + *, + plugin: str = None, + extension: str = None, + format_hint: str = None, + **kwargs +) -> None: ... +def improps( + uri, + *, + index: Optional[int] = 0, + plugin: str = None, + extension: str = None, + **kwargs +) -> ImageProperties: ... +def immeta( + uri, + *, + index: Optional[int] = 0, + plugin: str = None, + extension: str = None, + exclude_applied: bool = True, + **kwargs +) -> Dict[str, Any]: ... diff --git a/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/INSTALLER b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/METADATA b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5dbad867d45b39beb24549a6a40c753d3a768c4b --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/METADATA @@ -0,0 +1,134 @@ +Metadata-Version: 2.4 +Name: importlib_metadata +Version: 8.7.0 +Summary: Read metadata from Python packages +Author-email: "Jason R. Coombs" +Project-URL: Source, https://github.com/python/importlib_metadata +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: zipp>=3.20 +Requires-Dist: typing-extensions>=3.6.4; python_version < "3.8" +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: importlib_resources>=1.3; python_version < "3.9" and extra == "test" +Requires-Dist: packaging; extra == "test" +Requires-Dist: pyfakefs; extra == "test" +Requires-Dist: flufl.flake8; extra == "test" +Requires-Dist: pytest-perf>=0.9.2; extra == "test" +Requires-Dist: jaraco.test>=5.4; extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx>=3.5; extra == "doc" +Requires-Dist: jaraco.packaging>=9.3; extra == "doc" +Requires-Dist: rst.linker>=1.9; extra == "doc" +Requires-Dist: furo; extra == "doc" +Requires-Dist: sphinx-lint; extra == "doc" +Requires-Dist: jaraco.tidelift>=1.4; extra == "doc" +Provides-Extra: perf +Requires-Dist: ipython; extra == "perf" +Provides-Extra: check +Requires-Dist: pytest-checkdocs>=2.4; extra == "check" +Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check" +Provides-Extra: cover +Requires-Dist: pytest-cov; extra == "cover" +Provides-Extra: enabler +Requires-Dist: pytest-enabler>=2.2; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy; extra == "type" +Dynamic: license-file + +.. image:: https://img.shields.io/pypi/v/importlib_metadata.svg + :target: https://pypi.org/project/importlib_metadata + +.. image:: https://img.shields.io/pypi/pyversions/importlib_metadata.svg + +.. image:: https://github.com/python/importlib_metadata/actions/workflows/main.yml/badge.svg + :target: https://github.com/python/importlib_metadata/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/importlib-metadata/badge/?version=latest + :target: https://importlib-metadata.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2025-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/importlib-metadata + :target: https://tidelift.com/subscription/pkg/pypi-importlib-metadata?utm_source=pypi-importlib-metadata&utm_medium=readme + +Library to access the metadata for a Python package. + +This package supplies third-party access to the functionality of +`importlib.metadata `_ +including improvements added to subsequent Python versions. + + +Compatibility +============= + +New features are introduced in this third-party library and later merged +into CPython. The following table indicates which versions of this library +were contributed to different versions in the standard library: + +.. list-table:: + :header-rows: 1 + + * - importlib_metadata + - stdlib + * - 7.0 + - 3.13 + * - 6.5 + - 3.12 + * - 4.13 + - 3.11 + * - 4.6 + - 3.10 + * - 1.4 + - 3.8 + + +Usage +===== + +See the `online documentation `_ +for usage details. + +`Finder authors +`_ can +also add support for custom package installers. See the above documentation +for details. + + +Caveats +======= + +This project primarily supports third-party packages installed by PyPA +tools (or other conforming packages). It does not support: + +- Packages in the stdlib. +- Packages installed without metadata. + +Project details +=============== + + * Project home: https://github.com/python/importlib_metadata + * Report bugs at: https://github.com/python/importlib_metadata/issues + * Code hosting: https://github.com/python/importlib_metadata + * Documentation: https://importlib-metadata.readthedocs.io/ + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/RECORD b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..fec0f7fdce5be5601e4154c9069a6f955d8e34b5 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/RECORD @@ -0,0 +1,33 @@ +importlib_metadata-8.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +importlib_metadata-8.7.0.dist-info/METADATA,sha256=QJMudfqWDjfobdzipgUH5gskLahdXueIgy433mjk_Qw,4760 +importlib_metadata-8.7.0.dist-info/RECORD,, +importlib_metadata-8.7.0.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91 +importlib_metadata-8.7.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +importlib_metadata-8.7.0.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19 +importlib_metadata/__init__.py,sha256=R60WJL9VdkZ9SgxtzCH-AU604rJPmNBnntPrUfcNEqc,37062 +importlib_metadata/__pycache__/__init__.cpython-312.pyc,, +importlib_metadata/__pycache__/_adapters.cpython-312.pyc,, +importlib_metadata/__pycache__/_collections.cpython-312.pyc,, +importlib_metadata/__pycache__/_compat.cpython-312.pyc,, +importlib_metadata/__pycache__/_functools.cpython-312.pyc,, +importlib_metadata/__pycache__/_itertools.cpython-312.pyc,, +importlib_metadata/__pycache__/_meta.cpython-312.pyc,, +importlib_metadata/__pycache__/_text.cpython-312.pyc,, +importlib_metadata/__pycache__/_typing.cpython-312.pyc,, +importlib_metadata/__pycache__/diagnose.cpython-312.pyc,, +importlib_metadata/_adapters.py,sha256=9Y3FAlZuoo8pOMVLnKXm5Xx6hKgsdUQOXF5SkiDGqWo,3784 +importlib_metadata/_collections.py,sha256=CxAhzlF3g1rwu_fMiB53JtRQiUFh0RgiMpoOvmK_ocg,760 +importlib_metadata/_compat.py,sha256=VC5ZDLlT-BcshauCShdFJvMNLntJJfZzNK1meGa-enw,1313 +importlib_metadata/_functools.py,sha256=bSbAqC9-2niWM9364FYBx9GWtetnJEfo4mdLv8uMl7c,2895 +importlib_metadata/_itertools.py,sha256=nMvp9SfHAQ_JYwK4L2i64lr3GRXGlYlikGTVzWbys_E,5351 +importlib_metadata/_meta.py,sha256=EtHyiJ5kGzWFDfKyQ2XQp6Vu113CeadKW1Vf6aGc1B4,1765 +importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166 +importlib_metadata/_typing.py,sha256=EQKhhsEgz_Sa-FnePI-faC72rNOOQwopjA1i5pG8FDU,367 +importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_metadata/compat/__pycache__/__init__.cpython-312.pyc,, +importlib_metadata/compat/__pycache__/py311.cpython-312.pyc,, +importlib_metadata/compat/__pycache__/py39.cpython-312.pyc,, +importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608 +importlib_metadata/compat/py39.py,sha256=J3W7PUVRPNYMmcvT12RF8ndBU9e8_T0Ac4U87Bsrq70,1187 +importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379 +importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/WHEEL b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8acb95590701b87bf84eec079cf4e3989f63b098 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/top_level.txt b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbb07547a19c30031d13c45cf01cba61dc434e47 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata-8.7.0.dist-info/top_level.txt @@ -0,0 +1 @@ +importlib_metadata diff --git a/python_embeded/Lib/site-packages/importlib_metadata/__init__.py b/python_embeded/Lib/site-packages/importlib_metadata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cdfc1f629d3357806978209dd2f35e98743e1490 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/__init__.py @@ -0,0 +1,1175 @@ +""" +APIs exposing metadata from third-party Python packages. + +This codebase is shared between importlib.metadata in the stdlib +and importlib_metadata in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +from __future__ import annotations + +import abc +import collections +import email +import functools +import itertools +import operator +import os +import pathlib +import posixpath +import re +import sys +import textwrap +import types +from collections.abc import Iterable, Mapping +from contextlib import suppress +from importlib import import_module +from importlib.abc import MetaPathFinder +from itertools import starmap +from typing import Any + +from . import _meta +from ._collections import FreezableDefaultDict, Pair +from ._compat import ( + NullFinder, + install, +) +from ._functools import method_cache, pass_none +from ._itertools import always_iterable, bucket, unique_everseen +from ._meta import PackageMetadata, SimplePath +from ._typing import md_none +from .compat import py39, py311 + +__all__ = [ + 'Distribution', + 'DistributionFinder', + 'PackageMetadata', + 'PackageNotFoundError', + 'SimplePath', + 'distribution', + 'distributions', + 'entry_points', + 'files', + 'metadata', + 'packages_distributions', + 'requires', + 'version', +] + + +class PackageNotFoundError(ModuleNotFoundError): + """The package was not found.""" + + def __str__(self) -> str: + return f"No package metadata was found for {self.name}" + + @property + def name(self) -> str: # type: ignore[override] # make readonly + (name,) = self.args + return name + + +class Sectioned: + """ + A simple entry point config parser for performance + + >>> for item in Sectioned.read(Sectioned._sample): + ... print(item) + Pair(name='sec1', value='# comments ignored') + Pair(name='sec1', value='a = 1') + Pair(name='sec1', value='b = 2') + Pair(name='sec2', value='a = 2') + + >>> res = Sectioned.section_pairs(Sectioned._sample) + >>> item = next(res) + >>> item.name + 'sec1' + >>> item.value + Pair(name='a', value='1') + >>> item = next(res) + >>> item.value + Pair(name='b', value='2') + >>> item = next(res) + >>> item.name + 'sec2' + >>> item.value + Pair(name='a', value='2') + >>> list(res) + [] + """ + + _sample = textwrap.dedent( + """ + [sec1] + # comments ignored + a = 1 + b = 2 + + [sec2] + a = 2 + """ + ).lstrip() + + @classmethod + def section_pairs(cls, text): + return ( + section._replace(value=Pair.parse(section.value)) + for section in cls.read(text, filter_=cls.valid) + if section.name is not None + ) + + @staticmethod + def read(text, filter_=None): + lines = filter(filter_, map(str.strip, text.splitlines())) + name = None + for value in lines: + section_match = value.startswith('[') and value.endswith(']') + if section_match: + name = value.strip('[]') + continue + yield Pair(name, value) + + @staticmethod + def valid(line: str): + return line and not line.startswith('#') + + +class _EntryPointMatch(types.SimpleNamespace): + module: str + attr: str + extras: str + + +class EntryPoint: + """An entry point as defined by Python packaging conventions. + + See `the packaging docs on entry points + `_ + for more information. + + >>> ep = EntryPoint( + ... name=None, group=None, value='package.module:attr [extra1, extra2]') + >>> ep.module + 'package.module' + >>> ep.attr + 'attr' + >>> ep.extras + ['extra1', 'extra2'] + + If the value package or module are not valid identifiers, a + ValueError is raised on access. + + >>> EntryPoint(name=None, group=None, value='invalid-name').module + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + >>> EntryPoint(name=None, group=None, value='invalid-name').attr + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + >>> EntryPoint(name=None, group=None, value='invalid-name').extras + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + + The same thing happens on construction. + + >>> EntryPoint(name=None, group=None, value='invalid-name') + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + + """ + + pattern = re.compile( + r'(?P[\w.]+)\s*' + r'(:\s*(?P[\w.]+)\s*)?' + r'((?P\[.*\])\s*)?$' + ) + """ + A regular expression describing the syntax for an entry point, + which might look like: + + - module + - package.module + - package.module:attribute + - package.module:object.attribute + - package.module:attr [extra1, extra2] + + Other combinations are possible as well. + + The expression is lenient about whitespace around the ':', + following the attr, and following any extras. + """ + + name: str + value: str + group: str + + dist: Distribution | None = None + + def __init__(self, name: str, value: str, group: str) -> None: + vars(self).update(name=name, value=value, group=group) + self.module + + def load(self) -> Any: + """Load the entry point from its definition. If only a module + is indicated by the value, return that module. Otherwise, + return the named object. + """ + module = import_module(self.module) + attrs = filter(None, (self.attr or '').split('.')) + return functools.reduce(getattr, attrs, module) + + @property + def module(self) -> str: + return self._match.module + + @property + def attr(self) -> str: + return self._match.attr + + @property + def extras(self) -> list[str]: + return re.findall(r'\w+', self._match.extras or '') + + @functools.cached_property + def _match(self) -> _EntryPointMatch: + match = self.pattern.match(self.value) + if not match: + raise ValueError( + 'Invalid object reference. ' + 'See https://packaging.python.org' + '/en/latest/specifications/entry-points/#data-model', + self.value, + ) + return _EntryPointMatch(**match.groupdict()) + + def _for(self, dist): + vars(self).update(dist=dist) + return self + + def matches(self, **params): + """ + EntryPoint matches the given parameters. + + >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]') + >>> ep.matches(group='foo') + True + >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]') + True + >>> ep.matches(group='foo', name='other') + False + >>> ep.matches() + True + >>> ep.matches(extras=['extra1', 'extra2']) + True + >>> ep.matches(module='bing') + True + >>> ep.matches(attr='bong') + True + """ + self._disallow_dist(params) + attrs = (getattr(self, param) for param in params) + return all(map(operator.eq, params.values(), attrs)) + + @staticmethod + def _disallow_dist(params): + """ + Querying by dist is not allowed (dist objects are not comparable). + >>> EntryPoint(name='fan', value='fav', group='fag').matches(dist='foo') + Traceback (most recent call last): + ... + ValueError: "dist" is not suitable for matching... + """ + if "dist" in params: + raise ValueError( + '"dist" is not suitable for matching. ' + "Instead, use Distribution.entry_points.select() on a " + "located distribution." + ) + + def _key(self): + return self.name, self.value, self.group + + def __lt__(self, other): + return self._key() < other._key() + + def __eq__(self, other): + return self._key() == other._key() + + def __setattr__(self, name, value): + raise AttributeError("EntryPoint objects are immutable.") + + def __repr__(self): + return ( + f'EntryPoint(name={self.name!r}, value={self.value!r}, ' + f'group={self.group!r})' + ) + + def __hash__(self) -> int: + return hash(self._key()) + + +class EntryPoints(tuple): + """ + An immutable collection of selectable EntryPoint objects. + """ + + __slots__ = () + + def __getitem__(self, name: str) -> EntryPoint: # type: ignore[override] # Work with str instead of int + """ + Get the EntryPoint in self matching name. + """ + try: + return next(iter(self.select(name=name))) + except StopIteration: + raise KeyError(name) + + def __repr__(self): + """ + Repr with classname and tuple constructor to + signal that we deviate from regular tuple behavior. + """ + return '%s(%r)' % (self.__class__.__name__, tuple(self)) + + def select(self, **params) -> EntryPoints: + """ + Select entry points from self that match the + given parameters (typically group and/or name). + """ + return EntryPoints(ep for ep in self if py39.ep_matches(ep, **params)) + + @property + def names(self) -> set[str]: + """ + Return the set of all names of all entry points. + """ + return {ep.name for ep in self} + + @property + def groups(self) -> set[str]: + """ + Return the set of all groups of all entry points. + """ + return {ep.group for ep in self} + + @classmethod + def _from_text_for(cls, text, dist): + return cls(ep._for(dist) for ep in cls._from_text(text)) + + @staticmethod + def _from_text(text): + return ( + EntryPoint(name=item.value.name, value=item.value.value, group=item.name) + for item in Sectioned.section_pairs(text or '') + ) + + +class PackagePath(pathlib.PurePosixPath): + """A reference to a path in a package""" + + hash: FileHash | None + size: int + dist: Distribution + + def read_text(self, encoding: str = 'utf-8') -> str: + return self.locate().read_text(encoding=encoding) + + def read_binary(self) -> bytes: + return self.locate().read_bytes() + + def locate(self) -> SimplePath: + """Return a path-like object for this path""" + return self.dist.locate_file(self) + + +class FileHash: + def __init__(self, spec: str) -> None: + self.mode, _, self.value = spec.partition('=') + + def __repr__(self) -> str: + return f'' + + +class Distribution(metaclass=abc.ABCMeta): + """ + An abstract Python distribution package. + + Custom providers may derive from this class and define + the abstract methods to provide a concrete implementation + for their environment. Some providers may opt to override + the default implementation of some properties to bypass + the file-reading mechanism. + """ + + @abc.abstractmethod + def read_text(self, filename) -> str | None: + """Attempt to load metadata file given by the name. + + Python distribution metadata is organized by blobs of text + typically represented as "files" in the metadata directory + (e.g. package-1.0.dist-info). These files include things + like: + + - METADATA: The distribution metadata including fields + like Name and Version and Description. + - entry_points.txt: A series of entry points as defined in + `the entry points spec `_. + - RECORD: A record of files according to + `this recording spec `_. + + A package may provide any set of files, including those + not listed here or none at all. + + :param filename: The name of the file in the distribution info. + :return: The text if found, otherwise None. + """ + + @abc.abstractmethod + def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: + """ + Given a path to a file in this distribution, return a SimplePath + to it. + + This method is used by callers of ``Distribution.files()`` to + locate files within the distribution. If it's possible for a + Distribution to represent files in the distribution as + ``SimplePath`` objects, it should implement this method + to resolve such objects. + + Some Distribution providers may elect not to resolve SimplePath + objects within the distribution by raising a + NotImplementedError, but consumers of such a Distribution would + be unable to invoke ``Distribution.files()``. + """ + + @classmethod + def from_name(cls, name: str) -> Distribution: + """Return the Distribution for the given package name. + + :param name: The name of the distribution package to search for. + :return: The Distribution instance (or subclass thereof) for the named + package, if found. + :raises PackageNotFoundError: When the named package's distribution + metadata cannot be found. + :raises ValueError: When an invalid value is supplied for name. + """ + if not name: + raise ValueError("A distribution name is required.") + try: + return next(iter(cls._prefer_valid(cls.discover(name=name)))) + except StopIteration: + raise PackageNotFoundError(name) + + @classmethod + def discover( + cls, *, context: DistributionFinder.Context | None = None, **kwargs + ) -> Iterable[Distribution]: + """Return an iterable of Distribution objects for all packages. + + Pass a ``context`` or pass keyword arguments for constructing + a context. + + :context: A ``DistributionFinder.Context`` object. + :return: Iterable of Distribution objects for packages matching + the context. + """ + if context and kwargs: + raise ValueError("cannot accept context and kwargs") + context = context or DistributionFinder.Context(**kwargs) + return itertools.chain.from_iterable( + resolver(context) for resolver in cls._discover_resolvers() + ) + + @staticmethod + def _prefer_valid(dists: Iterable[Distribution]) -> Iterable[Distribution]: + """ + Prefer (move to the front) distributions that have metadata. + + Ref python/importlib_resources#489. + """ + buckets = bucket(dists, lambda dist: bool(dist.metadata)) + return itertools.chain(buckets[True], buckets[False]) + + @staticmethod + def at(path: str | os.PathLike[str]) -> Distribution: + """Return a Distribution for the indicated metadata path. + + :param path: a string or path-like object + :return: a concrete Distribution instance for the path + """ + return PathDistribution(pathlib.Path(path)) + + @staticmethod + def _discover_resolvers(): + """Search the meta_path for resolvers (MetadataPathFinders).""" + declared = ( + getattr(finder, 'find_distributions', None) for finder in sys.meta_path + ) + return filter(None, declared) + + @property + def metadata(self) -> _meta.PackageMetadata | None: + """Return the parsed metadata for this Distribution. + + The returned object will have keys that name the various bits of + metadata per the + `Core metadata specifications `_. + + Custom providers may provide the METADATA file or override this + property. + """ + + text = ( + self.read_text('METADATA') + or self.read_text('PKG-INFO') + # This last clause is here to support old egg-info files. Its + # effect is to just end up using the PathDistribution's self._path + # (which points to the egg-info file) attribute unchanged. + or self.read_text('') + ) + return self._assemble_message(text) + + @staticmethod + @pass_none + def _assemble_message(text: str) -> _meta.PackageMetadata: + # deferred for performance (python/cpython#109829) + from . import _adapters + + return _adapters.Message(email.message_from_string(text)) + + @property + def name(self) -> str: + """Return the 'Name' metadata for the distribution package.""" + return md_none(self.metadata)['Name'] + + @property + def _normalized_name(self): + """Return a normalized version of the name.""" + return Prepared.normalize(self.name) + + @property + def version(self) -> str: + """Return the 'Version' metadata for the distribution package.""" + return md_none(self.metadata)['Version'] + + @property + def entry_points(self) -> EntryPoints: + """ + Return EntryPoints for this distribution. + + Custom providers may provide the ``entry_points.txt`` file + or override this property. + """ + return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) + + @property + def files(self) -> list[PackagePath] | None: + """Files in this distribution. + + :return: List of PackagePath for this distribution or None + + Result is `None` if the metadata file that enumerates files + (i.e. RECORD for dist-info, or installed-files.txt or + SOURCES.txt for egg-info) is missing. + Result may be empty if the metadata exists but is empty. + + Custom providers are recommended to provide a "RECORD" file (in + ``read_text``) or override this property to allow for callers to be + able to resolve filenames provided by the package. + """ + + def make_file(name, hash=None, size_str=None): + result = PackagePath(name) + result.hash = FileHash(hash) if hash else None + result.size = int(size_str) if size_str else None + result.dist = self + return result + + @pass_none + def make_files(lines): + # Delay csv import, since Distribution.files is not as widely used + # as other parts of importlib.metadata + import csv + + return starmap(make_file, csv.reader(lines)) + + @pass_none + def skip_missing_files(package_paths): + return list(filter(lambda path: path.locate().exists(), package_paths)) + + return skip_missing_files( + make_files( + self._read_files_distinfo() + or self._read_files_egginfo_installed() + or self._read_files_egginfo_sources() + ) + ) + + def _read_files_distinfo(self): + """ + Read the lines of RECORD. + """ + text = self.read_text('RECORD') + return text and text.splitlines() + + def _read_files_egginfo_installed(self): + """ + Read installed-files.txt and return lines in a similar + CSV-parsable format as RECORD: each file must be placed + relative to the site-packages directory and must also be + quoted (since file names can contain literal commas). + + This file is written when the package is installed by pip, + but it might not be written for other installation methods. + Assume the file is accurate if it exists. + """ + text = self.read_text('installed-files.txt') + # Prepend the .egg-info/ subdir to the lines in this file. + # But this subdir is only available from PathDistribution's + # self._path. + subdir = getattr(self, '_path', None) + if not text or not subdir: + return + + paths = ( + py311.relative_fix((subdir / name).resolve()) + .relative_to(self.locate_file('').resolve(), walk_up=True) + .as_posix() + for name in text.splitlines() + ) + return map('"{}"'.format, paths) + + def _read_files_egginfo_sources(self): + """ + Read SOURCES.txt and return lines in a similar CSV-parsable + format as RECORD: each file name must be quoted (since it + might contain literal commas). + + Note that SOURCES.txt is not a reliable source for what + files are installed by a package. This file is generated + for a source archive, and the files that are present + there (e.g. setup.py) may not correctly reflect the files + that are present after the package has been installed. + """ + text = self.read_text('SOURCES.txt') + return text and map('"{}"'.format, text.splitlines()) + + @property + def requires(self) -> list[str] | None: + """Generated requirements specified for this Distribution""" + reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs() + return reqs and list(reqs) + + def _read_dist_info_reqs(self): + return self.metadata.get_all('Requires-Dist') + + def _read_egg_info_reqs(self): + source = self.read_text('requires.txt') + return pass_none(self._deps_from_requires_text)(source) + + @classmethod + def _deps_from_requires_text(cls, source): + return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source)) + + @staticmethod + def _convert_egg_info_reqs_to_simple_reqs(sections): + """ + Historically, setuptools would solicit and store 'extra' + requirements, including those with environment markers, + in separate sections. More modern tools expect each + dependency to be defined separately, with any relevant + extras and environment markers attached directly to that + requirement. This method converts the former to the + latter. See _test_deps_from_requires_text for an example. + """ + + def make_condition(name): + return name and f'extra == "{name}"' + + def quoted_marker(section): + section = section or '' + extra, sep, markers = section.partition(':') + if extra and markers: + markers = f'({markers})' + conditions = list(filter(None, [markers, make_condition(extra)])) + return '; ' + ' and '.join(conditions) if conditions else '' + + def url_req_space(req): + """ + PEP 508 requires a space between the url_spec and the quoted_marker. + Ref python/importlib_metadata#357. + """ + # '@' is uniquely indicative of a url_req. + return ' ' * ('@' in req) + + for section in sections: + space = url_req_space(section.value) + yield section.value + space + quoted_marker(section.name) + + @property + def origin(self): + return self._load_json('direct_url.json') + + def _load_json(self, filename): + # Deferred for performance (python/importlib_metadata#503) + import json + + return pass_none(json.loads)( + self.read_text(filename), + object_hook=lambda data: types.SimpleNamespace(**data), + ) + + +class DistributionFinder(MetaPathFinder): + """ + A MetaPathFinder capable of discovering installed distributions. + + Custom providers should implement this interface in order to + supply metadata. + """ + + class Context: + """ + Keyword arguments presented by the caller to + ``distributions()`` or ``Distribution.discover()`` + to narrow the scope of a search for distributions + in all DistributionFinders. + + Each DistributionFinder may expect any parameters + and should attempt to honor the canonical + parameters defined below when appropriate. + + This mechanism gives a custom provider a means to + solicit additional details from the caller beyond + "name" and "path" when searching distributions. + For example, imagine a provider that exposes suites + of packages in either a "public" or "private" ``realm``. + A caller may wish to query only for distributions in + a particular realm and could call + ``distributions(realm="private")`` to signal to the + custom provider to only include distributions from that + realm. + """ + + name = None + """ + Specific name for which a distribution finder should match. + A name of ``None`` matches all distributions. + """ + + def __init__(self, **kwargs): + vars(self).update(kwargs) + + @property + def path(self) -> list[str]: + """ + The sequence of directory path that a distribution finder + should search. + + Typically refers to Python installed package paths such as + "site-packages" directories and defaults to ``sys.path``. + """ + return vars(self).get('path', sys.path) + + @abc.abstractmethod + def find_distributions(self, context=Context()) -> Iterable[Distribution]: + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching the ``context``, + a DistributionFinder.Context instance. + """ + + +class FastPath: + """ + Micro-optimized class for searching a root for children. + + Root is a path on the file system that may contain metadata + directories either as natural directories or within a zip file. + + >>> FastPath('').children() + ['...'] + + FastPath objects are cached and recycled for any given root. + + >>> FastPath('foobar') is FastPath('foobar') + True + """ + + @functools.lru_cache() # type: ignore[misc] + def __new__(cls, root): + return super().__new__(cls) + + def __init__(self, root): + self.root = root + + def joinpath(self, child): + return pathlib.Path(self.root, child) + + def children(self): + with suppress(Exception): + return os.listdir(self.root or '.') + with suppress(Exception): + return self.zip_children() + return [] + + def zip_children(self): + # deferred for performance (python/importlib_metadata#502) + from zipp.compat.overlay import zipfile + + zip_path = zipfile.Path(self.root) + names = zip_path.root.namelist() + self.joinpath = zip_path.joinpath + + return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) + + def search(self, name): + return self.lookup(self.mtime).search(name) + + @property + def mtime(self): + with suppress(OSError): + return os.stat(self.root).st_mtime + self.lookup.cache_clear() + + @method_cache + def lookup(self, mtime): + return Lookup(self) + + +class Lookup: + """ + A micro-optimized class for searching a (fast) path for metadata. + """ + + def __init__(self, path: FastPath): + """ + Calculate all of the children representing metadata. + + From the children in the path, calculate early all of the + children that appear to represent metadata (infos) or legacy + metadata (eggs). + """ + + base = os.path.basename(path.root).lower() + base_is_egg = base.endswith(".egg") + self.infos = FreezableDefaultDict(list) + self.eggs = FreezableDefaultDict(list) + + for child in path.children(): + low = child.lower() + if low.endswith((".dist-info", ".egg-info")): + # rpartition is faster than splitext and suitable for this purpose. + name = low.rpartition(".")[0].partition("-")[0] + normalized = Prepared.normalize(name) + self.infos[normalized].append(path.joinpath(child)) + elif base_is_egg and low == "egg-info": + name = base.rpartition(".")[0].partition("-")[0] + legacy_normalized = Prepared.legacy_normalize(name) + self.eggs[legacy_normalized].append(path.joinpath(child)) + + self.infos.freeze() + self.eggs.freeze() + + def search(self, prepared: Prepared): + """ + Yield all infos and eggs matching the Prepared query. + """ + infos = ( + self.infos[prepared.normalized] + if prepared + else itertools.chain.from_iterable(self.infos.values()) + ) + eggs = ( + self.eggs[prepared.legacy_normalized] + if prepared + else itertools.chain.from_iterable(self.eggs.values()) + ) + return itertools.chain(infos, eggs) + + +class Prepared: + """ + A prepared search query for metadata on a possibly-named package. + + Pre-calculates the normalization to prevent repeated operations. + + >>> none = Prepared(None) + >>> none.normalized + >>> none.legacy_normalized + >>> bool(none) + False + >>> sample = Prepared('Sample__Pkg-name.foo') + >>> sample.normalized + 'sample_pkg_name_foo' + >>> sample.legacy_normalized + 'sample__pkg_name.foo' + >>> bool(sample) + True + """ + + normalized = None + legacy_normalized = None + + def __init__(self, name: str | None): + self.name = name + if name is None: + return + self.normalized = self.normalize(name) + self.legacy_normalized = self.legacy_normalize(name) + + @staticmethod + def normalize(name): + """ + PEP 503 normalization plus dashes as underscores. + """ + return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') + + @staticmethod + def legacy_normalize(name): + """ + Normalize the package name as found in the convention in + older packaging tools versions and specs. + """ + return name.lower().replace('-', '_') + + def __bool__(self): + return bool(self.name) + + +@install +class MetadataPathFinder(NullFinder, DistributionFinder): + """A degenerate finder for distribution packages on the file system. + + This finder supplies only a find_distributions() method for versions + of Python that do not have a PathFinder find_distributions(). + """ + + @classmethod + def find_distributions( + cls, context=DistributionFinder.Context() + ) -> Iterable[PathDistribution]: + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching ``context.name`` + (or all names if ``None`` indicated) along the paths in the list + of directories ``context.path``. + """ + found = cls._search_paths(context.name, context.path) + return map(PathDistribution, found) + + @classmethod + def _search_paths(cls, name, paths): + """Find metadata directories in paths heuristically.""" + prepared = Prepared(name) + return itertools.chain.from_iterable( + path.search(prepared) for path in map(FastPath, paths) + ) + + @classmethod + def invalidate_caches(cls) -> None: + FastPath.__new__.cache_clear() + + +class PathDistribution(Distribution): + def __init__(self, path: SimplePath) -> None: + """Construct a distribution. + + :param path: SimplePath indicating the metadata directory. + """ + self._path = path + + def read_text(self, filename: str | os.PathLike[str]) -> str | None: + with suppress( + FileNotFoundError, + IsADirectoryError, + KeyError, + NotADirectoryError, + PermissionError, + ): + return self._path.joinpath(filename).read_text(encoding='utf-8') + + return None + + read_text.__doc__ = Distribution.read_text.__doc__ + + def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: + return self._path.parent / path + + @property + def _normalized_name(self): + """ + Performance optimization: where possible, resolve the + normalized name from the file system path. + """ + stem = os.path.basename(str(self._path)) + return ( + pass_none(Prepared.normalize)(self._name_from_stem(stem)) + or super()._normalized_name + ) + + @staticmethod + def _name_from_stem(stem): + """ + >>> PathDistribution._name_from_stem('foo-3.0.egg-info') + 'foo' + >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info') + 'CherryPy' + >>> PathDistribution._name_from_stem('face.egg-info') + 'face' + >>> PathDistribution._name_from_stem('foo.bar') + """ + filename, ext = os.path.splitext(stem) + if ext not in ('.dist-info', '.egg-info'): + return + name, sep, rest = filename.partition('-') + return name + + +def distribution(distribution_name: str) -> Distribution: + """Get the ``Distribution`` instance for the named package. + + :param distribution_name: The name of the distribution package as a string. + :return: A ``Distribution`` instance (or subclass thereof). + """ + return Distribution.from_name(distribution_name) + + +def distributions(**kwargs) -> Iterable[Distribution]: + """Get all ``Distribution`` instances in the current environment. + + :return: An iterable of ``Distribution`` instances. + """ + return Distribution.discover(**kwargs) + + +def metadata(distribution_name: str) -> _meta.PackageMetadata | None: + """Get the metadata for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: A PackageMetadata containing the parsed metadata. + """ + return Distribution.from_name(distribution_name).metadata + + +def version(distribution_name: str) -> str: + """Get the version string for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: The version string for the package as defined in the package's + "Version" metadata key. + """ + return distribution(distribution_name).version + + +_unique = functools.partial( + unique_everseen, + key=py39.normalized_name, +) +""" +Wrapper for ``distributions`` to return unique distributions by name. +""" + + +def entry_points(**params) -> EntryPoints: + """Return EntryPoint objects for all installed packages. + + Pass selection parameters (group or name) to filter the + result to entry points matching those properties (see + EntryPoints.select()). + + :return: EntryPoints for all installed packages. + """ + eps = itertools.chain.from_iterable( + dist.entry_points for dist in _unique(distributions()) + ) + return EntryPoints(eps).select(**params) + + +def files(distribution_name: str) -> list[PackagePath] | None: + """Return a list of files for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: List of files composing the distribution. + """ + return distribution(distribution_name).files + + +def requires(distribution_name: str) -> list[str] | None: + """ + Return a list of requirements for the named package. + + :return: An iterable of requirements, suitable for + packaging.requirement.Requirement. + """ + return distribution(distribution_name).requires + + +def packages_distributions() -> Mapping[str, list[str]]: + """ + Return a mapping of top-level packages to their + distributions. + + >>> import collections.abc + >>> pkgs = packages_distributions() + >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) + True + """ + pkg_to_dist = collections.defaultdict(list) + for dist in distributions(): + for pkg in _top_level_declared(dist) or _top_level_inferred(dist): + pkg_to_dist[pkg].append(md_none(dist.metadata)['Name']) + return dict(pkg_to_dist) + + +def _top_level_declared(dist): + return (dist.read_text('top_level.txt') or '').split() + + +def _topmost(name: PackagePath) -> str | None: + """ + Return the top-most parent as long as there is a parent. + """ + top, *rest = name.parts + return top if rest else None + + +def _get_toplevel_name(name: PackagePath) -> str: + """ + Infer a possibly importable module name from a name presumed on + sys.path. + + >>> _get_toplevel_name(PackagePath('foo.py')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo.pyc')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo/__init__.py')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo.pth')) + 'foo.pth' + >>> _get_toplevel_name(PackagePath('foo.dist-info')) + 'foo.dist-info' + """ + # Defer import of inspect for performance (python/cpython#118761) + import inspect + + return _topmost(name) or inspect.getmodulename(name) or str(name) + + +def _top_level_inferred(dist): + opt_names = set(map(_get_toplevel_name, always_iterable(dist.files))) + + def importable_name(name): + return '.' not in name + + return filter(importable_name, opt_names) diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_adapters.py b/python_embeded/Lib/site-packages/importlib_metadata/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b30dd92cde69ab7c4a4c6485c36d4dc38a551a --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_adapters.py @@ -0,0 +1,135 @@ +import email.message +import email.policy +import re +import textwrap + +from ._text import FoldedCase + + +class RawPolicy(email.policy.EmailPolicy): + def fold(self, name, value): + folded = self.linesep.join( + textwrap.indent(value, prefix=' ' * 8, predicate=lambda line: True) + .lstrip() + .splitlines() + ) + return f'{name}: {folded}{self.linesep}' + + +class Message(email.message.Message): + r""" + Specialized Message subclass to handle metadata naturally. + + Reads values that may have newlines in them and converts the + payload to the Description. + + >>> msg_text = textwrap.dedent(''' + ... Name: Foo + ... Version: 3.0 + ... License: blah + ... de-blah + ... + ... First line of description. + ... Second line of description. + ... + ... Fourth line! + ... ''').lstrip().replace('', '') + >>> msg = Message(email.message_from_string(msg_text)) + >>> msg['Description'] + 'First line of description.\nSecond line of description.\n\nFourth line!\n' + + Message should render even if values contain newlines. + + >>> print(msg) + Name: Foo + Version: 3.0 + License: blah + de-blah + Description: First line of description. + Second line of description. + + Fourth line! + + + """ + + multiple_use_keys = set( + map( + FoldedCase, + [ + 'Classifier', + 'Obsoletes-Dist', + 'Platform', + 'Project-URL', + 'Provides-Dist', + 'Provides-Extra', + 'Requires-Dist', + 'Requires-External', + 'Supported-Platform', + 'Dynamic', + ], + ) + ) + """ + Keys that may be indicated multiple times per PEP 566. + """ + + def __new__(cls, orig: email.message.Message): + res = super().__new__(cls) + vars(res).update(vars(orig)) + return res + + def __init__(self, *args, **kwargs): + self._headers = self._repair_headers() + + # suppress spurious error from mypy + def __iter__(self): + return super().__iter__() + + def __getitem__(self, item): + """ + Override parent behavior to typical dict behavior. + + ``email.message.Message`` will emit None values for missing + keys. Typical mappings, including this ``Message``, will raise + a key error for missing keys. + + Ref python/importlib_metadata#371. + """ + res = super().__getitem__(item) + if res is None: + raise KeyError(item) + return res + + def _repair_headers(self): + def redent(value): + "Correct for RFC822 indentation" + indent = ' ' * 8 + if not value or '\n' + indent not in value: + return value + return textwrap.dedent(indent + value) + + headers = [(key, redent(value)) for key, value in vars(self)['_headers']] + if self._payload: + headers.append(('Description', self.get_payload())) + self.set_payload('') + return headers + + def as_string(self): + return super().as_string(policy=RawPolicy()) + + @property + def json(self): + """ + Convert PackageMetadata to a JSON-compatible format + per PEP 0566. + """ + + def transform(key): + value = self.get_all(key) if key in self.multiple_use_keys else self[key] + if key == 'Keywords': + value = re.split(r'\s+', value) + tk = key.lower().replace('-', '_') + return tk, value + + return dict(map(transform, map(FoldedCase, self))) diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_collections.py b/python_embeded/Lib/site-packages/importlib_metadata/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5045d36be57251000393b32baba7baa9cd8c4f --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_collections.py @@ -0,0 +1,34 @@ +import collections +import typing + + +# from jaraco.collections 3.3 +class FreezableDefaultDict(collections.defaultdict): + """ + Often it is desirable to prevent the mutation of + a default dict after its initial construction, such + as to prevent mutation during iteration. + + >>> dd = FreezableDefaultDict(list) + >>> dd[0].append('1') + >>> dd.freeze() + >>> dd[1] + [] + >>> len(dd) + 1 + """ + + def __missing__(self, key): + return getattr(self, '_frozen', super().__missing__)(key) + + def freeze(self): + self._frozen = lambda key: self.default_factory() + + +class Pair(typing.NamedTuple): + name: str + value: str + + @classmethod + def parse(cls, text): + return cls(*map(str.strip, text.split("=", 1))) diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_compat.py b/python_embeded/Lib/site-packages/importlib_metadata/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..01356d69b97c95a6d41818e5c2c50a299146bef4 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_compat.py @@ -0,0 +1,56 @@ +import platform +import sys + +__all__ = ['install', 'NullFinder'] + + +def install(cls): + """ + Class decorator for installation on sys.meta_path. + + Adds the backport DistributionFinder to sys.meta_path and + attempts to disable the finder functionality of the stdlib + DistributionFinder. + """ + sys.meta_path.append(cls()) + disable_stdlib_finder() + return cls + + +def disable_stdlib_finder(): + """ + Give the backport primacy for discovering path-based distributions + by monkey-patching the stdlib O_O. + + See #91 for more background for rationale on this sketchy + behavior. + """ + + def matches(finder): + return getattr( + finder, '__module__', None + ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions') + + for finder in filter(matches, sys.meta_path): # pragma: nocover + del finder.find_distributions + + +class NullFinder: + """ + A "Finder" (aka "MetaPathFinder") that never finds any modules, + but may find distributions. + """ + + @staticmethod + def find_spec(*args, **kwargs): + return None + + +def pypy_partial(val): + """ + Adjust for variable stacklevel on partial under PyPy. + + Workaround for #327. + """ + is_pypy = platform.python_implementation() == 'PyPy' + return val + is_pypy diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_functools.py b/python_embeded/Lib/site-packages/importlib_metadata/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..5dda6a2199ad0be79351899a583b98c48eda4938 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_functools.py @@ -0,0 +1,104 @@ +import functools +import types + + +# from jaraco.functools 3.3 +def method_cache(method, cache_wrapper=None): + """ + Wrap lru_cache to support storing the cache data in the object instances. + + Abstracts the common paradigm where the method explicitly saves an + underscore-prefixed protected property on first call and returns that + subsequently. + + >>> class MyClass: + ... calls = 0 + ... + ... @method_cache + ... def method(self, value): + ... self.calls += 1 + ... return value + + >>> a = MyClass() + >>> a.method(3) + 3 + >>> for x in range(75): + ... res = a.method(x) + >>> a.calls + 75 + + Note that the apparent behavior will be exactly like that of lru_cache + except that the cache is stored on each instance, so values in one + instance will not flush values from another, and when an instance is + deleted, so are the cached values for that instance. + + >>> b = MyClass() + >>> for x in range(35): + ... res = b.method(x) + >>> b.calls + 35 + >>> a.method(0) + 0 + >>> a.calls + 75 + + Note that if method had been decorated with ``functools.lru_cache()``, + a.calls would have been 76 (due to the cached value of 0 having been + flushed by the 'b' instance). + + Clear the cache with ``.cache_clear()`` + + >>> a.method.cache_clear() + + Same for a method that hasn't yet been called. + + >>> c = MyClass() + >>> c.method.cache_clear() + + Another cache wrapper may be supplied: + + >>> cache = functools.lru_cache(maxsize=2) + >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) + >>> a = MyClass() + >>> a.method2() + 3 + + Caution - do not subsequently wrap the method with another decorator, such + as ``@property``, which changes the semantics of the function. + + See also + http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ + for another implementation and additional justification. + """ + cache_wrapper = cache_wrapper or functools.lru_cache() + + def wrapper(self, *args, **kwargs): + # it's the first call, replace the method with a cached, bound method + bound_method = types.MethodType(method, self) + cached_method = cache_wrapper(bound_method) + setattr(self, method.__name__, cached_method) + return cached_method(*args, **kwargs) + + # Support cache clear even before cache has been created. + wrapper.cache_clear = lambda: None + + return wrapper + + +# From jaraco.functools 3.3 +def pass_none(func): + """ + Wrap func so it's not called if its first param is None + + >>> print_text = pass_none(print) + >>> print_text('text') + text + >>> print_text(None) + """ + + @functools.wraps(func) + def wrapper(param, *args, **kwargs): + if param is not None: + return func(param, *args, **kwargs) + + return wrapper diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_itertools.py b/python_embeded/Lib/site-packages/importlib_metadata/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..79d37198ce7aff317873f6e4e84cd904a46a69de --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_itertools.py @@ -0,0 +1,171 @@ +from collections import defaultdict, deque +from itertools import filterfalse + + +def unique_everseen(iterable, key=None): + "List unique elements, preserving order. Remember all elements ever seen." + # unique_everseen('AAAABBBCCDAABBB') --> A B C D + # unique_everseen('ABBCcAD', str.lower) --> A B C D + seen = set() + seen_add = seen.add + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen_add(element) + yield element + else: + for element in iterable: + k = key(element) + if k not in seen: + seen_add(k) + yield element + + +# copied from more_itertools 8.8 +def always_iterable(obj, base_type=(str, bytes)): + """If *obj* is iterable, return an iterator over its items:: + + >>> obj = (1, 2, 3) + >>> list(always_iterable(obj)) + [1, 2, 3] + + If *obj* is not iterable, return a one-item iterable containing *obj*:: + + >>> obj = 1 + >>> list(always_iterable(obj)) + [1] + + If *obj* is ``None``, return an empty iterable: + + >>> obj = None + >>> list(always_iterable(None)) + [] + + By default, binary and text strings are not considered iterable:: + + >>> obj = 'foo' + >>> list(always_iterable(obj)) + ['foo'] + + If *base_type* is set, objects for which ``isinstance(obj, base_type)`` + returns ``True`` won't be considered iterable. + + >>> obj = {'a': 1} + >>> list(always_iterable(obj)) # Iterate over the dict's keys + ['a'] + >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit + [{'a': 1}] + + Set *base_type* to ``None`` to avoid any special handling and treat objects + Python considers iterable as iterable: + + >>> obj = 'foo' + >>> list(always_iterable(obj, base_type=None)) + ['f', 'o', 'o'] + """ + if obj is None: + return iter(()) + + if (base_type is not None) and isinstance(obj, base_type): + return iter((obj,)) + + try: + return iter(obj) + except TypeError: + return iter((obj,)) + + +# Copied from more_itertools 10.3 +class bucket: + """Wrap *iterable* and return an object that buckets the iterable into + child iterables based on a *key* function. + + >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] + >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character + >>> sorted(list(s)) # Get the keys + ['a', 'b', 'c'] + >>> a_iterable = s['a'] + >>> next(a_iterable) + 'a1' + >>> next(a_iterable) + 'a2' + >>> list(s['b']) + ['b1', 'b2', 'b3'] + + The original iterable will be advanced and its items will be cached until + they are used by the child iterables. This may require significant storage. + + By default, attempting to select a bucket to which no items belong will + exhaust the iterable and cache all values. + If you specify a *validator* function, selected buckets will instead be + checked against it. + + >>> from itertools import count + >>> it = count(1, 2) # Infinite sequence of odd numbers + >>> key = lambda x: x % 10 # Bucket by last digit + >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only + >>> s = bucket(it, key=key, validator=validator) + >>> 2 in s + False + >>> list(s[2]) + [] + + """ + + def __init__(self, iterable, key, validator=None): + self._it = iter(iterable) + self._key = key + self._cache = defaultdict(deque) + self._validator = validator or (lambda x: True) + + def __contains__(self, value): + if not self._validator(value): + return False + + try: + item = next(self[value]) + except StopIteration: + return False + else: + self._cache[value].appendleft(item) + + return True + + def _get_values(self, value): + """ + Helper to yield items from the parent iterator that match *value*. + Items that don't match are stored in the local cache as they + are encountered. + """ + while True: + # If we've cached some items that match the target value, emit + # the first one and evict it from the cache. + if self._cache[value]: + yield self._cache[value].popleft() + # Otherwise we need to advance the parent iterator to search for + # a matching item, caching the rest. + else: + while True: + try: + item = next(self._it) + except StopIteration: + return + item_value = self._key(item) + if item_value == value: + yield item + break + elif self._validator(item_value): + self._cache[item_value].append(item) + + def __iter__(self): + for item in self._it: + item_value = self._key(item) + if self._validator(item_value): + self._cache[item_value].append(item) + + yield from self._cache.keys() + + def __getitem__(self, value): + if not self._validator(value): + return iter(()) + + return self._get_values(value) diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_meta.py b/python_embeded/Lib/site-packages/importlib_metadata/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..0c20eff3da75223a5ca76a1743b7c5b8fa1dc1f6 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_meta.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import os +from collections.abc import Iterator +from typing import ( + Any, + Protocol, + TypeVar, + overload, +) + +_T = TypeVar("_T") + + +class PackageMetadata(Protocol): + def __len__(self) -> int: ... # pragma: no cover + + def __contains__(self, item: str) -> bool: ... # pragma: no cover + + def __getitem__(self, key: str) -> str: ... # pragma: no cover + + def __iter__(self) -> Iterator[str]: ... # pragma: no cover + + @overload + def get( + self, name: str, failobj: None = None + ) -> str | None: ... # pragma: no cover + + @overload + def get(self, name: str, failobj: _T) -> str | _T: ... # pragma: no cover + + # overload per python/importlib_metadata#435 + @overload + def get_all( + self, name: str, failobj: None = None + ) -> list[Any] | None: ... # pragma: no cover + + @overload + def get_all(self, name: str, failobj: _T) -> list[Any] | _T: + """ + Return all values associated with a possibly multi-valued key. + """ + + @property + def json(self) -> dict[str, str | list[str]]: + """ + A JSON-compatible form of the metadata. + """ + + +class SimplePath(Protocol): + """ + A minimal subset of pathlib.Path required by Distribution. + """ + + def joinpath( + self, other: str | os.PathLike[str] + ) -> SimplePath: ... # pragma: no cover + + def __truediv__( + self, other: str | os.PathLike[str] + ) -> SimplePath: ... # pragma: no cover + + @property + def parent(self) -> SimplePath: ... # pragma: no cover + + def read_text(self, encoding=None) -> str: ... # pragma: no cover + + def read_bytes(self) -> bytes: ... # pragma: no cover + + def exists(self) -> bool: ... # pragma: no cover diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_text.py b/python_embeded/Lib/site-packages/importlib_metadata/_text.py new file mode 100644 index 0000000000000000000000000000000000000000..c88cfbb2349c6401336bc5ba6623f51afd1eb59d --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_text.py @@ -0,0 +1,99 @@ +import re + +from ._functools import method_cache + + +# from jaraco.text 3.5 +class FoldedCase(str): + """ + A case insensitive string class; behaves just like str + except compares equal when the only variation is case. + + >>> s = FoldedCase('hello world') + + >>> s == 'Hello World' + True + + >>> 'Hello World' == s + True + + >>> s != 'Hello World' + False + + >>> s.index('O') + 4 + + >>> s.split('O') + ['hell', ' w', 'rld'] + + >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) + ['alpha', 'Beta', 'GAMMA'] + + Sequence membership is straightforward. + + >>> "Hello World" in [s] + True + >>> s in ["Hello World"] + True + + You may test for set inclusion, but candidate and elements + must both be folded. + + >>> FoldedCase("Hello World") in {s} + True + >>> s in {FoldedCase("Hello World")} + True + + String inclusion works as long as the FoldedCase object + is on the right. + + >>> "hello" in FoldedCase("Hello World") + True + + But not if the FoldedCase object is on the left: + + >>> FoldedCase('hello') in 'Hello World' + False + + In that case, use in_: + + >>> FoldedCase('hello').in_('Hello World') + True + + >>> FoldedCase('hello') > FoldedCase('Hello') + False + """ + + def __lt__(self, other): + return self.lower() < other.lower() + + def __gt__(self, other): + return self.lower() > other.lower() + + def __eq__(self, other): + return self.lower() == other.lower() + + def __ne__(self, other): + return self.lower() != other.lower() + + def __hash__(self): + return hash(self.lower()) + + def __contains__(self, other): + return super().lower().__contains__(other.lower()) + + def in_(self, other): + "Does self appear in other?" + return self in FoldedCase(other) + + # cache lower since it's likely to be called frequently. + @method_cache + def lower(self): + return super().lower() + + def index(self, sub): + return self.lower().index(sub.lower()) + + def split(self, splitter=' ', maxsplit=0): + pattern = re.compile(re.escape(splitter), re.I) + return pattern.split(self, maxsplit) diff --git a/python_embeded/Lib/site-packages/importlib_metadata/_typing.py b/python_embeded/Lib/site-packages/importlib_metadata/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..32b1d2b98ac987e8361f60362b8bdabcdc6fb1c8 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/_typing.py @@ -0,0 +1,15 @@ +import functools +import typing + +from ._meta import PackageMetadata + +md_none = functools.partial(typing.cast, PackageMetadata) +""" +Suppress type errors for optional metadata. + +Although Distribution.metadata can return None when metadata is corrupt +and thus None, allow callers to assume it's not None and crash if +that's the case. + +# python/importlib_metadata#493 +""" diff --git a/python_embeded/Lib/site-packages/importlib_metadata/diagnose.py b/python_embeded/Lib/site-packages/importlib_metadata/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..e405471ac4d94371b1ee9b1622227ff76b337180 --- /dev/null +++ b/python_embeded/Lib/site-packages/importlib_metadata/diagnose.py @@ -0,0 +1,21 @@ +import sys + +from . import Distribution + + +def inspect(path): + print("Inspecting", path) + dists = list(Distribution.discover(path=[path])) + if not dists: + return + print("Found", len(dists), "packages:", end=' ') + print(', '.join(dist.name for dist in dists)) + + +def run(): + for path in sys.path: + inspect(path) + + +if __name__ == '__main__': + run() diff --git a/python_embeded/Lib/site-packages/importlib_metadata/py.typed b/python_embeded/Lib/site-packages/importlib_metadata/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/INSTALLER b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/METADATA b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..77e96cde03dfa38e0ca1ea7c76ae2092d45c705f --- /dev/null +++ b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/METADATA @@ -0,0 +1,23 @@ +Metadata-Version: 2.4 +Name: iopath +Version: 0.1.10 +Summary: A library for providing I/O abstraction. +Home-page: https://github.com/facebookresearch/iopath +Author: FAIR +License: MIT licensed, as found in the LICENSE file +Requires-Python: >=3.6 +License-File: LICENSE +Requires-Dist: tqdm +Requires-Dist: typing_extensions +Requires-Dist: portalocker +Requires-Dist: dataclasses; python_version < "3.7" +Provides-Extra: aws +Requires-Dist: boto3; extra == "aws" +Dynamic: author +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary diff --git a/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/RECORD b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..d60b5cc05a94e8af4dcb1e58638168818da12674 --- /dev/null +++ b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/RECORD @@ -0,0 +1,27 @@ +iopath-0.1.10.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +iopath-0.1.10.dist-info/METADATA,sha256=xQCE_b4rrW5riE3SUPwCCq7TpjPJjLJkC0JXumRt9ZI,639 +iopath-0.1.10.dist-info/RECORD,, +iopath-0.1.10.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +iopath-0.1.10.dist-info/WHEEL,sha256=pxyMxgL8-pra_rKaQ4drOZAegBVuX-G_4nRHjjgWbmo,91 +iopath-0.1.10.dist-info/licenses/LICENSE,sha256=UkEte8fOQVfqYou6rLiCngqcs8WPV_mRdhJryM8r_IU,1086 +iopath-0.1.10.dist-info/top_level.txt,sha256=shzNi7iftsN1VGFvS0mhnWDt307cBAT6Mtp-dxwLQAU,7 +iopath/__init__.py,sha256=DCNdBEYQIXksia09NBXU8107msFL9fCliXDXfclkh0k,466 +iopath/__pycache__/__init__.cpython-312.pyc,, +iopath/__pycache__/version.cpython-312.pyc,, +iopath/common/__init__.py,sha256=ASP97dnFuUy1rlg0FvEkC3nj8Nhe_XuSftpGbXJr29I,244 +iopath/common/__pycache__/__init__.cpython-312.pyc,, +iopath/common/__pycache__/download.cpython-312.pyc,, +iopath/common/__pycache__/event_logger.cpython-312.pyc,, +iopath/common/__pycache__/file_io.cpython-312.pyc,, +iopath/common/__pycache__/non_blocking_io.cpython-312.pyc,, +iopath/common/__pycache__/s3.cpython-312.pyc,, +iopath/common/download.py,sha256=wwNdfhlNeSX2iEXU50sCxfMnP0o_RNMiGSpS6QODzsU,2653 +iopath/common/event_logger.py,sha256=AE_GX66PCyYMQzkXhdcPEpPpPE48UYN8aQb7vFFEHzc,3322 +iopath/common/file_io.py,sha256=_SA5HI6-us-ay8EzbwZDQz3VZoQQ5VwNBeBm1Rz9VB4,58735 +iopath/common/non_blocking_io.py,sha256=zQHaAkBnd5lyWSJiCwK13uAp14bn7jaYJOlM5KSvlZA,15720 +iopath/common/s3.py,sha256=LKXtv1W6P1RBXrzrnYpM2SfSQQiZPiFjsExey7p8na0,31653 +iopath/tabular/__init__.py,sha256=Jb-eSAPyOHkHiamF-iVR-7AmZbw_CjN_svyCVrFOFPc,72 +iopath/tabular/__pycache__/__init__.cpython-312.pyc,, +iopath/tabular/__pycache__/tabular_io.cpython-312.pyc,, +iopath/tabular/tabular_io.py,sha256=Wyh5Ie6ggOf5U6NWKTVdQH74kT_aTs392Qxow2iEgWU,504 +iopath/version.py,sha256=1UEOlVj1DAs_xg1_WVbroxsduCyrXV9MBdxHUKASYRE,96 diff --git a/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/REQUESTED b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/WHEEL b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..f6e58ac2efd88aaaeeb06afb2740850e2a191b93 --- /dev/null +++ b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/top_level.txt b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66459e0664cba09de6df1760c98961128fa16567 --- /dev/null +++ b/python_embeded/Lib/site-packages/iopath-0.1.10.dist-info/top_level.txt @@ -0,0 +1 @@ +iopath diff --git a/python_embeded/Lib/site-packages/iopath/__init__.py b/python_embeded/Lib/site-packages/iopath/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e40081f27b50dfdbc4cc34122b7b06629366dba --- /dev/null +++ b/python_embeded/Lib/site-packages/iopath/__init__.py @@ -0,0 +1,18 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + +from iopath.common import file_lock, get_cache_dir, LazyPath, PathManager +from iopath.tabular.tabular_io import TabularPathHandler, TabularUriParser + +from .version import __version__ + + +# pyre-fixme[5]: Global expression must be annotated. +__all__ = [ + "LazyPath", + "PathManager", + "get_cache_dir", + "file_lock", + "TabularPathHandler", + "TabularUriParser", + __version__, +] diff --git a/python_embeded/Lib/site-packages/iopath/version.py b/python_embeded/Lib/site-packages/iopath/version.py new file mode 100644 index 0000000000000000000000000000000000000000..b21266d9628ca163ec4f2c3f8f6105e9efe116a7 --- /dev/null +++ b/python_embeded/Lib/site-packages/iopath/version.py @@ -0,0 +1,3 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + +__version__ = "0.1.10" diff --git a/python_embeded/Lib/site-packages/isapi/PyISAPI_loader.dll b/python_embeded/Lib/site-packages/isapi/PyISAPI_loader.dll new file mode 100644 index 0000000000000000000000000000000000000000..90a89d742cec4735d76e9efa56454568c2540b99 Binary files /dev/null and b/python_embeded/Lib/site-packages/isapi/PyISAPI_loader.dll differ diff --git a/python_embeded/Lib/site-packages/isapi/README.txt b/python_embeded/Lib/site-packages/isapi/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..1beae22e90f0b546e1e92ba8a4fbdd1cd643ca19 --- /dev/null +++ b/python_embeded/Lib/site-packages/isapi/README.txt @@ -0,0 +1,7 @@ +A Python ISAPI extension. Contributed by Phillip Frantz, and is +Copyright 2002-2003 by Blackdog Software Pty Ltd. + +See the 'samples' directory, and particularly samples\README.txt + +You can find documentation in the PyWin32.chm file that comes with pywin32 - +you can open this from Pythonwin->Help, or from the start menu. diff --git a/python_embeded/Lib/site-packages/isapi/__init__.py b/python_embeded/Lib/site-packages/isapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4e869ebfa28654927b4b31100c04e58ff9848ec --- /dev/null +++ b/python_embeded/Lib/site-packages/isapi/__init__.py @@ -0,0 +1,39 @@ +# The Python ISAPI package. + + +# Exceptions thrown by the DLL framework. +class ISAPIError(Exception): + def __init__(self, errno, strerror=None, funcname=None): + # named attributes match OSError etc. + self.errno = errno + self.strerror = strerror + self.funcname = funcname + Exception.__init__(self, errno, strerror, funcname) + + def __str__(self): + if self.strerror is None: + try: + import win32api + + self.strerror = win32api.FormatMessage(self.errno).strip() + except: + self.strerror = "no error message is available" + # str() looks like a win32api error. + return str((self.errno, self.strerror, self.funcname)) + + +class FilterError(ISAPIError): + pass + + +class ExtensionError(ISAPIError): + pass + + +# A little development aid - a filter or extension callback function can +# raise one of these exceptions, and the handler module will be reloaded. +# This means you can change your code without restarting IIS. +# After a reload, your filter/extension will have the GetFilterVersion/ +# GetExtensionVersion function called, but with None as the first arg. +class InternalReloadException(Exception): + pass diff --git a/python_embeded/Lib/site-packages/isapi/install.py b/python_embeded/Lib/site-packages/isapi/install.py new file mode 100644 index 0000000000000000000000000000000000000000..b62c19442f9e23a19fd49adcdec2d2e2d15b7fd6 --- /dev/null +++ b/python_embeded/Lib/site-packages/isapi/install.py @@ -0,0 +1,809 @@ +"""Installation utilities for Python ISAPI filters and extensions.""" + +# this code adapted from "Tomcat JK2 ISAPI redirector", part of Apache +# Created July 2004, Mark Hammond. +from __future__ import annotations + +import importlib.machinery +import os +import shutil +import stat +import sys +import traceback +from collections.abc import Mapping + +import pythoncom +import win32api +import winerror +from win32com.client import GetObject + +_APP_INPROC = 0 +_APP_OUTPROC = 1 +_APP_POOLED = 2 +_IIS_OBJECT = "IIS://LocalHost/W3SVC" +_IIS_SERVER = "IIsWebServer" +_IIS_WEBDIR = "IIsWebDirectory" +_IIS_WEBVIRTUALDIR = "IIsWebVirtualDir" +_IIS_FILTERS = "IIsFilters" +_IIS_FILTER = "IIsFilter" + +_DEFAULT_SERVER_NAME = "Default Web Site" +_DEFAULT_HEADERS = "X-Powered-By: Python" +_DEFAULT_PROTECTION = _APP_POOLED + +# Default is for 'execute' only access - ie, only the extension +# can be used. This can be overridden via your install script. +_DEFAULT_ACCESS_EXECUTE = True +_DEFAULT_ACCESS_READ = False +_DEFAULT_ACCESS_WRITE = False +_DEFAULT_ACCESS_SCRIPT = False +_DEFAULT_CONTENT_INDEXED = False +_DEFAULT_ENABLE_DIR_BROWSING = False +_DEFAULT_ENABLE_DEFAULT_DOC = False + +this_dir = os.path.abspath(os.path.dirname(__file__)) + + +class FilterParameters: + Name = None + Description = None + Path = None + Server = None + # Params that control if/how AddExtensionFile is called. + AddExtensionFile = True + AddExtensionFile_Enabled = True + AddExtensionFile_GroupID = None # defaults to Name + AddExtensionFile_CanDelete = True + AddExtensionFile_Description = None # defaults to Description. + + def __init__(self, **kw): + self.__dict__.update(kw) + + +class VirtualDirParameters: + Name = None # Must be provided. + Description = None # defaults to Name + AppProtection = _DEFAULT_PROTECTION + Headers = _DEFAULT_HEADERS + Path = None # defaults to WWW root. + Type = _IIS_WEBVIRTUALDIR + AccessExecute = _DEFAULT_ACCESS_EXECUTE + AccessRead = _DEFAULT_ACCESS_READ + AccessWrite = _DEFAULT_ACCESS_WRITE + AccessScript = _DEFAULT_ACCESS_SCRIPT + ContentIndexed = _DEFAULT_CONTENT_INDEXED + EnableDirBrowsing = _DEFAULT_ENABLE_DIR_BROWSING + EnableDefaultDoc = _DEFAULT_ENABLE_DEFAULT_DOC + DefaultDoc = None # Only set in IIS if not None + ScriptMaps: list[ScriptMapParams] = [] + ScriptMapUpdate = "end" # can be 'start', 'end', 'replace' + Server = None + + def __init__(self, **kw): + self.__dict__.update(kw) + + def is_root(self): + "This virtual directory is a root directory if parent and name are blank" + parent, name = self.split_path() + return not parent and not name + + def split_path(self): + return split_path(self.Name) + + +class ScriptMapParams: + Extension = None + Module = None + Flags = 5 + Verbs = "" + # Params that control if/how AddExtensionFile is called. + AddExtensionFile = True + AddExtensionFile_Enabled = True + AddExtensionFile_GroupID = None # defaults to Name + AddExtensionFile_CanDelete = True + AddExtensionFile_Description = None # defaults to Description. + + def __init__(self, **kw): + self.__dict__.update(kw) + + def __str__(self): + "Format this parameter suitable for IIS" + items = [self.Extension, self.Module, self.Flags] + # IIS gets upset if there is a trailing verb comma, but no verbs + if self.Verbs: + items.append(self.Verbs) + items = [str(item) for item in items] + return ",".join(items) + + +class ISAPIParameters: + ServerName = _DEFAULT_SERVER_NAME + # Description = None + Filters: list[FilterParameters] = [] + VirtualDirs: list[VirtualDirParameters] = [] + + def __init__(self, **kw): + self.__dict__.update(kw) + + +verbose = 1 # The level - 0 is quiet. + + +def log(level, what): + if verbose >= level: + print(what) + + +# Convert an ADSI COM exception to the Win32 error code embedded in it. +def _GetWin32ErrorCode(com_exc): + hr = com_exc.hresult + # If we have more details in the 'excepinfo' struct, use it. + if com_exc.excepinfo: + hr = com_exc.excepinfo[-1] + if winerror.HRESULT_FACILITY(hr) != winerror.FACILITY_WIN32: + raise + return winerror.SCODE_CODE(hr) + + +class InstallationError(Exception): + pass + + +class ItemNotFound(InstallationError): + pass + + +class ConfigurationError(InstallationError): + pass + + +def FindPath(options, server, name): + if name.lower().startswith("iis://"): + return name + else: + if name and name[0] != "/": + name = "/" + name + return FindWebServer(options, server) + "/ROOT" + name + + +def LocateWebServerPath(description): + """ + Find an IIS web server whose name or comment matches the provided + description (case-insensitive). + + >>> LocateWebServerPath('Default Web Site') # doctest: +SKIP + + or + + >>> LocateWebServerPath('1') #doctest: +SKIP + """ + assert len(description) >= 1, "Server name or comment is required" + iis = GetObject(_IIS_OBJECT) + description = description.lower().strip() + for site in iis: + # Name is generally a number, but no need to assume that. + site_attributes = [ + getattr(site, attr, "").lower().strip() + for attr in ("Name", "ServerComment") + ] + if description in site_attributes: + return site.AdsPath + msg = "No web sites match the description '%s'" % description + raise ItemNotFound(msg) + + +def GetWebServer(description=None): + """ + Load the web server instance (COM object) for a given instance + or description. + If None is specified, the default website is retrieved (indicated + by the identifier 1. + """ + description = description or "1" + path = LocateWebServerPath(description) + server = LoadWebServer(path) + return server + + +def LoadWebServer(path): + try: + server = GetObject(path) + except pythoncom.com_error as exc: + msg = exc.strerror + if exc.excepinfo and exc.excepinfo[2]: + msg = exc.excepinfo[2] + msg = f"WebServer {path}: {msg}" + raise ItemNotFound(msg) + return server + + +def FindWebServer(options, server_desc): + """ + Legacy function to allow options to define a .server property + to override the other parameter. Use GetWebServer instead. + """ + # options takes precedence + server_desc = options.server or server_desc + # make sure server_desc is unicode (could be mbcs if passed in + # sys.argv). + if server_desc and not isinstance(server_desc, str): + server_desc = server_desc.decode("mbcs") + + # get the server (if server_desc is None, the default site is acquired) + server = GetWebServer(server_desc) + return server.adsPath + + +def split_path(path): + """ + Get the parent path and basename. + + >>> split_path('/') + ['', ''] + + >>> split_path('') + ['', ''] + + >>> split_path('foo') + ['', 'foo'] + + >>> split_path('/foo') + ['', 'foo'] + + >>> split_path('/foo/bar') + ['/foo', 'bar'] + + >>> split_path('foo/bar') + ['/foo', 'bar'] + """ + + if not path.startswith("/"): + path = "/" + path + return path.rsplit("/", 1) + + +def _CreateDirectory(iis_dir, name, params): + # We used to go to lengths to keep an existing virtual directory + # in place. However, in some cases the existing directories got + # into a bad state, and an update failed to get them working. + # So we nuke it first. If this is a problem, we could consider adding + # a --keep-existing option. + try: + # Also seen the Class change to a generic IISObject - so nuke + # *any* existing object, regardless of Class + assert name.strip("/"), "mustn't delete the root!" + iis_dir.Delete("", name) + log(2, f"Deleted old directory '{name}'") + except pythoncom.com_error: + pass + + newDir = iis_dir.Create(params.Type, name) + log(2, f"Creating new directory '{name}' in {iis_dir.Name}...") + + friendly = params.Description or params.Name + newDir.AppFriendlyName = friendly + + # Note that the new directory won't be visible in the IIS UI + # unless the directory exists on the filesystem. + try: + path = params.Path or iis_dir.Path + newDir.Path = path + except AttributeError: + # If params.Type is IIS_WEBDIRECTORY, an exception is thrown + pass + newDir.AppCreate2(params.AppProtection) + # XXX - note that these Headers only work in IIS6 and earlier. IIS7 + # only supports them on the w3svc node - not even on individial sites, + # let alone individual extensions in the site! + if params.Headers: + newDir.HttpCustomHeaders = params.Headers + + log(2, "Setting directory options...") + newDir.AccessExecute = params.AccessExecute + newDir.AccessRead = params.AccessRead + newDir.AccessWrite = params.AccessWrite + newDir.AccessScript = params.AccessScript + newDir.ContentIndexed = params.ContentIndexed + newDir.EnableDirBrowsing = params.EnableDirBrowsing + newDir.EnableDefaultDoc = params.EnableDefaultDoc + if params.DefaultDoc is not None: + newDir.DefaultDoc = params.DefaultDoc + newDir.SetInfo() + return newDir + + +def CreateDirectory(params, options): + _CallHook(params, "PreInstall", options) + if not params.Name: + raise ConfigurationError("No Name param") + parent, name = params.split_path() + target_dir = GetObject(FindPath(options, params.Server, parent)) + + if not params.is_root(): + target_dir = _CreateDirectory(target_dir, name, params) + + AssignScriptMaps(params.ScriptMaps, target_dir, params.ScriptMapUpdate) + + _CallHook(params, "PostInstall", options, target_dir) + log(1, f"Configured Virtual Directory: {params.Name}") + return target_dir + + +def AssignScriptMaps(script_maps, target, update="replace"): + """Updates IIS with the supplied script map information. + + script_maps is a list of ScriptMapParameter objects + + target is an IIS Virtual Directory to assign the script maps to + + update is a string indicating how to update the maps, one of ('start', + 'end', or 'replace') + """ + # determine which function to use to assign script maps + script_map_func = "_AssignScriptMaps" + update.capitalize() + try: + script_map_func = eval(script_map_func) + except NameError: + msg = "Unknown ScriptMapUpdate option '%s'" % update + raise ConfigurationError(msg) + # use the str method to format the script maps for IIS + script_maps = [str(s) for s in script_maps] + # call the correct function + script_map_func(target, script_maps) + target.SetInfo() + + +def get_unique_items(sequence, reference): + "Return items in sequence that can't be found in reference." + return tuple([item for item in sequence if item not in reference]) + + +def _AssignScriptMapsReplace(target, script_maps): + target.ScriptMaps = script_maps + + +def _AssignScriptMapsEnd(target, script_maps): + unique_new_maps = get_unique_items(script_maps, target.ScriptMaps) + target.ScriptMaps += unique_new_maps + + +def _AssignScriptMapsStart(target, script_maps): + unique_new_maps = get_unique_items(script_maps, target.ScriptMaps) + target.ScriptMaps = unique_new_maps + target.ScriptMaps + + +def CreateISAPIFilter(filterParams, options): + server = FindWebServer(options, filterParams.Server) + _CallHook(filterParams, "PreInstall", options) + try: + filters = GetObject(server + "/Filters") + except pythoncom.com_error as exc: + # Brand new sites don't have the '/Filters' collection - create it. + # Any errors other than 'not found' we shouldn't ignore. + if ( + winerror.HRESULT_FACILITY(exc.hresult) != winerror.FACILITY_WIN32 + or winerror.HRESULT_CODE(exc.hresult) != winerror.ERROR_PATH_NOT_FOUND + ): + raise + server_ob = GetObject(server) + filters = server_ob.Create(_IIS_FILTERS, "Filters") + filters.FilterLoadOrder = "" + filters.SetInfo() + + # As for VirtualDir, delete an existing one. + assert filterParams.Name.strip("/"), "mustn't delete the root!" + try: + filters.Delete(_IIS_FILTER, filterParams.Name) + log(2, f"Deleted old filter '{filterParams.Name}'") + except pythoncom.com_error: + pass + newFilter = filters.Create(_IIS_FILTER, filterParams.Name) + log(2, "Created new ISAPI filter...") + assert os.path.isfile(filterParams.Path) + newFilter.FilterPath = filterParams.Path + newFilter.FilterDescription = filterParams.Description + newFilter.SetInfo() + load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b] + if filterParams.Name not in load_order: + load_order.append(filterParams.Name) + filters.FilterLoadOrder = ",".join(load_order) + filters.SetInfo() + _CallHook(filterParams, "PostInstall", options, newFilter) + log(1, f"Configured Filter: {filterParams.Name}") + return newFilter + + +def DeleteISAPIFilter(filterParams, options): + _CallHook(filterParams, "PreRemove", options) + server = FindWebServer(options, filterParams.Server) + ob_path = server + "/Filters" + try: + filters = GetObject(ob_path) + except pythoncom.com_error as details: + # failure to open the filters just means a totally clean IIS install + # (IIS5 at least has no 'Filters' key when freshly installed). + log(2, f"ISAPI filter path '{ob_path}' did not exist.") + return + try: + assert filterParams.Name.strip("/"), "mustn't delete the root!" + filters.Delete(_IIS_FILTER, filterParams.Name) + log(2, f"Deleted ISAPI filter '{filterParams.Name}'") + except pythoncom.com_error as details: + rc = _GetWin32ErrorCode(details) + if rc != winerror.ERROR_PATH_NOT_FOUND: + raise + log(2, f"ISAPI filter '{filterParams.Name}' did not exist.") + # Remove from the load order + load_order = [b.strip() for b in filters.FilterLoadOrder.split(",") if b] + if filterParams.Name in load_order: + load_order.remove(filterParams.Name) + filters.FilterLoadOrder = ",".join(load_order) + filters.SetInfo() + _CallHook(filterParams, "PostRemove", options) + log(1, f"Deleted Filter: {filterParams.Name}") + + +def _AddExtensionFile(module, def_groupid, def_desc, params, options): + group_id = params.AddExtensionFile_GroupID or def_groupid + desc = params.AddExtensionFile_Description or def_desc + try: + ob = GetObject(_IIS_OBJECT) + ob.AddExtensionFile( + module, + params.AddExtensionFile_Enabled, + group_id, + params.AddExtensionFile_CanDelete, + desc, + ) + log(2, f"Added extension file '{module}' ({desc})") + except (pythoncom.com_error, AttributeError) as details: + # IIS5 always fails. Probably should upgrade this to + # complain more loudly if IIS6 fails. + log(2, f"Failed to add extension file '{module}': {details}") + + +def AddExtensionFiles(params, options): + """Register the modules used by the filters/extensions as a trusted + 'extension module' - required by the default IIS6 security settings.""" + # Add each module only once. + added = {} + for vd in params.VirtualDirs: + for smp in vd.ScriptMaps: + if smp.Module not in added and smp.AddExtensionFile: + _AddExtensionFile(smp.Module, vd.Name, vd.Description, smp, options) + added[smp.Module] = True + + for fd in params.Filters: + if fd.Path not in added and fd.AddExtensionFile: + _AddExtensionFile(fd.Path, fd.Name, fd.Description, fd, options) + added[fd.Path] = True + + +def _DeleteExtensionFileRecord(module, options): + try: + ob = GetObject(_IIS_OBJECT) + ob.DeleteExtensionFileRecord(module) + log(2, "Deleted extension file record for '%s'" % module) + except (pythoncom.com_error, AttributeError) as details: + log(2, f"Failed to remove extension file '{module}': {details}") + + +def DeleteExtensionFileRecords(params, options): + deleted = {} # only remove each .dll once. + for vd in params.VirtualDirs: + for smp in vd.ScriptMaps: + if smp.Module not in deleted and smp.AddExtensionFile: + _DeleteExtensionFileRecord(smp.Module, options) + deleted[smp.Module] = True + + for filter_def in params.Filters: + if filter_def.Path not in deleted and filter_def.AddExtensionFile: + _DeleteExtensionFileRecord(filter_def.Path, options) + deleted[filter_def.Path] = True + + +def CheckLoaderModule(dll_name): + suffix = "_d" if "_d.pyd" in importlib.machinery.EXTENSION_SUFFIXES else "" + template = os.path.join(this_dir, "PyISAPI_loader" + suffix + ".dll") + if not os.path.isfile(template): + raise ConfigurationError(f"Template loader '{template}' does not exist") + # We can't do a simple "is newer" check, as the DLL is specific to the + # Python version. So we check the date-time and size are identical, + # and skip the copy in that case. + src_stat = os.stat(template) + try: + dest_stat = os.stat(dll_name) + except OSError: + same = 0 + else: + same = ( + src_stat[stat.ST_SIZE] == dest_stat[stat.ST_SIZE] + and src_stat[stat.ST_MTIME] == dest_stat[stat.ST_MTIME] + ) + if not same: + log(2, f"Updating {template}->{dll_name}") + shutil.copyfile(template, dll_name) + shutil.copystat(template, dll_name) + else: + log(2, f"{dll_name} is up to date.") + + +def _CallHook(ob, hook_name, options, *extra_args): + func = getattr(ob, hook_name, None) + if func is not None: + args = (ob, options) + extra_args + func(*args) + + +def Install(params, options): + _CallHook(params, "PreInstall", options) + for vd in params.VirtualDirs: + CreateDirectory(vd, options) + + for filter_def in params.Filters: + CreateISAPIFilter(filter_def, options) + + AddExtensionFiles(params, options) + + _CallHook(params, "PostInstall", options) + + +def RemoveDirectory(params, options): + if params.is_root(): + return + try: + directory = GetObject(FindPath(options, params.Server, params.Name)) + except pythoncom.com_error as details: + rc = _GetWin32ErrorCode(details) + if rc != winerror.ERROR_PATH_NOT_FOUND: + raise + log(2, "VirtualDirectory '%s' did not exist" % params.Name) + directory = None + if directory is not None: + # Be robust should IIS get upset about unloading. + try: + directory.AppUnLoad() + except: + exc_val = sys.exc_info()[1] + log(2, f"AppUnLoad() for {params.Name} failed: {exc_val}") + # Continue trying to delete it. + try: + parent = GetObject(directory.Parent) + parent.Delete(directory.Class, directory.Name) + log(1, f"Deleted Virtual Directory: {params.Name}") + except: + exc_val = sys.exc_info()[1] + log(1, f"Failed to remove directory {params.Name}: {exc_val}") + + +def RemoveScriptMaps(vd_params, options): + "Remove script maps from the already installed virtual directory" + parent, name = vd_params.split_path() + target_dir = GetObject(FindPath(options, vd_params.Server, parent)) + installed_maps = list(target_dir.ScriptMaps) + for _map in map(str, vd_params.ScriptMaps): + if _map in installed_maps: + installed_maps.remove(_map) + target_dir.ScriptMaps = installed_maps + target_dir.SetInfo() + + +def Uninstall(params, options): + _CallHook(params, "PreRemove", options) + + DeleteExtensionFileRecords(params, options) + + for vd in params.VirtualDirs: + _CallHook(vd, "PreRemove", options) + + RemoveDirectory(vd, options) + if vd.is_root(): + # if this is installed to the root virtual directory, we can't delete it + # so remove the script maps. + RemoveScriptMaps(vd, options) + + _CallHook(vd, "PostRemove", options) + + for filter_def in params.Filters: + DeleteISAPIFilter(filter_def, options) + _CallHook(params, "PostRemove", options) + + +# Patch up any missing module names in the params, replacing them with +# the DLL name that hosts this extension/filter. +def _PatchParamsModule(params, dll_name, file_must_exist=True): + if file_must_exist: + if not os.path.isfile(dll_name): + raise ConfigurationError(f"{dll_name} does not exist") + + # Patch up all references to the DLL. + for f in params.Filters: + if f.Path is None: + f.Path = dll_name + for d in params.VirtualDirs: + for sm in d.ScriptMaps: + if sm.Module is None: + sm.Module = dll_name + + +def GetLoaderModuleName(mod_name, check_module=None): + # find the name of the DLL hosting us. + # By default, this is "_{module_base_name}.dll" + if hasattr(sys, "frozen"): + # What to do? The .dll knows its name, but this is likely to be + # executed via a .exe, which does not know. + base, ext = os.path.splitext(mod_name) + path, base = os.path.split(base) + # handle the common case of 'foo.exe'/'foow.exe' + if base.endswith("w"): + base = base[:-1] + # For py2exe, we have '_foo.dll' as the standard pyisapi loader - but + # 'foo.dll' is what we use (it just delegates). + # So no leading '_' on the installed name. + dll_name = os.path.abspath(os.path.join(path, base + ".dll")) + else: + base, ext = os.path.splitext(mod_name) + path, base = os.path.split(base) + dll_name = os.path.abspath(os.path.join(path, "_" + base + ".dll")) + # Check we actually have it. + if check_module is None: + check_module = not hasattr(sys, "frozen") + if check_module: + CheckLoaderModule(dll_name) + return dll_name + + +# Note the 'log' params to these 'builtin' args - old versions of pywin32 +# didn't log at all in this function (by intent; anyone calling this was +# responsible). So existing code that calls this function with the old +# signature (ie, without a 'log' param) still gets the same behaviour as +# before... + + +def InstallModule(conf_module_name, params, options, log=lambda *args: None): + "Install the extension" + if not hasattr(sys, "frozen"): + conf_module_name = os.path.abspath(conf_module_name) + if not os.path.isfile(conf_module_name): + raise ConfigurationError(f"{conf_module_name} does not exist") + + loader_dll = GetLoaderModuleName(conf_module_name) + _PatchParamsModule(params, loader_dll) + Install(params, options) + log(1, "Installation complete.") + + +def UninstallModule(conf_module_name, params, options, log=lambda *args: None): + "Remove the extension" + loader_dll = GetLoaderModuleName(conf_module_name, False) + _PatchParamsModule(params, loader_dll, False) + Uninstall(params, options) + log(1, "Uninstallation complete.") + + +standard_arguments = { + "install": InstallModule, + "remove": UninstallModule, +} + + +def build_usage(handler_map: Mapping[str, object]) -> str: + arg_names = "|".join(handler_map) + lines = [ + " %-10s: %s" % (arg, handler.__doc__) for arg, handler in handler_map.items() + ] + return f"%prog [options] [{arg_names}]\ncommands:\n" + "\n".join(lines) + + +def MergeStandardOptions(options, params): + """ + Take an options object generated by the command line and merge + the values into the IISParameters object. + """ + pass + + +# We support 2 ways of extending our command-line/install support. +# * Many of the installation items allow you to specify "PreInstall", +# "PostInstall", "PreRemove" and "PostRemove" hooks +# All hooks are called with the 'params' object being operated on, and +# the 'optparser' options for this session (ie, the command-line options) +# PostInstall for VirtualDirectories and Filters both have an additional +# param - the ADSI object just created. +# * You can pass your own option parser for us to use, and/or define a map +# with your own custom arg handlers. It is a map of 'arg'->function. +# The function is called with (options, log_fn, arg). The function's +# docstring is used in the usage output. +def HandleCommandLine( + params, + argv=None, + conf_module_name=None, + default_arg="install", + opt_parser=None, + custom_arg_handlers={}, +): + """Perform installation or removal of an ISAPI filter or extension. + + This module handles standard command-line options and configuration + information, and installs, removes or updates the configuration of an + ISAPI filter or extension. + + You must pass your configuration information in params - all other + arguments are optional, and allow you to configure the installation + process. + """ + global verbose + from optparse import OptionParser + + argv = argv or sys.argv + if not conf_module_name: + conf_module_name = sys.argv[0] + # convert to a long name so that if we were somehow registered with + # the "short" version but unregistered with the "long" version we + # still work (that will depend on exactly how the installer was + # started) + try: + conf_module_name = win32api.GetLongPathName(conf_module_name) + except win32api.error as exc: + log( + 2, + f"Couldn't determine the long name for {conf_module_name!r}: {exc}", + ) + + if opt_parser is None: + # Build our own parser. + parser = OptionParser(usage="") + else: + # The caller is providing their own filter, presumably with their + # own options all setup. + parser = opt_parser + + # build a usage string if we don't have one. + if not parser.get_usage(): + all_handlers = standard_arguments.copy() + all_handlers.update(custom_arg_handlers) + parser.set_usage(build_usage(all_handlers)) + + # allow the user to use uninstall as a synonym for remove if it wasn't + # defined by the custom arg handlers. + all_handlers.setdefault("uninstall", all_handlers["remove"]) + + parser.add_option( + "-q", + "--quiet", + action="store_false", + dest="verbose", + default=True, + help="don't print status messages to stdout", + ) + parser.add_option( + "-v", + "--verbosity", + action="count", + dest="verbose", + default=1, + help="increase the verbosity of status messages", + ) + parser.add_option( + "", + "--server", + action="store", + help="Specifies the IIS server to install/uninstall on." + f" Default is '{_IIS_OBJECT}/1'", + ) + + (options, args) = parser.parse_args(argv[1:]) + MergeStandardOptions(options, params) + verbose = options.verbose + if not args: + args = [default_arg] + try: + for arg in args: + handler = all_handlers[arg] + handler(conf_module_name, params, options, log) + except (ItemNotFound, InstallationError) as details: + if options.verbose > 1: + traceback.print_exc() + print(f"{details.__class__.__name__}: {details}") + except KeyError: + parser.error("Invalid arg '%s'" % arg) diff --git a/python_embeded/Lib/site-packages/isapi/isapicon.py b/python_embeded/Lib/site-packages/isapi/isapicon.py new file mode 100644 index 0000000000000000000000000000000000000000..07856d1d19dd9190eaadce4098b83479ef2e574d --- /dev/null +++ b/python_embeded/Lib/site-packages/isapi/isapicon.py @@ -0,0 +1,121 @@ +"""Constants needed by ISAPI filters and extensions.""" + +# ====================================================================== +# Copyright 2002-2003 by Blackdog Software Pty Ltd. +# +# All Rights Reserved +# +# Permission to use, copy, modify, and distribute this software and +# its documentation for any purpose and without fee is hereby +# granted, provided that the above copyright notice appear in all +# copies and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Blackdog Software not be used in advertising or publicity pertaining to +# distribution of the software without specific, written prior +# permission. +# +# BLACKDOG SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN +# NO EVENT SHALL BLACKDOG SOFTWARE BE LIABLE FOR ANY SPECIAL, INDIRECT OR +# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# ====================================================================== + +# HTTP reply codes + +HTTP_CONTINUE = 100 +HTTP_SWITCHING_PROTOCOLS = 101 +HTTP_PROCESSING = 102 +HTTP_OK = 200 +HTTP_CREATED = 201 +HTTP_ACCEPTED = 202 +HTTP_NON_AUTHORITATIVE = 203 +HTTP_NO_CONTENT = 204 +HTTP_RESET_CONTENT = 205 +HTTP_PARTIAL_CONTENT = 206 +HTTP_MULTI_STATUS = 207 +HTTP_MULTIPLE_CHOICES = 300 +HTTP_MOVED_PERMANENTLY = 301 +HTTP_MOVED_TEMPORARILY = 302 +HTTP_SEE_OTHER = 303 +HTTP_NOT_MODIFIED = 304 +HTTP_USE_PROXY = 305 +HTTP_TEMPORARY_REDIRECT = 307 +HTTP_BAD_REQUEST = 400 +HTTP_UNAUTHORIZED = 401 +HTTP_PAYMENT_REQUIRED = 402 +HTTP_FORBIDDEN = 403 +HTTP_NOT_FOUND = 404 +HTTP_METHOD_NOT_ALLOWED = 405 +HTTP_NOT_ACCEPTABLE = 406 +HTTP_PROXY_AUTHENTICATION_REQUIRED = 407 +HTTP_REQUEST_TIME_OUT = 408 +HTTP_CONFLICT = 409 +HTTP_GONE = 410 +HTTP_LENGTH_REQUIRED = 411 +HTTP_PRECONDITION_FAILED = 412 +HTTP_REQUEST_ENTITY_TOO_LARGE = 413 +HTTP_REQUEST_URI_TOO_LARGE = 414 +HTTP_UNSUPPORTED_MEDIA_TYPE = 415 +HTTP_RANGE_NOT_SATISFIABLE = 416 +HTTP_EXPECTATION_FAILED = 417 +HTTP_UNPROCESSABLE_ENTITY = 422 +HTTP_INTERNAL_SERVER_ERROR = 500 +HTTP_NOT_IMPLEMENTED = 501 +HTTP_BAD_GATEWAY = 502 +HTTP_SERVICE_UNAVAILABLE = 503 +HTTP_GATEWAY_TIME_OUT = 504 +HTTP_VERSION_NOT_SUPPORTED = 505 +HTTP_VARIANT_ALSO_VARIES = 506 + +HSE_STATUS_SUCCESS = 1 +HSE_STATUS_SUCCESS_AND_KEEP_CONN = 2 +HSE_STATUS_PENDING = 3 +HSE_STATUS_ERROR = 4 + +SF_NOTIFY_SECURE_PORT = 0x00000001 +SF_NOTIFY_NONSECURE_PORT = 0x00000002 +SF_NOTIFY_READ_RAW_DATA = 0x00008000 +SF_NOTIFY_PREPROC_HEADERS = 0x00004000 +SF_NOTIFY_AUTHENTICATION = 0x00002000 +SF_NOTIFY_URL_MAP = 0x00001000 +SF_NOTIFY_ACCESS_DENIED = 0x00000800 +SF_NOTIFY_SEND_RESPONSE = 0x00000040 +SF_NOTIFY_SEND_RAW_DATA = 0x00000400 +SF_NOTIFY_LOG = 0x00000200 +SF_NOTIFY_END_OF_REQUEST = 0x00000080 +SF_NOTIFY_END_OF_NET_SESSION = 0x00000100 + +SF_NOTIFY_ORDER_HIGH = 0x00080000 +SF_NOTIFY_ORDER_MEDIUM = 0x00040000 +SF_NOTIFY_ORDER_LOW = 0x00020000 +SF_NOTIFY_ORDER_DEFAULT = SF_NOTIFY_ORDER_LOW + +SF_NOTIFY_ORDER_MASK = ( + SF_NOTIFY_ORDER_HIGH | SF_NOTIFY_ORDER_MEDIUM | SF_NOTIFY_ORDER_LOW +) + +SF_STATUS_REQ_FINISHED = 134217728 # 0x8000000 +SF_STATUS_REQ_FINISHED_KEEP_CONN = 134217728 + 1 +SF_STATUS_REQ_NEXT_NOTIFICATION = 134217728 + 2 +SF_STATUS_REQ_HANDLED_NOTIFICATION = 134217728 + 3 +SF_STATUS_REQ_ERROR = 134217728 + 4 +SF_STATUS_REQ_READ_NEXT = 134217728 + 5 + +HSE_IO_SYNC = 0x00000001 # for WriteClient +HSE_IO_ASYNC = 0x00000002 # for WriteClient/TF/EU +HSE_IO_DISCONNECT_AFTER_SEND = 0x00000004 # for TF +HSE_IO_SEND_HEADERS = 0x00000008 # for TF +HSE_IO_NODELAY = 0x00001000 # turn off nagling +# These two are only used by VectorSend +HSE_IO_FINAL_SEND = 0x00000010 +HSE_IO_CACHE_RESPONSE = 0x00000020 + +HSE_EXEC_URL_NO_HEADERS = 0x02 +HSE_EXEC_URL_IGNORE_CURRENT_INTERCEPTOR = 0x04 +HSE_EXEC_URL_IGNORE_VALIDATION_AND_RANGE = 0x10 +HSE_EXEC_URL_DISABLE_CUSTOM_ERROR = 0x20 +HSE_EXEC_URL_SSI_CMD = 0x40 +HSE_EXEC_URL_HTTP_CACHE_ELIGIBLE = 0x80 diff --git a/python_embeded/Lib/site-packages/isapi/simple.py b/python_embeded/Lib/site-packages/isapi/simple.py new file mode 100644 index 0000000000000000000000000000000000000000..e7129fd65d2157d591be3f776294c686529aeaf7 --- /dev/null +++ b/python_embeded/Lib/site-packages/isapi/simple.py @@ -0,0 +1,73 @@ +"""Simple base-classes for extensions and filters. + +None of the filter and extension functions are considered 'optional' by the +framework. These base-classes provide simple implementations for the +Initialize and Terminate functions, allowing you to omit them, + +It is not necessary to use these base-classes - but if you don't, you +must ensure each of the required methods are implemented. +""" + +from __future__ import annotations + + +class SimpleExtension: + "Base class for a simple ISAPI extension" + + def __init__(self): + pass + + def GetExtensionVersion(self, vi): + """Called by the ISAPI framework to get the extension version + + The default implementation uses the classes docstring to + set the extension description.""" + # nod to our reload capability - vi is None when we are reloaded. + if vi is not None: + vi.ExtensionDesc = self.__doc__ + + def HttpExtensionProc(self, control_block): + """Called by the ISAPI framework for each extension request. + + sub-classes must provide an implementation for this method. + """ + raise NotImplementedError("sub-classes should override HttpExtensionProc") + + def TerminateExtension(self, status): + """Called by the ISAPI framework as the extension terminates.""" + pass + + +class SimpleFilter: + "Base class for a a simple ISAPI filter" + + filter_flags: int | None = None + + def __init__(self): + pass + + def GetFilterVersion(self, fv): + """Called by the ISAPI framework to get the extension version + + The default implementation uses the classes docstring to + set the extension description, and uses the classes + filter_flags attribute to set the ISAPI filter flags - you + must specify filter_flags in your class. + """ + if self.filter_flags is None: + raise RuntimeError("You must specify the filter flags") + # nod to our reload capability - fv is None when we are reloaded. + if fv is not None: + fv.Flags = self.filter_flags + fv.FilterDesc = self.__doc__ + + def HttpFilterProc(self, fc): + """Called by the ISAPI framework for each filter request. + + sub-classes must provide an implementation for this method. + """ + raise NotImplementedError("sub-classes should override HttpExtensionProc") + + def TerminateFilter(self, status): + """Called by the ISAPI framework as the filter terminates.""" + pass diff --git a/python_embeded/Lib/site-packages/isapi/threaded_extension.py b/python_embeded/Lib/site-packages/isapi/threaded_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7cc4d10e0e5e04c2540f75d69db1624b866c90 --- /dev/null +++ b/python_embeded/Lib/site-packages/isapi/threaded_extension.py @@ -0,0 +1,191 @@ +"""An ISAPI extension base class implemented using a thread-pool.""" + +# $Id$ + +import sys +import threading +import time +import traceback + +from pywintypes import OVERLAPPED +from win32event import INFINITE +from win32file import ( + CloseHandle, + CreateIoCompletionPort, + GetQueuedCompletionStatus, + PostQueuedCompletionStatus, +) +from win32security import SetThreadToken + +import isapi.simple +from isapi import ExtensionError, isapicon + +ISAPI_REQUEST = 1 +ISAPI_SHUTDOWN = 2 + + +class WorkerThread(threading.Thread): + def __init__(self, extension, io_req_port): + self.running = False + self.io_req_port = io_req_port + self.extension = extension + threading.Thread.__init__(self) + # We wait 15 seconds for a thread to terminate, but if it fails to, + # we don't want the process to hang at exit waiting for it... + self.setDaemon(True) + + def run(self): + self.running = True + while self.running: + errCode, bytes, key, overlapped = GetQueuedCompletionStatus( + self.io_req_port, INFINITE + ) + if key == ISAPI_SHUTDOWN and overlapped is None: + break + + # Let the parent extension handle the command. + dispatcher = self.extension.dispatch_map.get(key) + if dispatcher is None: + raise RuntimeError(f"Bad request '{key}'") + + dispatcher(errCode, bytes, key, overlapped) + + def call_handler(self, cblock): + self.extension.Dispatch(cblock) + + +# A generic thread-pool based extension, using IO Completion Ports. +# Sub-classes can override one method to implement a simple extension, or +# may leverage the CompletionPort to queue their own requests, and implement a +# fully asynch extension. +class ThreadPoolExtension(isapi.simple.SimpleExtension): + "Base class for an ISAPI extension based around a thread-pool" + + max_workers = 20 + worker_shutdown_wait = 15000 # 15 seconds for workers to quit... + + def __init__(self): + self.workers = [] + # extensible dispatch map, for sub-classes that need to post their + # own requests to the completion port. + # Each of these functions is called with the result of + # GetQueuedCompletionStatus for our port. + self.dispatch_map = { + ISAPI_REQUEST: self.DispatchConnection, + } + + def GetExtensionVersion(self, vi): + isapi.simple.SimpleExtension.GetExtensionVersion(self, vi) + # As per Q192800, the CompletionPort should be created with the number + # of processors, even if the number of worker threads is much larger. + # Passing 0 means the system picks the number. + self.io_req_port = CreateIoCompletionPort(-1, None, 0, 0) + # start up the workers + self.workers = [] + for i in range(self.max_workers): + worker = WorkerThread(self, self.io_req_port) + worker.start() + self.workers.append(worker) + + def HttpExtensionProc(self, control_block): + overlapped = OVERLAPPED() + overlapped.object = control_block + PostQueuedCompletionStatus(self.io_req_port, 0, ISAPI_REQUEST, overlapped) + return isapicon.HSE_STATUS_PENDING + + def TerminateExtension(self, status): + for worker in self.workers: + worker.running = False + for worker in self.workers: + PostQueuedCompletionStatus(self.io_req_port, 0, ISAPI_SHUTDOWN, None) + # wait for them to terminate - pity we aren't using 'native' threads + # as then we could do a smart wait - but now we need to poll.... + end_time = time.time() + self.worker_shutdown_wait / 1000 + alive = self.workers + while alive: + if time.time() > end_time: + # xxx - might be nice to log something here. + break + time.sleep(0.2) + alive = [w for w in alive if w.is_alive()] + self.dispatch_map = {} # break circles + CloseHandle(self.io_req_port) + + # This is the one operation the base class supports - a simple + # Connection request. We setup the thread-token, and dispatch to the + # sub-class's 'Dispatch' method. + def DispatchConnection(self, errCode, bytes, key, overlapped): + control_block = overlapped.object + # setup the correct user for this request + hRequestToken = control_block.GetImpersonationToken() + SetThreadToken(None, hRequestToken) + try: + try: + self.Dispatch(control_block) + except: + self.HandleDispatchError(control_block) + finally: + # reset the security context + SetThreadToken(None, None) + + def Dispatch(self, ecb): + """Overridden by the sub-class to handle connection requests. + + This class creates a thread-pool using a Windows completion port, + and dispatches requests via this port. Sub-classes can generally + implement each connection request using blocking reads and writes, and + the thread-pool will still provide decent response to the end user. + + The sub-class can set a max_workers attribute (default is 20). Note + that this generally does *not* mean 20 threads will all be concurrently + running, via the magic of Windows completion ports. + + There is no default implementation - sub-classes must implement this. + """ + raise NotImplementedError("sub-classes should override Dispatch") + + def HandleDispatchError(self, ecb): + """Handles errors in the Dispatch method. + + When a Dispatch method call fails, this method is called to handle + the exception. The default implementation formats the traceback + in the browser. + """ + ecb.HttpStatusCode = isapicon.HSE_STATUS_ERROR + # control_block.LogData = "we failed!" + exc_typ, exc_val, exc_tb = sys.exc_info() + limit = None + try: + try: + import html + + ecb.SendResponseHeaders( + "200 OK", "Content-type: text/html\r\n\r\n", False + ) + print(file=ecb) + print("

Traceback (most recent call last):

", file=ecb) + list = traceback.format_tb( + exc_tb, limit + ) + traceback.format_exception_only(exc_typ, exc_val) + bold = list.pop() + print( + "
{}{}
".format( + html.escape("".join(list)), + html.escape(bold), + ), + file=ecb, + ) + except ExtensionError: + # The client disconnected without reading the error body - + # it's probably not a real browser at the other end, ignore it. + pass + except: + print("FAILED to render the error message!") + traceback.print_exc() + print("ORIGINAL extension error:") + traceback.print_exception(exc_typ, exc_val, exc_tb) + finally: + # holding tracebacks in a local of a frame that may itself be + # part of a traceback used to be evil and cause leaks! + exc_tb = None + ecb.DoneWithSession() diff --git a/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/AUTHORS b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..7281acf41a9a829eeaadc1c1437eab62a763a4a8 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/AUTHORS @@ -0,0 +1,8 @@ +# This is the list of JAX's significant contributors. +# +# This does not necessarily list everyone who has contributed code, +# especially since many employees of one corporation may be contributing. +# To see the full list of contributors, see the revision history in +# source control. +Google LLC +NVIDIA Corporation \ No newline at end of file diff --git a/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/LICENSE b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/METADATA b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..874c9d9c95d088534b6e92fbede6b715f8d8b4f8 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/METADATA @@ -0,0 +1,344 @@ +Metadata-Version: 2.2 +Name: jax +Version: 0.6.2 +Summary: Differentiate, compile, and transform Numpy code. +Home-page: https://github.com/jax-ml/jax +Author: JAX team +Author-email: jax-dev@google.com +License: Apache-2.0 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS +Requires-Dist: jaxlib<=0.6.2,>=0.6.2 +Requires-Dist: ml_dtypes>=0.5.0 +Requires-Dist: numpy>=1.26 +Requires-Dist: opt_einsum +Requires-Dist: scipy>=1.12 +Provides-Extra: minimum-jaxlib +Requires-Dist: jaxlib==0.6.2; extra == "minimum-jaxlib" +Provides-Extra: cpu +Provides-Extra: ci +Requires-Dist: jaxlib==0.6.1; extra == "ci" +Provides-Extra: tpu +Requires-Dist: jaxlib<=0.6.2,>=0.6.2; extra == "tpu" +Requires-Dist: libtpu==0.0.17.*; extra == "tpu" +Requires-Dist: requests; extra == "tpu" +Provides-Extra: cuda +Requires-Dist: jaxlib<=0.6.2,>=0.6.2; extra == "cuda" +Requires-Dist: jax-cuda12-plugin[with-cuda]<=0.6.2,>=0.6.2; extra == "cuda" +Provides-Extra: cuda12 +Requires-Dist: jaxlib<=0.6.2,>=0.6.2; extra == "cuda12" +Requires-Dist: jax-cuda12-plugin[with-cuda]<=0.6.2,>=0.6.2; extra == "cuda12" +Provides-Extra: cuda12-local +Requires-Dist: jaxlib<=0.6.2,>=0.6.2; extra == "cuda12-local" +Requires-Dist: jax-cuda12-plugin<=0.6.2,>=0.6.2; extra == "cuda12-local" +Provides-Extra: rocm +Requires-Dist: jaxlib<=0.6.2,>=0.6.2; extra == "rocm" +Requires-Dist: jax-rocm60-plugin<=0.6.2,>=0.6.2; extra == "rocm" +Provides-Extra: k8s +Requires-Dist: kubernetes; extra == "k8s" +Provides-Extra: xprof +Requires-Dist: xprof; extra == "xprof" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +
+logo +
+ +# Transformable numerical computing at scale + +[![Continuous integration](https://github.com/jax-ml/jax/actions/workflows/ci-build.yaml/badge.svg)](https://github.com/jax-ml/jax/actions/workflows/ci-build.yaml) +[![PyPI version](https://img.shields.io/pypi/v/jax)](https://pypi.org/project/jax/) + +[**Transformations**](#transformations) +| [**Scaling**](#scaling) +| [**Install guide**](#installation) +| [**Change logs**](https://docs.jax.dev/en/latest/changelog.html) +| [**Reference docs**](https://docs.jax.dev/en/latest/) + + +## What is JAX? + +JAX is a Python library for accelerator-oriented array computation and program transformation, +designed for high-performance numerical computing and large-scale machine learning. + +JAX can automatically differentiate native +Python and NumPy functions. It can differentiate through loops, branches, +recursion, and closures, and it can take derivatives of derivatives of +derivatives. It supports reverse-mode differentiation (a.k.a. backpropagation) +via [`jax.grad`](#automatic-differentiation-with-grad) as well as forward-mode differentiation, +and the two can be composed arbitrarily to any order. + +JAX uses [XLA](https://www.tensorflow.org/xla) +to compile and scale your NumPy programs on TPUs, GPUs, and other hardware accelerators. +You can compile your own pure functions with [`jax.jit`](#compilation-with-jit). +Compilation and automatic differentiation can be composed arbitrarily. + +Dig a little deeper, and you'll see that JAX is really an extensible system for +[composable function transformations](#transformations) at [scale](#scaling). + +This is a research project, not an official Google product. Expect +[sharp edges](https://docs.jax.dev/en/latest/notebooks/Common_Gotchas_in_JAX.html). +Please help by trying it out, [reporting bugs](https://github.com/jax-ml/jax/issues), +and letting us know what you think! + +```python +import jax +import jax.numpy as jnp + +def predict(params, inputs): + for W, b in params: + outputs = jnp.dot(inputs, W) + b + inputs = jnp.tanh(outputs) # inputs to the next layer + return outputs # no activation on last layer + +def loss(params, inputs, targets): + preds = predict(params, inputs) + return jnp.sum((preds - targets)**2) + +grad_loss = jax.jit(jax.grad(loss)) # compiled gradient evaluation function +perex_grads = jax.jit(jax.vmap(grad_loss, in_axes=(None, 0, 0))) # fast per-example grads +``` + +### Contents +* [Transformations](#transformations) +* [Scaling](#scaling) +* [Current gotchas](#gotchas-and-sharp-bits) +* [Installation](#installation) +* [Neural net libraries](#neural-network-libraries) +* [Citing JAX](#citing-jax) +* [Reference documentation](#reference-documentation) + +## Transformations + +At its core, JAX is an extensible system for transforming numerical functions. +Here are three: `jax.grad`, `jax.jit`, and `jax.vmap`. + +### Automatic differentiation with `grad` + +Use [`jax.grad`](https://docs.jax.dev/en/latest/jax.html#jax.grad) +to efficiently compute reverse-mode gradients: + +```python +import jax +import jax.numpy as jnp + +def tanh(x): + y = jnp.exp(-2.0 * x) + return (1.0 - y) / (1.0 + y) + +grad_tanh = jax.grad(tanh) +print(grad_tanh(1.0)) +# prints 0.4199743 +``` + +You can differentiate to any order with `grad`: + +```python +print(jax.grad(jax.grad(jax.grad(tanh)))(1.0)) +# prints 0.62162673 +``` + +You're free to use differentiation with Python control flow: + +```python +def abs_val(x): + if x > 0: + return x + else: + return -x + +abs_val_grad = jax.grad(abs_val) +print(abs_val_grad(1.0)) # prints 1.0 +print(abs_val_grad(-1.0)) # prints -1.0 (abs_val is re-evaluated) +``` + +See the [JAX Autodiff +Cookbook](https://docs.jax.dev/en/latest/notebooks/autodiff_cookbook.html) +and the [reference docs on automatic +differentiation](https://docs.jax.dev/en/latest/jax.html#automatic-differentiation) +for more. + +### Compilation with `jit` + +Use XLA to compile your functions end-to-end with +[`jit`](https://docs.jax.dev/en/latest/jax.html#just-in-time-compilation-jit), +used either as an `@jit` decorator or as a higher-order function. + +```python +import jax +import jax.numpy as jnp + +def slow_f(x): + # Element-wise ops see a large benefit from fusion + return x * x + x * 2.0 + +x = jnp.ones((5000, 5000)) +fast_f = jax.jit(slow_f) +%timeit -n10 -r3 fast_f(x) +%timeit -n10 -r3 slow_f(x) +``` + +Using `jax.jit` constrains the kind of Python control flow +the function can use; see +the tutorial on [Control Flow and Logical Operators with JIT](https://docs.jax.dev/en/latest/control-flow.html) +for more. + +### Auto-vectorization with `vmap` + +[`vmap`](https://docs.jax.dev/en/latest/jax.html#vectorization-vmap) maps +a function along array axes. +But instead of just looping over function applications, it pushes the loop down +onto the function’s primitive operations, e.g. turning matrix-vector multiplies into +matrix-matrix multiplies for better performance. + +Using `vmap` can save you from having to carry around batch dimensions in your +code: + +```python +import jax +import jax.numpy as jnp + +def l1_distance(x, y): + assert x.ndim == y.ndim == 1 # only works on 1D inputs + return jnp.sum(jnp.abs(x - y)) + +def pairwise_distances(dist1D, xs): + return jax.vmap(jax.vmap(dist1D, (0, None)), (None, 0))(xs, xs) + +xs = jax.random.normal(jax.random.key(0), (100, 3)) +dists = pairwise_distances(l1_distance, xs) +dists.shape # (100, 100) +``` + +By composing `jax.vmap` with `jax.grad` and `jax.jit`, we can get efficient +Jacobian matrices, or per-example gradients: + +```python +per_example_grads = jax.jit(jax.vmap(jax.grad(loss), in_axes=(None, 0, 0))) +``` + +## Scaling + +To scale your computations across thousands of devices, you can use any +composition of these: +* [**Compiler-based automatic parallelization**](https://docs.jax.dev/en/latest/notebooks/Distributed_arrays_and_automatic_parallelization.html) +where you program as if using a single global machine, and the compiler chooses +how to shard data and partition computation (with some user-provided constraints); +* [**Explicit sharding and automatic partitioning**](https://docs.jax.dev/en/latest/notebooks/explicit-sharding.html) +where you still have a global view but data shardings are +explicit in JAX types, inspectable using `jax.typeof`; +* [**Manual per-device programming**](https://docs.jax.dev/en/latest/notebooks/shard_map.html) +where you have a per-device view of data +and computation, and can communicate with explicit collectives. + +| Mode | View? | Explicit sharding? | Explicit Collectives? | +|---|---|---|---| +| Auto | Global | ❌ | ❌ | +| Explicit | Global | ✅ | ❌ | +| Manual | Per-device | ✅ | ✅ | + +```python +from jax.sharding import set_mesh, AxisType, PartitionSpec as P +mesh = jax.make_mesh((8,), ('data',), axis_types=(AxisType.Explicit,)) +set_mesh(mesh) + +# parameters are sharded for FSDP: +for W, b in params: + print(f'{jax.typeof(W)}') # f32[512@data,512] + print(f'{jax.typeof(b)}') # f32[512] + +# shard data for batch parallelism: +inputs, targets = jax.device_put((inputs, targets), P('data')) + +# evaluate gradients, automatically parallelized! +gradfun = jax.jit(jax.grad(loss)) +param_grads = gradfun(params, (inputs, targets)) +``` + +See the [tutorial](https://docs.jax.dev/en/latest/sharded-computation.html) and +[advanced guides](https://docs.jax.dev/en/latest/advanced_guide.html) for more. + +## Gotchas and sharp bits + +See the [Gotchas +Notebook](https://docs.jax.dev/en/latest/notebooks/Common_Gotchas_in_JAX.html). + +## Installation + +### Supported platforms + +| | Linux x86_64 | Linux aarch64 | Mac aarch64 | Windows x86_64 | Windows WSL2 x86_64 | +|------------|--------------|---------------|--------------|----------------|---------------------| +| CPU | yes | yes | yes | yes | yes | +| NVIDIA GPU | yes | yes | n/a | no | experimental | +| Google TPU | yes | n/a | n/a | n/a | n/a | +| AMD GPU | yes | no | n/a | no | no | +| Apple GPU | n/a | no | experimental | n/a | n/a | +| Intel GPU | experimental | n/a | n/a | no | no | + + +### Instructions + +| Platform | Instructions | +|-----------------|-----------------------------------------------------------------------------------------------------------------| +| CPU | `pip install -U jax` | +| NVIDIA GPU | `pip install -U "jax[cuda12]"` | +| Google TPU | `pip install -U "jax[tpu]"` | +| AMD GPU (Linux) | Follow [AMD's instructions](https://github.com/jax-ml/jax/blob/main/build/rocm/README.md). | +| Mac GPU | Follow [Apple's instructions](https://developer.apple.com/metal/jax/). | +| Intel GPU | Follow [Intel's instructions](https://github.com/intel/intel-extension-for-openxla/blob/main/docs/acc_jax.md). | + +See [the documentation](https://docs.jax.dev/en/latest/installation.html) +for information on alternative installation strategies. These include compiling +from source, installing with Docker, using other versions of CUDA, a +community-supported conda build, and answers to some frequently-asked questions. + +## Citing JAX + +To cite this repository: + +``` +@software{jax2018github, + author = {James Bradbury and Roy Frostig and Peter Hawkins and Matthew James Johnson and Chris Leary and Dougal Maclaurin and George Necula and Adam Paszke and Jake Vander{P}las and Skye Wanderman-{M}ilne and Qiao Zhang}, + title = {{JAX}: composable transformations of {P}ython+{N}um{P}y programs}, + url = {http://github.com/jax-ml/jax}, + version = {0.3.13}, + year = {2018}, +} +``` + +In the above bibtex entry, names are in alphabetical order, the version number +is intended to be that from [jax/version.py](../main/jax/version.py), and +the year corresponds to the project's open-source release. + +A nascent version of JAX, supporting only automatic differentiation and +compilation to XLA, was described in a [paper that appeared at SysML +2018](https://mlsys.org/Conferences/2019/doc/2018/146.pdf). We're currently working on +covering JAX's ideas and capabilities in a more comprehensive and up-to-date +paper. + +## Reference documentation + +For details about the JAX API, see the +[reference documentation](https://docs.jax.dev/). + +For getting started as a JAX developer, see the +[developer documentation](https://docs.jax.dev/en/latest/developer.html). diff --git a/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/RECORD b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e3194d685fbdee6a4e2d51654018de287032c623 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/RECORD @@ -0,0 +1,1135 @@ +jax-0.6.2.dist-info/AUTHORS,sha256=OOBQygrI1Zc94AYJycH1r_BSCwP38Hyv3sludltJ7hY,313 +jax-0.6.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jax-0.6.2.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +jax-0.6.2.dist-info/METADATA,sha256=tXu99kxksiCOsT9r2djs6BW2zbvyYhU_BZbidhpJHx0,13123 +jax-0.6.2.dist-info/RECORD,, +jax-0.6.2.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91 +jax-0.6.2.dist-info/top_level.txt,sha256=DabAh8MXQ-HM0EtjKD-Wx_D6tTIW-_de73pdG_f_KTE,4 +jax/__init__.py,sha256=LD82Acv1D4o9YeBUcnz7unFDFzjLRVkDToNoifV2bvQ,9291 +jax/__pycache__/__init__.cpython-312.pyc,, +jax/__pycache__/ad_checkpoint.cpython-312.pyc,, +jax/__pycache__/api_util.cpython-312.pyc,, +jax/__pycache__/cloud_tpu_init.cpython-312.pyc,, +jax/__pycache__/collect_profile.cpython-312.pyc,, +jax/__pycache__/core.cpython-312.pyc,, +jax/__pycache__/custom_batching.cpython-312.pyc,, +jax/__pycache__/custom_derivatives.cpython-312.pyc,, +jax/__pycache__/custom_transpose.cpython-312.pyc,, +jax/__pycache__/debug.cpython-312.pyc,, +jax/__pycache__/distributed.cpython-312.pyc,, +jax/__pycache__/dlpack.cpython-312.pyc,, +jax/__pycache__/dtypes.cpython-312.pyc,, +jax/__pycache__/errors.cpython-312.pyc,, +jax/__pycache__/export.cpython-312.pyc,, +jax/__pycache__/ffi.cpython-312.pyc,, +jax/__pycache__/flatten_util.cpython-312.pyc,, +jax/__pycache__/monitoring.cpython-312.pyc,, +jax/__pycache__/profiler.cpython-312.pyc,, +jax/__pycache__/random.cpython-312.pyc,, +jax/__pycache__/sharding.cpython-312.pyc,, +jax/__pycache__/stages.cpython-312.pyc,, +jax/__pycache__/test_util.cpython-312.pyc,, +jax/__pycache__/tree.cpython-312.pyc,, +jax/__pycache__/tree_util.cpython-312.pyc,, +jax/__pycache__/typing.cpython-312.pyc,, +jax/__pycache__/util.cpython-312.pyc,, +jax/__pycache__/version.cpython-312.pyc,, +jax/_src/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/__pycache__/__init__.cpython-312.pyc,, +jax/_src/__pycache__/abstract_arrays.cpython-312.pyc,, +jax/_src/__pycache__/ad_checkpoint.cpython-312.pyc,, +jax/_src/__pycache__/ad_util.cpython-312.pyc,, +jax/_src/__pycache__/api.cpython-312.pyc,, +jax/_src/__pycache__/api_util.cpython-312.pyc,, +jax/_src/__pycache__/array.cpython-312.pyc,, +jax/_src/__pycache__/attrs.cpython-312.pyc,, +jax/_src/__pycache__/basearray.cpython-312.pyc,, +jax/_src/__pycache__/blocked_sampler.cpython-312.pyc,, +jax/_src/__pycache__/buffer_callback.cpython-312.pyc,, +jax/_src/__pycache__/cache_key.cpython-312.pyc,, +jax/_src/__pycache__/callback.cpython-312.pyc,, +jax/_src/__pycache__/checkify.cpython-312.pyc,, +jax/_src/__pycache__/cloud_tpu_init.cpython-312.pyc,, +jax/_src/__pycache__/compilation_cache.cpython-312.pyc,, +jax/_src/__pycache__/compilation_cache_interface.cpython-312.pyc,, +jax/_src/__pycache__/compiler.cpython-312.pyc,, +jax/_src/__pycache__/compute_on.cpython-312.pyc,, +jax/_src/__pycache__/config.cpython-312.pyc,, +jax/_src/__pycache__/core.cpython-312.pyc,, +jax/_src/__pycache__/custom_api_util.cpython-312.pyc,, +jax/_src/__pycache__/custom_batching.cpython-312.pyc,, +jax/_src/__pycache__/custom_dce.cpython-312.pyc,, +jax/_src/__pycache__/custom_derivatives.cpython-312.pyc,, +jax/_src/__pycache__/custom_partitioning.cpython-312.pyc,, +jax/_src/__pycache__/custom_partitioning_sharding_rule.cpython-312.pyc,, +jax/_src/__pycache__/custom_transpose.cpython-312.pyc,, +jax/_src/__pycache__/debugging.cpython-312.pyc,, +jax/_src/__pycache__/deprecations.cpython-312.pyc,, +jax/_src/__pycache__/dispatch.cpython-312.pyc,, +jax/_src/__pycache__/distributed.cpython-312.pyc,, +jax/_src/__pycache__/dlpack.cpython-312.pyc,, +jax/_src/__pycache__/dtypes.cpython-312.pyc,, +jax/_src/__pycache__/earray.cpython-312.pyc,, +jax/_src/__pycache__/effects.cpython-312.pyc,, +jax/_src/__pycache__/environment_info.cpython-312.pyc,, +jax/_src/__pycache__/error_check.cpython-312.pyc,, +jax/_src/__pycache__/errors.cpython-312.pyc,, +jax/_src/__pycache__/ffi.cpython-312.pyc,, +jax/_src/__pycache__/flatten_util.cpython-312.pyc,, +jax/_src/__pycache__/frozen_dict.cpython-312.pyc,, +jax/_src/__pycache__/hardware_utils.cpython-312.pyc,, +jax/_src/__pycache__/hashable_array.cpython-312.pyc,, +jax/_src/__pycache__/jaxpr_util.cpython-312.pyc,, +jax/_src/__pycache__/lax_reference.cpython-312.pyc,, +jax/_src/__pycache__/layout.cpython-312.pyc,, +jax/_src/__pycache__/lazy_loader.cpython-312.pyc,, +jax/_src/__pycache__/linear_util.cpython-312.pyc,, +jax/_src/__pycache__/logging_config.cpython-312.pyc,, +jax/_src/__pycache__/lru_cache.cpython-312.pyc,, +jax/_src/__pycache__/mesh.cpython-312.pyc,, +jax/_src/__pycache__/mesh_utils.cpython-312.pyc,, +jax/_src/__pycache__/monitoring.cpython-312.pyc,, +jax/_src/__pycache__/named_sharding.cpython-312.pyc,, +jax/_src/__pycache__/op_shardings.cpython-312.pyc,, +jax/_src/__pycache__/partition_spec.cpython-312.pyc,, +jax/_src/__pycache__/path.cpython-312.pyc,, +jax/_src/__pycache__/pickle_util.cpython-312.pyc,, +jax/_src/__pycache__/pjit.cpython-312.pyc,, +jax/_src/__pycache__/pretty_printer.cpython-312.pyc,, +jax/_src/__pycache__/prng.cpython-312.pyc,, +jax/_src/__pycache__/profiler.cpython-312.pyc,, +jax/_src/__pycache__/public_test_util.cpython-312.pyc,, +jax/_src/__pycache__/random.cpython-312.pyc,, +jax/_src/__pycache__/shard_alike.cpython-312.pyc,, +jax/_src/__pycache__/shard_map.cpython-312.pyc,, +jax/_src/__pycache__/sharding.cpython-312.pyc,, +jax/_src/__pycache__/sharding_impls.cpython-312.pyc,, +jax/_src/__pycache__/sharding_specs.cpython-312.pyc,, +jax/_src/__pycache__/source_info_util.cpython-312.pyc,, +jax/_src/__pycache__/sourcemap.cpython-312.pyc,, +jax/_src/__pycache__/stages.cpython-312.pyc,, +jax/_src/__pycache__/test_loader.cpython-312.pyc,, +jax/_src/__pycache__/test_multiprocess.cpython-312.pyc,, +jax/_src/__pycache__/test_util.cpython-312.pyc,, +jax/_src/__pycache__/test_warning_util.cpython-312.pyc,, +jax/_src/__pycache__/tpu_custom_call.cpython-312.pyc,, +jax/_src/__pycache__/traceback_util.cpython-312.pyc,, +jax/_src/__pycache__/tree.cpython-312.pyc,, +jax/_src/__pycache__/tree_util.cpython-312.pyc,, +jax/_src/__pycache__/typing.cpython-312.pyc,, +jax/_src/__pycache__/util.cpython-312.pyc,, +jax/_src/__pycache__/xla_bridge.cpython-312.pyc,, +jax/_src/__pycache__/xla_metadata.cpython-312.pyc,, +jax/_src/abstract_arrays.py,sha256=1kxQA1qnwmri9_GeZHerQmghGZ-zHOy-etSyGHIhTIE,2889 +jax/_src/ad_checkpoint.py,sha256=yRK5mpBVlDjivqmVgBp_sfVP8KfFvm-u0Bg5N0n01Hw,37058 +jax/_src/ad_util.py,sha256=i1Oj_yGWZXcPb33GVukSYkLskVN3L4Kt0AUZ2F-i8wc,4446 +jax/_src/api.py,sha256=QSSywLTQv0pN_RyNZGkECdyHrQ0ImuWAB4uRdZJDnU0,138017 +jax/_src/api_util.py,sha256=j8VmM3_7ggUf6dPJYP2gATAQi3dWk0ks01XJLpwWCHE,30733 +jax/_src/array.py,sha256=jTqMr6kPZvd3uFpF01U4c-4jUYHSZbIqMKjCtj_cAc8,49562 +jax/_src/attrs.py,sha256=guRVvHWjaiyCauxtHOJY3gjIHrp4ts6U5JinaBpCYbo,15498 +jax/_src/basearray.py,sha256=FQOcRwUhh1w4byHijEzCZAVqa8Tukr3bSr4fEqZz1q4,6904 +jax/_src/basearray.pyi,sha256=2AAKVkmJ6c4fLr2N-SA0AiLNUuCKqOmO_XMRf6jsuJI,13467 +jax/_src/blocked_sampler.py,sha256=OtV8uaYBfdGsWOpYD6LG9JPK1yknKkrJuLPAJ_LJPeM,5915 +jax/_src/buffer_callback.py,sha256=1qpEUw7Lku1JrNIU-vKW36oYO47aPkAxmJPyt7YmJog,10533 +jax/_src/cache_key.py,sha256=Yon7NspNxWKIm0yBJso5j6I4Z6mnKFLmAIg_g0rc228,12923 +jax/_src/callback.py,sha256=cRLRf6LqKtnXIYZ3WONrZrzf0c6ZtFCvxWvAu44vXss,33140 +jax/_src/checkify.py,sha256=hZHK1ixcQroaaKq9By7QhMn5NWVENscCNe8pVsepu48,57782 +jax/_src/cloud_tpu_init.py,sha256=Ks9-0g8s45dOGPs3cHVa7Ddjy-Kqlbag9JAFBWyPlr0,4875 +jax/_src/clusters/__init__.py,sha256=blIgNT92mYE9Bst7obP5_xhZ2fE2hKqwxH6R0cAQZ94,1283 +jax/_src/clusters/__pycache__/__init__.cpython-312.pyc,, +jax/_src/clusters/__pycache__/cloud_tpu_cluster.cpython-312.pyc,, +jax/_src/clusters/__pycache__/cluster.cpython-312.pyc,, +jax/_src/clusters/__pycache__/k8s_cluster.cpython-312.pyc,, +jax/_src/clusters/__pycache__/mpi4py_cluster.cpython-312.pyc,, +jax/_src/clusters/__pycache__/ompi_cluster.cpython-312.pyc,, +jax/_src/clusters/__pycache__/slurm_cluster.cpython-312.pyc,, +jax/_src/clusters/cloud_tpu_cluster.py,sha256=SuB7FuOWChVC2dpLeKmNOYYpd49Ke1c0UgLoMJe4c3E,8522 +jax/_src/clusters/cluster.py,sha256=raW-A1TKgHDyqZeMfv3lgdm4ImDHxrzoMnFAOfgiK4M,5858 +jax/_src/clusters/k8s_cluster.py,sha256=uo4QCCwpqixEB3Mo_28fPmPpCkze-fQb1PK8I_WIGy4,9279 +jax/_src/clusters/mpi4py_cluster.py,sha256=ugDhirp00Hh3knxX3qVb5yxSz1d0_O1DuQUcVfyO8rg,2608 +jax/_src/clusters/ompi_cluster.py,sha256=Vfk3AimGa2jtDEwjpJJXuYP9p5uv1tBwEKtpGn1f4IQ,2317 +jax/_src/clusters/slurm_cluster.py,sha256=hsZQJXznkCXGDTfKgMDgjVf4bmbAtSne6pa0wW4iJT0,2321 +jax/_src/compilation_cache.py,sha256=WfrNBOZSpIyxrKFIzdgq7pkzekYy_Nxa_eFY6CttL5w,12006 +jax/_src/compilation_cache_interface.py,sha256=ONHvsIC3Kzoda0TcQWnhhjxtOWYixjkO9Or__BAW3_0,865 +jax/_src/compiler.py,sha256=yvNFzMoaJgd7chPd0kaQmQ4Dwkaq694nB8QGjr_huXY,33211 +jax/_src/compute_on.py,sha256=0b74TSV1R31kJTR53thafdtB0sYiFGqmRoAbZwAFcps,1911 +jax/_src/config.py,sha256=TrdCH1B_WTUeYqbfVEFQN_zwyra_C9-qdvuFmKz23YU,70329 +jax/_src/core.py,sha256=TM_E3VA3EmmnX76_eoN3bSwyQaCxddP_Q0NVyJ565g4,128945 +jax/_src/cudnn/__init__.py,sha256=03MR0G6UMqHXi-JBeyj6tipV6ioP9a-iSN1mW-8Ws5A,631 +jax/_src/cudnn/__pycache__/__init__.cpython-312.pyc,, +jax/_src/cudnn/__pycache__/fused_attention_stablehlo.cpython-312.pyc,, +jax/_src/cudnn/__pycache__/fusion.cpython-312.pyc,, +jax/_src/cudnn/__pycache__/scaled_matmul_stablehlo.cpython-312.pyc,, +jax/_src/cudnn/fused_attention_stablehlo.py,sha256=83_OlPbZ2vX57Ut2tMcPplbSESDxNtlbG48Kf222ezs,78802 +jax/_src/cudnn/fusion.py,sha256=KO7fo_thf5-sy1i_9HUrbTpt5cyOlS6zbu6k2RPonk8,2809 +jax/_src/cudnn/scaled_matmul_stablehlo.py,sha256=AKIxjX6NvXFp4YPQhenBjUTDpt0L5IbYBYdqW3xICTs,23901 +jax/_src/custom_api_util.py,sha256=uv6uyrXU1BHGzKuAe498W2PD9bcWt1PEa-8UAqr9Zaw,876 +jax/_src/custom_batching.py,sha256=pulnaqQfqfGA9YnwGvzyaZEhSJC8ktYZZmlyKAqshyc,15240 +jax/_src/custom_dce.py,sha256=cz9n_6n8JuKtur3a_EryePp6bN9aJqf8wrRN0QlTs70,17478 +jax/_src/custom_derivatives.py,sha256=thae08fHF2oRoeOxr_CbYOXve9PQ2D0edUk_bQbMFcA,79950 +jax/_src/custom_partitioning.py,sha256=Q8HTkO6QjECgc_RSpp75x4nRieCBqWm3BYX47wXJgn4,26170 +jax/_src/custom_partitioning_sharding_rule.py,sha256=qijmSIw4pKpyqyTb_mzTMYCnDHV3eMb-yzixrLUi7XY,18026 +jax/_src/custom_transpose.py,sha256=UpDGexoY0QOuwJvQS5Sk3ZCJQET1CnQKCJba8XlZ5qI,9195 +jax/_src/debugger/__init__.py,sha256=iZU1X5nkpSBK5pwLSuWhZsPZgtLUovBF3tyWPmQoh1Q,899 +jax/_src/debugger/__pycache__/__init__.cpython-312.pyc,, +jax/_src/debugger/__pycache__/cli_debugger.cpython-312.pyc,, +jax/_src/debugger/__pycache__/colab_debugger.cpython-312.pyc,, +jax/_src/debugger/__pycache__/colab_lib.cpython-312.pyc,, +jax/_src/debugger/__pycache__/core.cpython-312.pyc,, +jax/_src/debugger/__pycache__/web_debugger.cpython-312.pyc,, +jax/_src/debugger/cli_debugger.py,sha256=bzn-5Rd4C9WwGsVret8gbFNaLpXAf0SzvgltXNuZrcU,4778 +jax/_src/debugger/colab_debugger.py,sha256=PHmiL-QES4t97iICJt34a5FXSNTm-AaSUERPGCZ3QHA,7823 +jax/_src/debugger/colab_lib.py,sha256=jCbwj2Q4f8SEo7CBr6AeiUtzlsIv4BfKa5CVbq4Bn2U,4298 +jax/_src/debugger/core.py,sha256=WilcRMqpzssKa5YL_P7SFtKaUVUaXqDutxO_N-ZRnp0,8593 +jax/_src/debugger/web_debugger.py,sha256=Or-gJL40oBUfClu8mg1YUBoKA9cQytZgJAeGGrPPK_w,3433 +jax/_src/debugging.py,sha256=qgEF63pSywSBU_fbpgHl9PR4V3E8MwncCopY7T5ibJ0,28819 +jax/_src/deprecations.py,sha256=vBQeRe1h_4Okm3lJV5Xpu5yFSb9Z-nLX8Ieh5c7Yypg,4795 +jax/_src/dispatch.py,sha256=k27zGW7WZBaFWUXjxOKLT7ach2BxmpgaMhM6L4abA4M,26907 +jax/_src/distributed.py,sha256=8rAhhjxfe-1G4ZW0oKEqkt2RZYS2o1RaqUZeV4Q9c0E,13693 +jax/_src/dlpack.py,sha256=S8bG2Xjgxq_xrbE4GLnhi2DIoYZtBymRPiU5_qr1yl0,11411 +jax/_src/dtypes.py,sha256=yCM5YOoFke7jkSLF9JwK5qWAwt9YxpIThF-nQW7RnYw,35725 +jax/_src/earray.py,sha256=6KsYjNLzWaT1S0IKDwmZMAsa94E8yg9TU2Yb3-2QN70,4412 +jax/_src/effects.py,sha256=Jg3hDB313Vl1CN_khELWMI1mE2kJ8MzLXRHf2b31ArM,4736 +jax/_src/environment_info.py,sha256=IoRky2nPXfdS_VPKvpPhzW0mTShyfUJiAl6SBleErh4,1986 +jax/_src/error_check.py,sha256=X-FFObANtgQB_hZqKrjVCDvJ1hjZZDgSuT9fThPXtwQ,12727 +jax/_src/errors.py,sha256=Vp2gp5kQxtoss9aby-vpGwO5wBxRndvddVD_3-UWyZ4,24710 +jax/_src/export/__init__.py,sha256=mS3YSYUZFIG68T5Zo9CFGkT7wCyWRycnWV4L36CnHYU,581 +jax/_src/export/__pycache__/__init__.cpython-312.pyc,, +jax/_src/export/__pycache__/_export.cpython-312.pyc,, +jax/_src/export/__pycache__/serialization.cpython-312.pyc,, +jax/_src/export/__pycache__/serialization_generated.cpython-312.pyc,, +jax/_src/export/__pycache__/shape_poly.cpython-312.pyc,, +jax/_src/export/__pycache__/shape_poly_decision.cpython-312.pyc,, +jax/_src/export/_export.py,sha256=VR8o8Xg380sJOHS4vUmK96ZMNyDDTJ4vFGgcyeGgsyU,69828 +jax/_src/export/serialization.py,sha256=0fYNO50OjU8TWRC1_wHJm_z1pFbLnaGQai3Tif5KluU,19466 +jax/_src/export/serialization_generated.py,sha256=pCU6x5XxV-2IUyRkA036MrhMY1RvbKWdefXwOySy7Cw,27869 +jax/_src/export/shape_poly.py,sha256=4NpQwchghuErOJLwFDU6jXlN1oL-7fLSxDOpsrghD7I,85943 +jax/_src/export/shape_poly_decision.py,sha256=x24hHa1CGTskS83TMeo7xGILKsrgufYsGReiKLQAJtc,20476 +jax/_src/extend/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/_src/extend/__pycache__/__init__.cpython-312.pyc,, +jax/_src/extend/__pycache__/random.cpython-312.pyc,, +jax/_src/extend/random.py,sha256=1KmQCCYxFMJO8KB0qJz9ZVQhnK-05Sv4Jn0jXLPpWQw,1258 +jax/_src/ffi.py,sha256=m7JbkKFe3yCv6onjv-NwfyofRWkouw1klxk1em2ERVM,28810 +jax/_src/flatten_util.py,sha256=WSVHRWlDiJm4gdnEIK3csN9aOxLuvWdLe8HXJfuQPMA,3550 +jax/_src/frozen_dict.py,sha256=22m-h6SepCRV95hyPZpKfGyQigoE3lG7HHvum77Eu0E,1342 +jax/_src/hardware_utils.py,sha256=0-8OyFvMYu5l-C0e3VObpQMkLGg-BBtzP56CAdFEIxE,2295 +jax/_src/hashable_array.py,sha256=4ff9eVDYR7DFK3l9nNF0btGecguXonn1AzeWviiJQcQ,1036 +jax/_src/image/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/image/__pycache__/__init__.cpython-312.pyc,, +jax/_src/image/__pycache__/scale.cpython-312.pyc,, +jax/_src/image/scale.py,sha256=XL1VSkCM4gtOOFurIElk8nXPfUB802nw3P8wlqquP4Q,13774 +jax/_src/internal_test_util/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/internal_test_util/__pycache__/__init__.cpython-312.pyc,, +jax/_src/internal_test_util/__pycache__/deprecation_module.cpython-312.pyc,, +jax/_src/internal_test_util/__pycache__/export_back_compat_test_util.cpython-312.pyc,, +jax/_src/internal_test_util/__pycache__/lax_test_util.cpython-312.pyc,, +jax/_src/internal_test_util/__pycache__/test_harnesses.cpython-312.pyc,, +jax/_src/internal_test_util/deprecation_module.py,sha256=iZ6fRYNaUcOwrftwpDXMnlxrLrrQbdMrbybmmQFwql4,851 +jax/_src/internal_test_util/export_back_compat_test_data/__init__.py,sha256=gEMCMS8LKTvoFm0t7khiAnQg78EDUuMI-fvTvw250eo,682 +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/__init__.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/annotate_data_placement.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_cholesky_lapack_potrf.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_eig_lapack_geev.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_eigh_lapack_syev.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_hessenberg_lapack_gehrd.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_lu_lapack_getrf.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_qr_lapack_geqrf.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_schur_lapack_gees.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_svd_lapack_gesdd.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_triangular_solve_blas_trsm.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_tridiagonal_lapack_sytrd_hetrd.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cpu_tridiagonal_solve_lapack_gtsv.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_eigh_cusolver_syev.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_lu_cusolver_getrf.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_lu_pivots_to_permutation.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_qr_cusolver_geqrf.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_svd_cusolver_gesvd.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_threefry2x32.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_tridiagonal_cusolver_sytrd.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/cuda_tridiagonal_solve.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/rocm_eigh_hipsolver_syev.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/shardy_sharding_ops_with_different_meshes.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/stablehlo_dynamic_approx_top_k.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/stablehlo_dynamic_rng_bit_generator.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/stablehlo_dynamic_top_k.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/tpu_ApproxTopK.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/tpu_Eigh.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/tpu_Lu.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/tpu_Qr.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/tpu_Sharding.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/__pycache__/tpu_stablehlo_dynamic_reduce_window.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/annotate_data_placement.py,sha256=PZiDa_599R0BfRekXxtgYygrfGXKWEsTHrzb73Yr5is,14496 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_cholesky_lapack_potrf.py,sha256=h78iCf_nVYFnPTpAJByDclfoQMJv9GBxQrBd1slnq9o,45926 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_eig_lapack_geev.py,sha256=zIJnIA_e3r4-xrpYTQMtscVEjnCypDuJVBWeSMRT1ms,35773 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_eigh_lapack_syev.py,sha256=WvhpYwzpKTxHsx4TBJjlYm9XXlT_u6w1DyYh8OzcpQ4,58702 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_hessenberg_lapack_gehrd.py,sha256=Sav1CtBDRZ4SPzvbxS9LdXShoGBVgUmvyOb4dg8p15I,37237 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_lu_lapack_getrf.py,sha256=2G9cFdWm6Ppz-p0v5XSW-XvBgtA1o42ajE_ysyW3wro,80469 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_qr_lapack_geqrf.py,sha256=ht61muzEXcrW-835kxdIhwPiK60AfY2ZisgzE0WOjLk,28549 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_schur_lapack_gees.py,sha256=-yBUW2hATIqD6Q4fRyOyu1yFjYOVTfHkupyeKAyn_i4,25011 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_svd_lapack_gesdd.py,sha256=pbGLtB8oUnS1yUVLHfCURVySu2I0ozAJaXOw3bPWWK8,44237 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_triangular_solve_blas_trsm.py,sha256=2jc16YKe1KNaQ68KsJbRtB1M1hpqdvvMcHOfN6PmKLA,19047 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_tridiagonal_lapack_sytrd_hetrd.py,sha256=4tpXxuEDCrDK5SHtZ8Z-gFGJFHtAew6TJ6Wfa5tyPk0,58836 +jax/_src/internal_test_util/export_back_compat_test_data/cpu_tridiagonal_solve_lapack_gtsv.py,sha256=o8jisAqvk02Uyd9ExxujqvEELIwHHm7ngtvwqmWtXRs,31747 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_eigh_cusolver_syev.py,sha256=Ggvl-nVWZvHLVbQXhoJGyijq4MHw0lu9GfvnBM-BklA,43004 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_lu_cusolver_getrf.py,sha256=BKwHumIdGqT2yADKuI6MmaC9Lzyr5R1T1UUgJlq6CIY,28679 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_lu_pivots_to_permutation.py,sha256=9VBfh6UuV5OPxxHkRrSnUBHNm0XSElBtoqncKlwUCf0,4136 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_qr_cusolver_geqrf.py,sha256=eLLv7JISa9c1h2FSbxLJEb5mVLf90QaXW1c93spk5SU,31545 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_svd_cusolver_gesvd.py,sha256=R97n-YBNb8jGCGRkPkzoLe96Sk0OmyM7ykPpcq4_tpk,80009 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_threefry2x32.py,sha256=1XTgzOBzbiaxi_MeAKtww5FpZ8DgoQ4lZ58w_XeeZoI,14884 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_tridiagonal_cusolver_sytrd.py,sha256=M7LMg3Gcj7PMt336U7KvsPrJ1BG8UGevYhb7dDeD954,39010 +jax/_src/internal_test_util/export_back_compat_test_data/cuda_tridiagonal_solve.py,sha256=sAipfYHp6DuXPRrt9sz9MtLV80lDRU3LLjuddHFU0Gk,7731 +jax/_src/internal_test_util/export_back_compat_test_data/pallas/__init__.py,sha256=gEMCMS8LKTvoFm0t7khiAnQg78EDUuMI-fvTvw250eo,682 +jax/_src/internal_test_util/export_back_compat_test_data/pallas/__pycache__/__init__.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/pallas/__pycache__/mosaic_gpu_add_one.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/pallas/__pycache__/mosaic_matmul.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/pallas/__pycache__/mosaic_semaphore_dma.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/pallas/__pycache__/triton_add_one.cpython-312.pyc,, +jax/_src/internal_test_util/export_back_compat_test_data/pallas/mosaic_gpu_add_one.py,sha256=BdloBuwb9-98TIDs7IORnhG-CSyITzRynkeNn26ipEg,102043 +jax/_src/internal_test_util/export_back_compat_test_data/pallas/mosaic_matmul.py,sha256=EZfWq9HQ8HHkz7CUg3i9ps0B4Kw1YmSnGsBYXxpLCAY,31178 +jax/_src/internal_test_util/export_back_compat_test_data/pallas/mosaic_semaphore_dma.py,sha256=ogBS9Lpa2MqBju6EX2I9p1K_PQemWOQEh4t5_ugUWCQ,16882 +jax/_src/internal_test_util/export_back_compat_test_data/pallas/triton_add_one.py,sha256=t-7TInuIX49zOqHTa9HZXEhnbPY8Ae8v1Dy-kYspRO0,10018 +jax/_src/internal_test_util/export_back_compat_test_data/rocm_eigh_hipsolver_syev.py,sha256=_tei01kakwhNzxyUD57wtXX6SZ7J4MqIRPwyM79Xi6k,114989 +jax/_src/internal_test_util/export_back_compat_test_data/shardy_sharding_ops_with_different_meshes.py,sha256=0EVxa7Z3_TfR-LWO_cUT4qjGgb48vOz53UGGny7iMfE,14786 +jax/_src/internal_test_util/export_back_compat_test_data/stablehlo_dynamic_approx_top_k.py,sha256=oekOSBpWgOtEYFdMS8FBkncdKzkQUYQ7V_QiY-zJjcg,13027 +jax/_src/internal_test_util/export_back_compat_test_data/stablehlo_dynamic_rng_bit_generator.py,sha256=jQPA3m1YSVp6PE78bXkckyBNqgYzdWUH5yl-wtXEEyE,11386 +jax/_src/internal_test_util/export_back_compat_test_data/stablehlo_dynamic_top_k.py,sha256=iinBbhX0A06ODm2gWUGY6ZxOkXdO-1y_ss1XeG74a6E,14132 +jax/_src/internal_test_util/export_back_compat_test_data/tpu_ApproxTopK.py,sha256=M200M40lgHqXk58UWeKeFzAOb4NSmbhmLo8ehbijAQE,12524 +jax/_src/internal_test_util/export_back_compat_test_data/tpu_Eigh.py,sha256=Imsy4t5CKQR4Zy1bFCyvmXiCdVSRgpnS64SMwY7Na3E,10121 +jax/_src/internal_test_util/export_back_compat_test_data/tpu_Lu.py,sha256=mSP47CuGZ1dBQviBSSFZD8yk2tXwcmVC2gC3rNQj_Eo,6150 +jax/_src/internal_test_util/export_back_compat_test_data/tpu_Qr.py,sha256=UekaagWJ4d_fWfrzFpXPHyRQPlGQeDEtk__gcmGwNpg,10203 +jax/_src/internal_test_util/export_back_compat_test_data/tpu_Sharding.py,sha256=F_QjAPzA2FuQXhJUHIwTvBDZl8n0qj2_Il_QBEa-kas,11052 +jax/_src/internal_test_util/export_back_compat_test_data/tpu_stablehlo_dynamic_reduce_window.py,sha256=JnDt0u66UpQNcMAzZthYKcctBFtyRvhdY7pYhH0KIo4,22961 +jax/_src/internal_test_util/export_back_compat_test_util.py,sha256=ztpe2MofjCMxiUk_1T0KhHAqYOk0qrkcFUU-5ou9JLc,15676 +jax/_src/internal_test_util/lax_test_util.py,sha256=_83LJKAcbyDkSrT2D2k4x1waaBHa37JMNISX6veyGHU,12998 +jax/_src/internal_test_util/lazy_loader_module/__init__.py,sha256=UP_c2VfWHRhfEi6n4F6qLHZuageXhPiVSAcUKHrrxFs,705 +jax/_src/internal_test_util/lazy_loader_module/__pycache__/__init__.cpython-312.pyc,, +jax/_src/internal_test_util/lazy_loader_module/__pycache__/lazy_test_submodule.cpython-312.pyc,, +jax/_src/internal_test_util/lazy_loader_module/lazy_test_submodule.py,sha256=luZv4DGyWwdcBX0_NBVwu81IE4jFYVbRkKo9gQPmxPk,610 +jax/_src/internal_test_util/test_harnesses.py,sha256=U7PkgvUN_JDeyaw5T66M-9GgWStCRFjMacGIQEakOSU,126282 +jax/_src/interpreters/__init__.py,sha256=hnuhN7h1jY5__Kt2rBvTrk0o8nX4fQl244fDCIMh0qk,690 +jax/_src/interpreters/__pycache__/__init__.cpython-312.pyc,, +jax/_src/interpreters/__pycache__/ad.cpython-312.pyc,, +jax/_src/interpreters/__pycache__/batching.cpython-312.pyc,, +jax/_src/interpreters/__pycache__/mlir.cpython-312.pyc,, +jax/_src/interpreters/__pycache__/partial_eval.cpython-312.pyc,, +jax/_src/interpreters/__pycache__/pxla.cpython-312.pyc,, +jax/_src/interpreters/__pycache__/xla.cpython-312.pyc,, +jax/_src/interpreters/ad.py,sha256=V5stFH6IbCzeoP5Ad0ZVGTpUGf2d9GoezODSdTtMEb4,58581 +jax/_src/interpreters/batching.py,sha256=6IPzUSG0I2c34Qm2q2zyWQcu1Fo0GSU8tPHAu4KI-NU,51724 +jax/_src/interpreters/mlir.py,sha256=XGOvZVyqWmOvwnHaSweMdQxvBJsimBkt0u2gofBXd-s,129090 +jax/_src/interpreters/partial_eval.py,sha256=Jb5qY5sJRdA3urA9KVneK-ZYbpSLmAcFWWMXN-EHh_c,122533 +jax/_src/interpreters/pxla.py,sha256=Tq-EXkLMKzKKZrCF2AVq66WRtsuZ8Vj4jK-dV6u4PA8,135973 +jax/_src/interpreters/xla.py,sha256=Me2RiFbqW_hF-RUOBNxQEGWkPhqYfYjH-12eAQbJHb0,4981 +jax/_src/jaxpr_util.py,sha256=igIrtHU_7BtJVfLwEkfslVSV43S9bnvmljKneAhOvQA,8532 +jax/_src/lax/__init__.py,sha256=jRL3qQoUco8BVUAh8lV-KuY38h_4GxXcb41asljW2yI,690 +jax/_src/lax/__pycache__/__init__.cpython-312.pyc,, +jax/_src/lax/__pycache__/ann.cpython-312.pyc,, +jax/_src/lax/__pycache__/convolution.cpython-312.pyc,, +jax/_src/lax/__pycache__/fft.cpython-312.pyc,, +jax/_src/lax/__pycache__/lax.cpython-312.pyc,, +jax/_src/lax/__pycache__/linalg.cpython-312.pyc,, +jax/_src/lax/__pycache__/other.cpython-312.pyc,, +jax/_src/lax/__pycache__/parallel.cpython-312.pyc,, +jax/_src/lax/__pycache__/slicing.cpython-312.pyc,, +jax/_src/lax/__pycache__/special.cpython-312.pyc,, +jax/_src/lax/__pycache__/utils.cpython-312.pyc,, +jax/_src/lax/__pycache__/windowed_reductions.cpython-312.pyc,, +jax/_src/lax/ann.py,sha256=drKiFUIxy8wodSZxGqpYd91Lq_M-WFyqM4NSSn1DqGc,16786 +jax/_src/lax/control_flow/__init__.py,sha256=WRnqzy4ec591tqipY4GcyXFzniF0njoIVkP0HhKGbiI,2244 +jax/_src/lax/control_flow/__pycache__/__init__.cpython-312.pyc,, +jax/_src/lax/control_flow/__pycache__/common.cpython-312.pyc,, +jax/_src/lax/control_flow/__pycache__/conditionals.cpython-312.pyc,, +jax/_src/lax/control_flow/__pycache__/for_loop.cpython-312.pyc,, +jax/_src/lax/control_flow/__pycache__/loops.cpython-312.pyc,, +jax/_src/lax/control_flow/__pycache__/solves.cpython-312.pyc,, +jax/_src/lax/control_flow/common.py,sha256=8rq9e1Pp87oAIdepv9f0sp8HlLK2akStBWNQ9Ik9WQA,11534 +jax/_src/lax/control_flow/conditionals.py,sha256=pRECf355U24pFi9Z7NpA8S5m8v8IjCXzd5f3l-HEY1Y,50891 +jax/_src/lax/control_flow/for_loop.py,sha256=XtqDTv8OmHFHVKlNW8qWqgyyyJk11s9mjT3BboCrNwY,36377 +jax/_src/lax/control_flow/loops.py,sha256=CRRWGTjfDoH8JYwLdYUIFAFJe65tS-JrKcVGEUEekO4,132594 +jax/_src/lax/control_flow/solves.py,sha256=9C-rBd_2PaVdefP7FHeGRmIEZ8e7hlf5JJg-rlaWpv0,20140 +jax/_src/lax/convolution.py,sha256=rL-mM5hd7g7ounRZLItM2zZqE4BlOOJDSMhSpMmqooc,45958 +jax/_src/lax/fft.py,sha256=3jloTWfLPoPvHbUfHde9Dqt-E96D5UXDmqgBxPEAsOg,7277 +jax/_src/lax/lax.py,sha256=EakRTxiKvgYTcA7Awz7s-HMdSGrM25NrLj8EHtSGk4I,362044 +jax/_src/lax/linalg.py,sha256=L1Lo2ufyXmT0q0IC3a-E2hdTpyaUmaSEcov1Ch0oCPs,101863 +jax/_src/lax/other.py,sha256=CzM6WbfsOKVlEDkGEd6SMdhftIx3GsIk4Wc_Zjh4n3E,13880 +jax/_src/lax/parallel.py,sha256=P9fN30E3hQEMVWptIArPBjc0ngnWl24hvrTW78xRr1Y,92373 +jax/_src/lax/slicing.py,sha256=JA7mHLFTslJFetcZROBvYGXmEJBlsPjhNWcdQcvjOkI,134815 +jax/_src/lax/special.py,sha256=yIjzWwwZ6IetGqkpQbEvyLtbcKj09HBI0VUS19yi7fc,28856 +jax/_src/lax/utils.py,sha256=6g-yPv2f8m04wOWxqYrct2zT-S3wwLNUD0W4XfZJgYg,8184 +jax/_src/lax/windowed_reductions.py,sha256=sJAt0GtGqMroUbUgabrFLWgMF0Y2l7GFAfvopbBgGQw,45255 +jax/_src/lax_reference.py,sha256=YPZTCI52PssuXAEnMn4r44ZZ2jDHB0wYj8d_fJDrCnw,19282 +jax/_src/layout.py,sha256=hh8CdqYW1CAF0JJ2i9g2D1LnK3HPNFK0Wveb5R21_us,5473 +jax/_src/lazy_loader.py,sha256=G6czW2Uq6WRC1EjDiX6rslMu02cZUGRkKNrvIhXksxw,1842 +jax/_src/lib/__init__.py,sha256=5diQ2imse9hzyc_lttydXH4-2vLxcRkqEnjuMatDtPg,7414 +jax/_src/lib/__pycache__/__init__.cpython-312.pyc,, +jax/_src/lib/__pycache__/mosaic_gpu.cpython-312.pyc,, +jax/_src/lib/__pycache__/triton.cpython-312.pyc,, +jax/_src/lib/mlir/__init__.py,sha256=UoirBDcNhqLa8Gb1Qrxd4wYxScz_p-1tb-ewbTsK1jM,733 +jax/_src/lib/mlir/__pycache__/__init__.cpython-312.pyc,, +jax/_src/lib/mlir/dialects/__init__.py,sha256=AmPoWPMMC7cOKxh68U9nEoIbL7FuiDh-5jOsf6_w57o,1965 +jax/_src/lib/mlir/dialects/__pycache__/__init__.cpython-312.pyc,, +jax/_src/lib/mosaic_gpu.py,sha256=lHnM852MFg7K5UUwry1zN_r5nrPSWl6ZVwOxVnsWAz4,898 +jax/_src/lib/triton.py,sha256=lMwAguUTQxYs9HkdLqeracg8sz5RL7gm1W6PpzSrzdk,2202 +jax/_src/linear_util.py,sha256=BywNkv9YiT5Aj9EBDFCKKSwlGpLV53PKQ1s4NOGSdBA,18959 +jax/_src/logging_config.py,sha256=zKijn3gjyw21ljvWjTsBX1bE6AyIa3zHRQ15YvaDDmk,4452 +jax/_src/lru_cache.py,sha256=NejEgo8BmO7xy8uORQrAHsN0HpCnY8qsEUnuEhDCkPs,6741 +jax/_src/mesh.py,sha256=T-PwGNcaVI628_R8HB5aYjzYx2qCUAUqWK-4EzkEaho,19327 +jax/_src/mesh_utils.py,sha256=JJWHor6Gjp4PL3FHeAybDrQmVLuKolK7Sja2tjMWT8M,32401 +jax/_src/monitoring.py,sha256=PSOb1js-21Hb4INsIdiJpm0s483xeljnoRr0Lha4nzM,6241 +jax/_src/named_sharding.py,sha256=spppAwVBVRD8oAIZfe1zS_wyqQrNZ8hjZ8wcj1TpjBc,20936 +jax/_src/nn/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/nn/__pycache__/__init__.cpython-312.pyc,, +jax/_src/nn/__pycache__/functions.cpython-312.pyc,, +jax/_src/nn/__pycache__/initializers.cpython-312.pyc,, +jax/_src/nn/functions.py,sha256=Pw6MrlzB3mZwWE5WzNKY2ATEs3PQPstKkLPvFDEIHQU,46816 +jax/_src/nn/initializers.py,sha256=Cxy-y3C9m9ZW0OBdYpPQZFmOUx8rdFLy78dao4dhH8M,26245 +jax/_src/numpy/__init__.py,sha256=-QhmzWj2qFbKVIT9TDAIvQWaKQibiRXy3r1zQkI3X4M,581 +jax/_src/numpy/__pycache__/__init__.cpython-312.pyc,, +jax/_src/numpy/__pycache__/array.cpython-312.pyc,, +jax/_src/numpy/__pycache__/array_api_metadata.cpython-312.pyc,, +jax/_src/numpy/__pycache__/array_creation.cpython-312.pyc,, +jax/_src/numpy/__pycache__/array_methods.cpython-312.pyc,, +jax/_src/numpy/__pycache__/einsum.cpython-312.pyc,, +jax/_src/numpy/__pycache__/error.cpython-312.pyc,, +jax/_src/numpy/__pycache__/fft.cpython-312.pyc,, +jax/_src/numpy/__pycache__/index_tricks.cpython-312.pyc,, +jax/_src/numpy/__pycache__/indexing.cpython-312.pyc,, +jax/_src/numpy/__pycache__/lax_numpy.cpython-312.pyc,, +jax/_src/numpy/__pycache__/linalg.cpython-312.pyc,, +jax/_src/numpy/__pycache__/polynomial.cpython-312.pyc,, +jax/_src/numpy/__pycache__/reductions.cpython-312.pyc,, +jax/_src/numpy/__pycache__/scalar_types.cpython-312.pyc,, +jax/_src/numpy/__pycache__/setops.cpython-312.pyc,, +jax/_src/numpy/__pycache__/sorting.cpython-312.pyc,, +jax/_src/numpy/__pycache__/tensor_contractions.cpython-312.pyc,, +jax/_src/numpy/__pycache__/ufunc_api.cpython-312.pyc,, +jax/_src/numpy/__pycache__/ufuncs.cpython-312.pyc,, +jax/_src/numpy/__pycache__/util.cpython-312.pyc,, +jax/_src/numpy/__pycache__/vectorize.cpython-312.pyc,, +jax/_src/numpy/__pycache__/window_functions.cpython-312.pyc,, +jax/_src/numpy/array.py,sha256=y28YH4w3g4_kuRrARM4XmKn0Go50UmFjlTclT5mukLE,14802 +jax/_src/numpy/array_api_metadata.py,sha256=GWwtKgbVQqOlmOsUqAqfE6A5p93ggVn4XBJNGXNwyx4,3655 +jax/_src/numpy/array_creation.py,sha256=uqLG63eWmYjTQvB324ioPteBHwhkg54SABQXzoiybOw,28396 +jax/_src/numpy/array_methods.py,sha256=Uu8IKkCzFnBCszxpjwxOAMOFQs4nAh545XGcHwXU-xA,47587 +jax/_src/numpy/einsum.py,sha256=OIO5axi7ltf8rljLpsfg_XavPtDHC6sNpVVt1mMVW-g,23717 +jax/_src/numpy/error.py,sha256=CYwkbfCTOCA-FNOIZSWiAHuUEx_9wa-Z7MW4XYv9Ss8,6625 +jax/_src/numpy/fft.py,sha256=UCYHowz7dIYjMas2VfMY16ePUuZWo3JgDKq6e5yUslY,52211 +jax/_src/numpy/index_tricks.py,sha256=Ug5oq2VY_XifIakhA6gibLbliXv0-1mz7SGptixN6jk,10047 +jax/_src/numpy/indexing.py,sha256=EjCQwYUyNiifwqfkh5osLqBePa687AlZARye2RTKyB0,51527 +jax/_src/numpy/lax_numpy.py,sha256=8NEU9-TvN8blY-oCwZJCvit45VgY8QfncGHzJfBFoq8,334446 +jax/_src/numpy/linalg.py,sha256=WJrCDPlGok-2XulamhQI4q2HF1l8C9aXyvn-lU63EXw,79128 +jax/_src/numpy/polynomial.py,sha256=GFJBmVeesY-fPwaz2CuNAOocODyBi6lYmCRu7jy20Jg,28429 +jax/_src/numpy/reductions.py,sha256=W3mb6r3xO7woO19XenARGUU9q6ucX1486zaLJI2wbFw,109440 +jax/_src/numpy/scalar_types.py,sha256=zd0YLOSUGus6TpytEUkENBMCz6g_pbuif0MYaLHqD1c,3823 +jax/_src/numpy/setops.py,sha256=HIRlTvUNoH7QdmpiGrnAH_86tO1_oi4gf8QSfQeqQvA,47910 +jax/_src/numpy/sorting.py,sha256=SbC_zj9z3IUUFnuXGJJ12kWSpjpl2oLpbuoFl2ndPts,16232 +jax/_src/numpy/tensor_contractions.py,sha256=uGQd_mRqfQcSJIndZKAaQt--qVOdlR72aKGo6bubeAU,24311 +jax/_src/numpy/ufunc_api.py,sha256=77SkEC8gDmMFpX9twGJfWAU-BsNZymy3C6ZUIqqAThw,24245 +jax/_src/numpy/ufuncs.py,sha256=L4nWL2e3f7kYWautK29Q6LHRw4WGN9hLq-kbiioqTgA,118733 +jax/_src/numpy/util.py,sha256=DazxM1zHR_fRTvdH3S0kUt-xKho8P8KNXzEATGG5HKM,17394 +jax/_src/numpy/vectorize.py,sha256=thLB2fBHVQBas7oaVWSsaOhtLgVWRwQekq_L5F7IjAA,14077 +jax/_src/numpy/window_functions.py,sha256=-AlJAgIqxJXMiXbIupk9XFC3DJljUF_BYVYIygR0k9I,5533 +jax/_src/op_shardings.py,sha256=nRnGgfaKz7mIB7sHxh_QkiCa1oPMA9VsDpPyQkivtlU,3857 +jax/_src/ops/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/ops/__pycache__/__init__.cpython-312.pyc,, +jax/_src/ops/__pycache__/scatter.cpython-312.pyc,, +jax/_src/ops/__pycache__/special.cpython-312.pyc,, +jax/_src/ops/scatter.py,sha256=8QUaAIS9mgB28RfAL-L_qocl6WW8I6pit1rPQJqe2ac,18181 +jax/_src/ops/special.py,sha256=p1hRiOonzxVdhfcDGjVxLkL2nU0iU3EtgtmnchLIFgo,4212 +jax/_src/pallas/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/_src/pallas/__pycache__/__init__.cpython-312.pyc,, +jax/_src/pallas/__pycache__/core.cpython-312.pyc,, +jax/_src/pallas/__pycache__/cost_estimate.cpython-312.pyc,, +jax/_src/pallas/__pycache__/helpers.cpython-312.pyc,, +jax/_src/pallas/__pycache__/hlo_interpreter.cpython-312.pyc,, +jax/_src/pallas/__pycache__/pallas_call.cpython-312.pyc,, +jax/_src/pallas/__pycache__/primitives.cpython-312.pyc,, +jax/_src/pallas/__pycache__/utils.cpython-312.pyc,, +jax/_src/pallas/core.py,sha256=2CCu88ci6N9xytDmT_8tERaH6uAaE5Zo4e5LVMINOiI,48329 +jax/_src/pallas/cost_estimate.py,sha256=inTDMJ3N7qBsRFf7MIBnkgK72wN5qyaTDp5Qg5jt7WE,8316 +jax/_src/pallas/fuser/__init__.py,sha256=cHEWioEa-43e-714tP3fFN9hdyZg_ebBFbFJur7bXwg,1182 +jax/_src/pallas/fuser/__pycache__/__init__.cpython-312.pyc,, +jax/_src/pallas/fuser/__pycache__/block_spec.cpython-312.pyc,, +jax/_src/pallas/fuser/__pycache__/custom_evaluate.cpython-312.pyc,, +jax/_src/pallas/fuser/__pycache__/fuser_utils.cpython-312.pyc,, +jax/_src/pallas/fuser/__pycache__/fusible.cpython-312.pyc,, +jax/_src/pallas/fuser/__pycache__/fusible_dtype.cpython-312.pyc,, +jax/_src/pallas/fuser/__pycache__/fusion.cpython-312.pyc,, +jax/_src/pallas/fuser/__pycache__/jaxpr_fusion.cpython-312.pyc,, +jax/_src/pallas/fuser/block_spec.py,sha256=mbOyMpm3r61LFNSxS8BDMDmhlg1lVk4yYzQE-TIyuSQ,67290 +jax/_src/pallas/fuser/custom_evaluate.py,sha256=jv5JjL5BlUUK89ZKx9sufff0bVyqJA3s5ag6Bpus5ys,2823 +jax/_src/pallas/fuser/fuser_utils.py,sha256=UY_9Ly9Z863mHX3R_EdLw4H1jLsTCeaeTDMV1Dg9l-s,1273 +jax/_src/pallas/fuser/fusible.py,sha256=afsksW8n7JyKqC3Ggolu4GLWYU1ontw-czS0xkwPmjU,2692 +jax/_src/pallas/fuser/fusible_dtype.py,sha256=dDhqowkKZ7uePKSSsCq3toBctGXC8bBRAfm5yMO0MGM,15648 +jax/_src/pallas/fuser/fusion.py,sha256=W1NBIzSqOkBk8ADty9HfjnmePZXKBsPxFUiM_k3qtC8,1488 +jax/_src/pallas/fuser/jaxpr_fusion.py,sha256=02209zSpwEsPCrR8lsj1EXkleKG5ylZFmcKhHLclHsU,10808 +jax/_src/pallas/helpers.py,sha256=UpIfs-yNk4IrTXNVzmGlSOOXQriEzGwNAlCLofX7CMg,2806 +jax/_src/pallas/hlo_interpreter.py,sha256=zeOxcMsbGApyMHQcB4ktTdNlvU4rQIMf6qzbh9HR_mE,19049 +jax/_src/pallas/mosaic/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/_src/pallas/mosaic/__pycache__/__init__.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/core.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/error_handling.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/helpers.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/interpret.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/lowering.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/pallas_call_registration.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/pipeline.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/primitives.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/random.cpython-312.pyc,, +jax/_src/pallas/mosaic/__pycache__/verification.cpython-312.pyc,, +jax/_src/pallas/mosaic/core.py,sha256=pD2hETgHNjp_tr4wJa5eT7hY50Rp4XKnN5Hx8mqzwlA,9908 +jax/_src/pallas/mosaic/error_handling.py,sha256=FCbB-b5Dl75erMmr-FMvc4QJwCXqn2z7ioNC2Eh0vQc,5542 +jax/_src/pallas/mosaic/helpers.py,sha256=DFBL7RuFtfBQc-aUaC4bILa5Xzsbb91Wu3VCn7b3v4M,2767 +jax/_src/pallas/mosaic/interpret.py,sha256=EhtWDOp8hSSzO130OQKcG9GgYbUBGcLg5IaipJOY6CU,89639 +jax/_src/pallas/mosaic/lowering.py,sha256=TjUpBJjBFPZhCUpXRGSdasnrMm2A67QXM7a9Uv3zHkY,137751 +jax/_src/pallas/mosaic/pallas_call_registration.py,sha256=N46ZF8Wv2aJleLyDWfBf88rDWSyD8HmtNlaDQ1yo_iE,10372 +jax/_src/pallas/mosaic/pipeline.py,sha256=QM23p3Bi3mOMe47mTISP0oVor3LfNOySImFlW0O-8do,58211 +jax/_src/pallas/mosaic/primitives.py,sha256=C5YGYasXoiBa-YRZGRlPN5q6ykZQT3w4YpSi2uezRP4,27566 +jax/_src/pallas/mosaic/random.py,sha256=l402QtsGJkvPQ9UY_o9XNWsL58_YXVDBxaGxNhFTLWo,7845 +jax/_src/pallas/mosaic/verification.py,sha256=1QWYOwAAOvuCgB8gXWCJUlP1mPLvegzeUoFgJ_xC4X4,24485 +jax/_src/pallas/mosaic_gpu/__init__.py,sha256=mS3YSYUZFIG68T5Zo9CFGkT7wCyWRycnWV4L36CnHYU,581 +jax/_src/pallas/mosaic_gpu/__pycache__/__init__.cpython-312.pyc,, +jax/_src/pallas/mosaic_gpu/__pycache__/core.cpython-312.pyc,, +jax/_src/pallas/mosaic_gpu/__pycache__/helpers.cpython-312.pyc,, +jax/_src/pallas/mosaic_gpu/__pycache__/lowering.cpython-312.pyc,, +jax/_src/pallas/mosaic_gpu/__pycache__/pallas_call_registration.cpython-312.pyc,, +jax/_src/pallas/mosaic_gpu/__pycache__/pipeline.cpython-312.pyc,, +jax/_src/pallas/mosaic_gpu/__pycache__/primitives.cpython-312.pyc,, +jax/_src/pallas/mosaic_gpu/core.py,sha256=TrrfnxJBJaDBqxXTzoyuvyn9v3o1tvpTf5MQtiizJRM,36464 +jax/_src/pallas/mosaic_gpu/helpers.py,sha256=DOkDJ7shcKrNau9KgJ8Kt_ceUGE4lkFCEEpqaZjUE-k,2854 +jax/_src/pallas/mosaic_gpu/lowering.py,sha256=Dah7uTWIUk0ik1XKnSbrNPar78vxqSi63dr5nyOXU8c,116786 +jax/_src/pallas/mosaic_gpu/pallas_call_registration.py,sha256=THgSdULeaycMfFwzVPu6IoMoC8TFIvEIIWAL55DmJlc,5589 +jax/_src/pallas/mosaic_gpu/pipeline.py,sha256=xYlDhR0S2ZE0CpHRDwG11coljWacwYssiSGsE3-AdAE,29039 +jax/_src/pallas/mosaic_gpu/primitives.py,sha256=pw7pqjT9RSYP61a3v9YdBPVjyXjCDNQ2--p63M-jTYU,71008 +jax/_src/pallas/pallas_call.py,sha256=msCZDel3ss4Slrj3EhwZmpNQI5fG_L9DurOBn5nd284,69253 +jax/_src/pallas/primitives.py,sha256=sS4qmP9oV5WIxA0GCjnpyjJeNGFPZ7YZMt4GIG2hV_Q,43036 +jax/_src/pallas/triton/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/_src/pallas/triton/__pycache__/__init__.cpython-312.pyc,, +jax/_src/pallas/triton/__pycache__/core.cpython-312.pyc,, +jax/_src/pallas/triton/__pycache__/lowering.cpython-312.pyc,, +jax/_src/pallas/triton/__pycache__/pallas_call_registration.cpython-312.pyc,, +jax/_src/pallas/triton/__pycache__/primitives.cpython-312.pyc,, +jax/_src/pallas/triton/core.py,sha256=pd0AQ5oEU2oljvCJfkJmUuyjEBtxEn6Ml6dtChdCTE4,1383 +jax/_src/pallas/triton/lowering.py,sha256=jLBLVEQ-mHGT4C1lNHDFYFbq87xoMxR4JtSRkMzuNCA,99180 +jax/_src/pallas/triton/pallas_call_registration.py,sha256=5D-I2Y4c-xr4AcFNU7z2NwhpVffrwMZxBzro7STZQng,6699 +jax/_src/pallas/triton/primitives.py,sha256=h_nAb5_WTDgtna0a5VDKql4hDx8I2gt9ryuY5LsQo9A,4235 +jax/_src/pallas/utils.py,sha256=LvCcGVDxrA08HbQ3cngF8D2hZKq2lz7-_Opye8wSccA,13889 +jax/_src/partition_spec.py,sha256=zvr3RWjMJDxpq_l9APIxwyeLPJU2zmtGtpzTdR0NQUg,8618 +jax/_src/path.py,sha256=VkrwcBMWagZZQBBQYhdSFr7pQzoxwBnNUEfKfEbN-nU,1596 +jax/_src/pickle_util.py,sha256=gE8IrNWtg4hfu84T5rQ2DVAdpozh5xwSzAlRi7UIWcQ,2312 +jax/_src/pjit.py,sha256=4AygjlqWJSbkFOolz1P1h7ThT_8wXSz3auPOnxJ1j4M,147338 +jax/_src/pretty_printer.py,sha256=1tSAtbJj6N9a0ZjwqphDD-kPPolsYxRp8JM_WYkrUXI,17578 +jax/_src/prng.py,sha256=jjeeUE463LUWFfviEXqIrdauTTBzY8e_xvqf9NHrqpg,46495 +jax/_src/profiler.py,sha256=zPgtTULdZBFGT629usNmQq82mtAfRjd77Hssq2Xsf3Q,17282 +jax/_src/public_test_util.py,sha256=wXB1H7lgFuDvZVRyDOs-yPMm9C18VKVPKUfKlIdF7gI,12676 +jax/_src/random.py,sha256=lWxw3thgcBMIiZM-dgEBUEWQ9wfl7LBGYPJPti015q0,108171 +jax/_src/scipy/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/scipy/__pycache__/__init__.cpython-312.pyc,, +jax/_src/scipy/__pycache__/fft.cpython-312.pyc,, +jax/_src/scipy/__pycache__/integrate.cpython-312.pyc,, +jax/_src/scipy/__pycache__/linalg.cpython-312.pyc,, +jax/_src/scipy/__pycache__/ndimage.cpython-312.pyc,, +jax/_src/scipy/__pycache__/signal.cpython-312.pyc,, +jax/_src/scipy/__pycache__/special.cpython-312.pyc,, +jax/_src/scipy/cluster/__init__.py,sha256=S-o0CP72882Xv3l6k2PlrEx6eNvXBTk5Oaed5KF4iL8,581 +jax/_src/scipy/cluster/__pycache__/__init__.cpython-312.pyc,, +jax/_src/scipy/cluster/__pycache__/vq.cpython-312.pyc,, +jax/_src/scipy/cluster/vq.py,sha256=3Xfr7esTCzSawrDGZ37hu_MXJ-EqnZtff6hYmXhz0Fc,3043 +jax/_src/scipy/fft.py,sha256=NFy_bDIzx44Lpkw1-74fBm2jxeXmzIUp8LTVh3-6Z5s,15281 +jax/_src/scipy/integrate.py,sha256=4VtR2wYVO037Z0yiOdQbniKtpxL4boZQNIppy4J9qy0,2346 +jax/_src/scipy/interpolate/__init__.py,sha256=S-o0CP72882Xv3l6k2PlrEx6eNvXBTk5Oaed5KF4iL8,581 +jax/_src/scipy/interpolate/__pycache__/__init__.cpython-312.pyc,, +jax/_src/scipy/linalg.py,sha256=jLR8xl1wfluw0vr0rEdA1gCGfpKhYuFRsmD7cbGaX3k,79500 +jax/_src/scipy/ndimage.py,sha256=IuE4PMzY5HuxST9D0G0On1SVFRpNF367Y2cIQv8duTc,7092 +jax/_src/scipy/optimize/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/scipy/optimize/__pycache__/__init__.cpython-312.pyc,, +jax/_src/scipy/optimize/__pycache__/_lbfgs.cpython-312.pyc,, +jax/_src/scipy/optimize/__pycache__/bfgs.cpython-312.pyc,, +jax/_src/scipy/optimize/__pycache__/line_search.cpython-312.pyc,, +jax/_src/scipy/optimize/__pycache__/minimize.cpython-312.pyc,, +jax/_src/scipy/optimize/_lbfgs.py,sha256=kqKkdDeRYiH5prawdntOXfCs-g311NYwnY57jV8DDbw,7769 +jax/_src/scipy/optimize/bfgs.py,sha256=JRdDBxnfNrVxK5UDyehFGF3eQTJenWfdZVmKOMheenE,5609 +jax/_src/scipy/optimize/line_search.py,sha256=E51ROBUJYmanL1byuPpIa28HmN1vCf_BAaBC_dQZgoc,13235 +jax/_src/scipy/optimize/minimize.py,sha256=mCojZkL0TXQhix6w0-GroM7ITU2rodYdDwmvynLsqWs,4979 +jax/_src/scipy/signal.py,sha256=mwzup6IeV3hlG5npG2Q92imD-v74w9AtENhvxpcABQw,47396 +jax/_src/scipy/sparse/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/scipy/sparse/__pycache__/__init__.cpython-312.pyc,, +jax/_src/scipy/sparse/__pycache__/linalg.cpython-312.pyc,, +jax/_src/scipy/sparse/linalg.py,sha256=IGX8lZ2il77S3WA50Lz7MdBiw7lqdD8mHgWRaCUHX6k,27245 +jax/_src/scipy/spatial/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/_src/scipy/spatial/__pycache__/__init__.cpython-312.pyc,, +jax/_src/scipy/spatial/__pycache__/transform.cpython-312.pyc,, +jax/_src/scipy/spatial/transform.py,sha256=yD9HOfgQpQO3-eACTh5zW8qzV-WLcrTHY_5ZlsnBoSk,17525 +jax/_src/scipy/special.py,sha256=tR7nHwwEUHKCWjEXOwRoTXvWdnLaNTJKeyrkK3jzDo0,90272 +jax/_src/scipy/stats/__init__.py,sha256=9AYvmtjvwOmouHXvS-uU2Id1YBE7CUbYVE__dR1koWg,581 +jax/_src/scipy/stats/__pycache__/__init__.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/_core.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/bernoulli.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/beta.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/betabinom.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/binom.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/cauchy.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/chi2.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/dirichlet.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/expon.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/gamma.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/gennorm.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/geom.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/kde.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/laplace.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/logistic.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/multinomial.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/multivariate_normal.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/nbinom.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/norm.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/pareto.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/poisson.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/t.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/truncnorm.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/uniform.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/vonmises.cpython-312.pyc,, +jax/_src/scipy/stats/__pycache__/wrapcauchy.cpython-312.pyc,, +jax/_src/scipy/stats/_core.py,sha256=khdXG4LFVlXGQ2derIQIfL7TN1SXfdNZ59uBq3gtBn0,10652 +jax/_src/scipy/stats/bernoulli.py,sha256=zOvo5ZLr8y3O0byR0cp3JRPKPPHoz8oVyG3-C_5-NJo,4541 +jax/_src/scipy/stats/beta.py,sha256=h2LF8lIveFCa-qNZ_XLD1hQIK9_dLSmlCjrqeSdz_ME,7988 +jax/_src/scipy/stats/betabinom.py,sha256=dmhOAUk6py5Fnu-jR95KnwJ6suvvfwNF9CXNHz73CSc,3447 +jax/_src/scipy/stats/binom.py,sha256=E7a3go8bCM5bSiC72l1pDQEuuzSpXLmgfG40iPF90wA,2825 +jax/_src/scipy/stats/cauchy.py,sha256=26eHaNIfxwh1og3kTqnPYgivH0GTIuWVwElai4VJwv8,8884 +jax/_src/scipy/stats/chi2.py,sha256=vPFrhpbLRPDheYenmHQ7QvZrRt8cAyRtOpU9VmemNIY,8008 +jax/_src/scipy/stats/dirichlet.py,sha256=_wWyx07z62_EH25i3J4jS5q53oj0UH5A3-XgQzapwbY,3198 +jax/_src/scipy/stats/expon.py,sha256=W0tt3HtC5jB5mEM-bQbAC4U9FKVJFspsqnPpOAN6_FE,7813 +jax/_src/scipy/stats/gamma.py,sha256=Nf0qgFD7K-2H4R581g1Kb0RQ_WHZrl81A1vgyS_PdxM,7038 +jax/_src/scipy/stats/gennorm.py,sha256=kp22L5H-rR5n7sn9rpeWsWta-F76yZaXkO0Ovvf9zc8,2989 +jax/_src/scipy/stats/geom.py,sha256=2hQ4LoaqNHFBahdRTGS9oyWMYdFQufJb2ByqOw9709s,2243 +jax/_src/scipy/stats/kde.py,sha256=qY2ZLH8HVOU50DhQBDrhH2XTLT1eUHAFx7qGuvhgSmc,10139 +jax/_src/scipy/stats/laplace.py,sha256=9PlK08r9wRHelqSIuKkv8KGO0oPV2AArI0Fs6rICFj0,3269 +jax/_src/scipy/stats/logistic.py,sha256=HB3Brjwwl-yyGB_9K1lpdiQlmitsHwNLfgl0g4owFSM,6271 +jax/_src/scipy/stats/multinomial.py,sha256=CVgpOPCVcr_wTNuF1vXcUjgsENe2mVO7gYBYTSdCOwI,2469 +jax/_src/scipy/stats/multivariate_normal.py,sha256=Dei7nhj3j5gB1lBi9q_ZpdMHi1UY7XCr3GTzNuaWF1E,3433 +jax/_src/scipy/stats/nbinom.py,sha256=kr6FLGYROqMMtfLfWLI1fumHBl_tSX1_Ys2icp59Hdw,2603 +jax/_src/scipy/stats/norm.py,sha256=pUS-JhrjrFtdbfO178IeOJizZBU_WjXU6aUr8W67tQg,8401 +jax/_src/scipy/stats/pareto.py,sha256=WcRAchdj198RF_W3egR8Bteok1dXE0PHv9ygw-pQYtM,2596 +jax/_src/scipy/stats/poisson.py,sha256=Y43e2hY6L89go0Vc1HJCDrf61-vDZcQVIC6zVJdaYyQ,3348 +jax/_src/scipy/stats/t.py,sha256=I32sQ9TVaes4keK5AIK6I-vX--nvl4qtZctuc0zIhG0,3221 +jax/_src/scipy/stats/truncnorm.py,sha256=V4_Y2OEMYPepPyWVqMZKO0hRV8HwwnI6_djK9xYwdDA,9239 +jax/_src/scipy/stats/uniform.py,sha256=pR3NYr6ZHTs6xhw-LECsRJqp5l_iBbsw689QHxr9Puc,4361 +jax/_src/scipy/stats/vonmises.py,sha256=yxvmgBI_HWQn8U3u7wtLv9PjqOk7hRX8I4gWKfqRZKg,2451 +jax/_src/scipy/stats/wrapcauchy.py,sha256=SpHIjzS9j3TqgAMTHXxtDz73aBfezqYUaNSsGYCky5I,2371 +jax/_src/shard_alike.py,sha256=wG_kUvyH6aNRjgViwVffEAz1tbfhBF66kf3vw0XexIg,3989 +jax/_src/shard_map.py,sha256=XEN3qJm1jiEoKU6MEVzISJuDsZyenfIgVIeePV1dd5g,83143 +jax/_src/sharding.py,sha256=pkrmy_r6huTjqDmNsQaFmWIFdxZukjp5NyeWhMbC-OE,7704 +jax/_src/sharding_impls.py,sha256=cz5OCPAFt9xdpg2KknC1cgeHehaIr2NosluMTb0mSSQ,54459 +jax/_src/sharding_specs.py,sha256=UCYUIcQfS6lcA993W33zZI5tfAg5zcefP9cZUyW9NoI,8617 +jax/_src/source_info_util.py,sha256=O8Ff0QonDyYKecTH8a2KdqBe7HuQHrIDTkb-OShHnpk,10852 +jax/_src/sourcemap.py,sha256=5s4zTThhX6PZwgQ4v4UbYL4norg4uHipqgUGdHBn76Y,6640 +jax/_src/stages.py,sha256=ZhJCGlgFqiYyIvYEiCLojdrwanNULwhorSAb_6N7SJA,31569 +jax/_src/state/__init__.py,sha256=TU0qQETOXKzVAd1oVaIEtOJTC2OMj1PdFhsExMHFx2g,988 +jax/_src/state/__pycache__/__init__.cpython-312.pyc,, +jax/_src/state/__pycache__/discharge.cpython-312.pyc,, +jax/_src/state/__pycache__/indexing.cpython-312.pyc,, +jax/_src/state/__pycache__/primitives.cpython-312.pyc,, +jax/_src/state/__pycache__/types.cpython-312.pyc,, +jax/_src/state/__pycache__/utils.cpython-312.pyc,, +jax/_src/state/discharge.py,sha256=6tvlsF0-yXrdFuIKj7VgzWIkdbsvGsuM9TpsQoo25rA,50958 +jax/_src/state/indexing.py,sha256=_ZVN84Jo5Z39SVAJR8WJvXlnDMnGKKMNncdUc1azI9A,12013 +jax/_src/state/primitives.py,sha256=IVxrV6bJcEFfyzo3qGbaeHlZJER70hoG539OvqWzd7c,30799 +jax/_src/state/types.py,sha256=BePu2rY2_iqistfF42FcxQCYqmyFm1NMDqfFt4fKZk4,14923 +jax/_src/state/utils.py,sha256=BBCCdjdCyaZmnB1Y6FSfSZ9JyWiAbTX8c1ZaXfR-lt4,4107 +jax/_src/test_loader.py,sha256=l7LDHdnqD5g44nUo4Hdwtc8IplXjCcn-L9-RO4Q_qhs,7260 +jax/_src/test_multiprocess.py,sha256=ZOXfV-PAbNdhyJpbaMywexNTfM1pnm_xpvLbRo3ub8U,8602 +jax/_src/test_util.py,sha256=xUMWeuXxjtnTGIBa10HHMzU4McYKjl613I-gAjcUf-8,81442 +jax/_src/test_warning_util.py,sha256=9CvuFdeyGcmTH5xfz3Wqs0qOUGpOVcOwh4SnJsp6FbE,4074 +jax/_src/third_party/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jax/_src/third_party/__pycache__/__init__.cpython-312.pyc,, +jax/_src/third_party/scipy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jax/_src/third_party/scipy/__pycache__/__init__.cpython-312.pyc,, +jax/_src/third_party/scipy/__pycache__/betaln.cpython-312.pyc,, +jax/_src/third_party/scipy/__pycache__/interpolate.cpython-312.pyc,, +jax/_src/third_party/scipy/__pycache__/linalg.cpython-312.pyc,, +jax/_src/third_party/scipy/__pycache__/signal_helper.cpython-312.pyc,, +jax/_src/third_party/scipy/__pycache__/special.cpython-312.pyc,, +jax/_src/third_party/scipy/betaln.py,sha256=TT77MW5HcPt-C6m-jHT43mGPLuAKO9ANcoEsXjl8JDE,2373 +jax/_src/third_party/scipy/interpolate.py,sha256=5C9-SwIUrwlpBUgAKYskaSLgTbOtpwESJRPv-6cjj0Y,6307 +jax/_src/third_party/scipy/linalg.py,sha256=SzmpCoi4kSnLTflDsRa5QdoBcijKHuwmtN9xac2TWlw,3786 +jax/_src/third_party/scipy/signal_helper.py,sha256=3IF3mEJ09uSuPeDVM1ntW5dYSoOi-LQDZJkXr38Rv-Q,3508 +jax/_src/third_party/scipy/special.py,sha256=weGxx01LOfJDklgdX8vKJVUpTy1_FV_9PWEX2hgNtB0,9136 +jax/_src/tpu/__init__.py,sha256=4S3pYNuiw6yzPmNNm2iRi40_Jf9xlHj-oIRb9Gp4sxk,581 +jax/_src/tpu/__pycache__/__init__.cpython-312.pyc,, +jax/_src/tpu/linalg/__init__.py,sha256=RrUPd-WnsNpraGGzWYI-IYTpNcbtQeGqaotRh0Bwwuw,779 +jax/_src/tpu/linalg/__pycache__/__init__.cpython-312.pyc,, +jax/_src/tpu/linalg/__pycache__/eigh.cpython-312.pyc,, +jax/_src/tpu/linalg/__pycache__/qdwh.cpython-312.pyc,, +jax/_src/tpu/linalg/__pycache__/stack.cpython-312.pyc,, +jax/_src/tpu/linalg/__pycache__/svd.cpython-312.pyc,, +jax/_src/tpu/linalg/eigh.py,sha256=0MfHzHgLzvEshFYTdO3p_J-lj9zNyI8EcGGLJ4mCCog,24588 +jax/_src/tpu/linalg/qdwh.py,sha256=dmslOVnzg-DhxjSIHV9jHCOKopVosYD-xe1FPmSgnCo,9391 +jax/_src/tpu/linalg/stack.py,sha256=7hxK1zlVa_Q9gO48Ymj8S1nA8DN6keYgcOY0DAtbjOY,2560 +jax/_src/tpu/linalg/svd.py,sha256=jg30dXixuXfvLX21YCl21rl2lwwxS2OE2-QQp0KraXA,10158 +jax/_src/tpu_custom_call.py,sha256=0KcEmuUf0rohGQfFRSUsdwC8fYzbJ-C93FpoXSXCmiQ,26097 +jax/_src/traceback_util.py,sha256=QZinVxddgYKdO3p8OFo2JITpZMJO-wttlxe4L7GcTqM,9141 +jax/_src/tree.py,sha256=UAJzeQwkIRHqVwtQlM3OSfn9lvb1pdnDxnfA6HCYOSo,13975 +jax/_src/tree_util.py,sha256=03qiPML25BoA4zEcg3Ew4DAlXATcS9UCihXntnw2Xew,47308 +jax/_src/typing.py,sha256=Ed5ujNHsKktTk0Z2nhZojS_77K1INnsPvj4S7o0KQ5Q,3529 +jax/_src/util.py,sha256=E9YnFhRSRbuaVQSN4e5_3VckAfaV4K6hWEF0qqrtCak,20945 +jax/_src/xla_bridge.py,sha256=VeZ-NCvtITNFrxpuu3IByAhUaZqAeotMsbipmdaOxpo,41461 +jax/_src/xla_metadata.py,sha256=ZQUQ4c8Sn11_3LW1WcOl8umxV3NerwhE5NLYKaUUh9I,2103 +jax/ad_checkpoint.py,sha256=jnNhXa-FiezkCFP9BlCul194Pz11olQPdZEeoCJQi-U,932 +jax/api_util.py,sha256=avYenJ6674XMZHYtWzplyMPO0j2NXOk13BYb1o3vnCc,979 +jax/cloud_tpu_init.py,sha256=r_UB06-qStzlo7BWtH7eZ7OMl3ayrG_CQXWQJJwWsYs,651 +jax/collect_profile.py,sha256=vLzsQEhtxsHlLbSocpoY4-9IIza8gEZ22NhLUo1Es6Q,4511 +jax/core.py,sha256=ArEQGXJE2KwLLZKXaLAkDM13beCiDP4XdiNAxCKHhxk,8619 +jax/custom_batching.py,sha256=MEoypZfGgYqvZrBKtnvL5sQjl8YrjVm11hiFWoTCtV8,691 +jax/custom_derivatives.py,sha256=CVhRiRgnWk5hBsc3ZX7mFD0Yst2S9VDAirtwF8rSZcY,1967 +jax/custom_transpose.py,sha256=vGj3GjRJQpxl-MhvYztIedauNBiWMj9nD_aJHQiNaYc,664 +jax/debug.py,sha256=HXdNZlaM5LxtEYS6fsH3J4LRgiDVL-5W6AXcimbFS5o,1083 +jax/distributed.py,sha256=CP5IDXwA4QzxXilcTCM1F6435U3dYsdWkDzO4hr_evE,710 +jax/dlpack.py,sha256=UBWbObzJ-N-nFAPvoSTamtXH2uaqSoG2-NnUDYuZuEo,1411 +jax/dtypes.py,sha256=iaMlUUaiUH8zFsy5IJEff4s5QTu0EzD5msV-JYAyD6I,1188 +jax/errors.py,sha256=MaZbeSxeRyWRMfq4cj6P0GA9UFykLgX3aURPAKhqbts,1363 +jax/example_libraries/__init__.py,sha256=9jtOmvvDMLWHLUuqHkvlxcTzvN1yoUxeFmRAxYu7lMw,581 +jax/example_libraries/__pycache__/__init__.cpython-312.pyc,, +jax/example_libraries/__pycache__/optimizers.cpython-312.pyc,, +jax/example_libraries/__pycache__/stax.cpython-312.pyc,, +jax/example_libraries/optimizers.py,sha256=T2D3qDPWZ50kwTyDe2IXPPLbOUu04cQTdf51oHdXVvU,20426 +jax/example_libraries/stax.py,sha256=jNCoL5RlFv9JnLssUHthGRaNcA9xY57BKPxF76Nz7u8,13862 +jax/experimental/__init__.py,sha256=yoE5_c5xRagzLRgNBgo2jRWg31h8Sm-dpKW58vhgjh0,1198 +jax/experimental/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/__pycache__/attrs.cpython-312.pyc,, +jax/experimental/__pycache__/buffer_callback.cpython-312.pyc,, +jax/experimental/__pycache__/checkify.cpython-312.pyc,, +jax/experimental/__pycache__/compute_on.cpython-312.pyc,, +jax/experimental/__pycache__/custom_dce.cpython-312.pyc,, +jax/experimental/__pycache__/custom_partitioning.cpython-312.pyc,, +jax/experimental/__pycache__/host_callback.cpython-312.pyc,, +jax/experimental/__pycache__/jet.cpython-312.pyc,, +jax/experimental/__pycache__/layout.cpython-312.pyc,, +jax/experimental/__pycache__/mesh_utils.cpython-312.pyc,, +jax/experimental/__pycache__/multihost_utils.cpython-312.pyc,, +jax/experimental/__pycache__/ode.cpython-312.pyc,, +jax/experimental/__pycache__/pjit.cpython-312.pyc,, +jax/experimental/__pycache__/profiler.cpython-312.pyc,, +jax/experimental/__pycache__/rnn.cpython-312.pyc,, +jax/experimental/__pycache__/serialize_executable.cpython-312.pyc,, +jax/experimental/__pycache__/shard.cpython-312.pyc,, +jax/experimental/__pycache__/shard_alike.cpython-312.pyc,, +jax/experimental/__pycache__/shard_map.cpython-312.pyc,, +jax/experimental/__pycache__/topologies.cpython-312.pyc,, +jax/experimental/__pycache__/transfer.cpython-312.pyc,, +jax/experimental/__pycache__/x64_context.cpython-312.pyc,, +jax/experimental/__pycache__/xla_metadata.cpython-312.pyc,, +jax/experimental/array_serialization/__init__.py,sha256=9jtOmvvDMLWHLUuqHkvlxcTzvN1yoUxeFmRAxYu7lMw,581 +jax/experimental/array_serialization/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/array_serialization/__pycache__/pytree_serialization.cpython-312.pyc,, +jax/experimental/array_serialization/__pycache__/pytree_serialization_utils.cpython-312.pyc,, +jax/experimental/array_serialization/__pycache__/serialization.cpython-312.pyc,, +jax/experimental/array_serialization/__pycache__/tensorstore_impl.cpython-312.pyc,, +jax/experimental/array_serialization/pytree_serialization.py,sha256=L5zgqU3-STe4LsDJywjOCwoketfhMHn7FMdSMz6enl4,21220 +jax/experimental/array_serialization/pytree_serialization_utils.py,sha256=rBZP00cuR2uWhIgdralpm4HgVrFjJ-nTMeNU2zqP7zA,2776 +jax/experimental/array_serialization/serialization.py,sha256=3wiRVOMdD3odJbxFPwK3gj1ttUhkrWWTEutDF_XXPBI,13434 +jax/experimental/array_serialization/tensorstore_impl.py,sha256=sqUObJJ-40GIJ_1CXDtSfe2GQK-T5ZuseAHO68oQvX0,24666 +jax/experimental/attrs.py,sha256=FRU-Wm4BsARc07DAZ_GyL765Rhuusz4OLtKHmwRPDL0,749 +jax/experimental/buffer_callback.py,sha256=ocKnbOO_9n62E2olM0c2a4ep8AHTan4I_AL-eR5VbrQ,765 +jax/experimental/checkify.py,sha256=V84hTTNrwnckaRzgvWDmpcKKA95kAakjZwwlfnRaXt0,1213 +jax/experimental/colocated_python/__init__.py,sha256=Cp1CgJT_Sn5qLkiO7jW5S0HPWieBmOdpEE-AaYpKs9E,980 +jax/experimental/colocated_python/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/colocated_python/__pycache__/api.cpython-312.pyc,, +jax/experimental/colocated_python/__pycache__/func.cpython-312.pyc,, +jax/experimental/colocated_python/__pycache__/func_backend.cpython-312.pyc,, +jax/experimental/colocated_python/__pycache__/obj.cpython-312.pyc,, +jax/experimental/colocated_python/__pycache__/obj_backend.cpython-312.pyc,, +jax/experimental/colocated_python/__pycache__/serialization.cpython-312.pyc,, +jax/experimental/colocated_python/api.py,sha256=wVcPWNFmwKL-NdmtzrK2vzhCndf90VmME-gkqnbnm_A,4455 +jax/experimental/colocated_python/func.py,sha256=rUwSmbLuA_lVE3mB-KI-kWU0t1zuNXHzgcu6TI0cJ_A,17353 +jax/experimental/colocated_python/func_backend.py,sha256=lXN-FRbWIWezsICyIc3QYwjpF9-tYgZV1Ut7TBN_dpE,1373 +jax/experimental/colocated_python/obj.py,sha256=N_KEQff3d9vzuX5EGkM4Z8rPn6lGEDPNFrTIqcesQ70,5636 +jax/experimental/colocated_python/obj_backend.py,sha256=50I4Ttb17qRk7IUrtufYMNlXqyl4KY6bBc61lGQBWfM,2283 +jax/experimental/colocated_python/serialization.py,sha256=DObZGJ-in5JHA4YKsBpshXhAcbtN3iLZzSlxQ-kgzNE,8987 +jax/experimental/compilation_cache/__init__.py,sha256=9jtOmvvDMLWHLUuqHkvlxcTzvN1yoUxeFmRAxYu7lMw,581 +jax/experimental/compilation_cache/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/compilation_cache/__pycache__/compilation_cache.cpython-312.pyc,, +jax/experimental/compilation_cache/compilation_cache.py,sha256=OIZLvS1c3Yw_EbbqlV28pC40g5dPdBB-XDrXnHcT6As,820 +jax/experimental/compute_on.py,sha256=Mdg2n8JtAsrq1ap_PwUPwoqpoCNGO5rjf7T47e_iaAE,644 +jax/experimental/custom_dce.py,sha256=ORRk_kBjbseQ06T_LmLPxYCO7-Rby5U8Erro5U5Gi4A,682 +jax/experimental/custom_partitioning.py,sha256=RlaIvfdM8VqlEJC3FajqCmB_EOHyk6iyfGUgaUyR61g,1054 +jax/experimental/host_callback.py,sha256=Msk8gUwv_UtJckKwsGU0lYTYGpPG2isWCJrxJ8mzb6g,1201 +jax/experimental/jax2tf/__init__.py,sha256=ZqsPlkalGAkzdTwRIutfW1k8NmOHzJn6kfIB1A98pdw,944 +jax/experimental/jax2tf/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/jax2tf/__pycache__/call_tf.cpython-312.pyc,, +jax/experimental/jax2tf/__pycache__/impl_no_xla.cpython-312.pyc,, +jax/experimental/jax2tf/__pycache__/jax2tf.cpython-312.pyc,, +jax/experimental/jax2tf/call_tf.py,sha256=pE4kpi_9JhPO64j3HwVVSIDp1HJLtzKlDdTEb43xV8w,28939 +jax/experimental/jax2tf/impl_no_xla.py,sha256=zi-U4UaZ7xVJ_Y9gmhHn8evKRX4_6SKJM33INEDucLY,54479 +jax/experimental/jax2tf/jax2tf.py,sha256=AXQlfMiqCRu8c2Jm163q3qVl9LOVBoecZSwWzUILfoY,145513 +jax/experimental/jet.py,sha256=qCQiv4k2XoRKOoLWgRGZYgwskBAWuTPqMSGx8zKhgXI,27322 +jax/experimental/key_reuse/__init__.py,sha256=5CjqLFSLnAhm_YyrowsWA48ENwxcvcD5KQrNQJTgLpQ,1688 +jax/experimental/key_reuse/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/key_reuse/__pycache__/_core.cpython-312.pyc,, +jax/experimental/key_reuse/_core.py,sha256=10LBbkl-_vUqYSEI7a2s-su86fIS7ORnA9c8foagr2o,23103 +jax/experimental/layout.py,sha256=ICtPXKjsJcDSmfF7YD8Gr3PSIAIJQJAj57hb76Ik71o,777 +jax/experimental/mesh_utils.py,sha256=Sf5ivjPuZ_u0ufQ38MLmhbEFnlIMs4SHd6lGXWQJgQY,923 +jax/experimental/mosaic/__init__.py,sha256=-MnUIUUmkSaNkO5bOpPdXrcTnKVWt9ModYX4cnlq9LY,883 +jax/experimental/mosaic/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/mosaic/__pycache__/dialects.cpython-312.pyc,, +jax/experimental/mosaic/dialects.py,sha256=eYxSlw_cu_8usVXcEA3f-cqmlxDUwcTiqLiqNAgWWfs,769 +jax/experimental/mosaic/gpu/__init__.py,sha256=YP7xRHpKa_ueEtHN6I3VjBeyW7kwfRc0NsuRDVNDCn0,3467 +jax/experimental/mosaic/gpu/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/core.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/dialect_lowering.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/fragmented_array.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/inference_utils.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/launch_context.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/layout_inference.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/layouts.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/mma_utils.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/profiler.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/tcgen05.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/transform_inference.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/utils.cpython-312.pyc,, +jax/experimental/mosaic/gpu/__pycache__/wgmma.cpython-312.pyc,, +jax/experimental/mosaic/gpu/core.py,sha256=RPtRuxKPfvbF0iekpCT-H6yPV64NnMjHQ402lfrjC8s,33119 +jax/experimental/mosaic/gpu/dialect_lowering.py,sha256=EqtT14rIW0aWJ6cIupGBBKuW1hLLEMVPztFiLNQ8MoU,62202 +jax/experimental/mosaic/gpu/fragmented_array.py,sha256=j-lPCaRMl4DML5KDG9uo9lTdXU6MKr7vf7k5wDce71g,114293 +jax/experimental/mosaic/gpu/inference_utils.py,sha256=a5qX6vpSp8FVLju7QCFypo_Z7Ny5cxnX5MrMW0lKZe0,7716 +jax/experimental/mosaic/gpu/launch_context.py,sha256=lDpM165JZtX4p_VbBXFOtHvegxHbnmU-4nhsWreE1KE,37873 +jax/experimental/mosaic/gpu/layout_inference.py,sha256=jLktgaPC0gjCT2O74qKSWPnarN_V5ggRDXnW3W6GzDY,27589 +jax/experimental/mosaic/gpu/layouts.py,sha256=FAojzJO91tQ_CP_f_WQmmTiozQOMJUKxb_ND7Vb-PCA,6820 +jax/experimental/mosaic/gpu/mma_utils.py,sha256=_Aoyrzdo3FWifCBUsSrlKMGyJ5NfxhLL01o3jlF1WGc,8664 +jax/experimental/mosaic/gpu/profiler.py,sha256=Y5I7eaONisW4DmRGOIlD-nZP6ebtPGmzDOq_SqYnRvw,15532 +jax/experimental/mosaic/gpu/tcgen05.py,sha256=I5x_mRVuOU8bTDR3_2FGYdadQJjfyyPBkb8lzrhWqGE,38907 +jax/experimental/mosaic/gpu/transform_inference.py,sha256=4U61EAMidFdRHuQoCR8exPZzZElOiMjsd4Rz7mwQiiE,17677 +jax/experimental/mosaic/gpu/utils.py,sha256=CHVvgAO23sDE32g88aZvffI39uFwpgsaGpTSv2kRMKA,53470 +jax/experimental/mosaic/gpu/wgmma.py,sha256=9tFPcdZJDfWumGHVHI3hZaBcsE1bH37MuDDyL8lFRG8,16961 +jax/experimental/multihost_utils.py,sha256=oCbJ2BfjfccFPM82eZbC58sMgw_W9zIhPYBpSG7KYdU,21886 +jax/experimental/ode.py,sha256=VmaWgwXaD1N9WspkCJ7pvdbUtYRuGtp4cpQaqJkf__8,10859 +jax/experimental/pallas/__init__.py,sha256=4dP1KYWvPGObgLxtP89scLukBD7DUMsiiGPnhVDUTTA,4303 +jax/experimental/pallas/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/__pycache__/mosaic_gpu.cpython-312.pyc,, +jax/experimental/pallas/__pycache__/tpu.cpython-312.pyc,, +jax/experimental/pallas/__pycache__/triton.cpython-312.pyc,, +jax/experimental/pallas/mosaic_gpu.py,sha256=Gr37TOTqXGhBc4zurUsWfSDVGVtbTGGQAKvJZcnP3m4,4402 +jax/experimental/pallas/ops/__init__.py,sha256=vC8qlznuwgbYeFDJqP8pDUIf2gEKFrCHg3EZYdTkiwM,764 +jax/experimental/pallas/ops/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__init__.py,sha256=mS3YSYUZFIG68T5Zo9CFGkT7wCyWRycnWV4L36CnHYU,581 +jax/experimental/pallas/ops/gpu/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/attention.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/attention_mgpu.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/blackwell_matmul_mgpu.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/collective_matmul_mgpu.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/decode_attention.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/layer_norm.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/paged_attention.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/ragged_dot_mgpu.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/rms_norm.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/__pycache__/softmax.cpython-312.pyc,, +jax/experimental/pallas/ops/gpu/attention.py,sha256=9jJNoBTnzr_yPM5N5Q4DV-J9EYJtqilxG4vjgHH2r7s,23222 +jax/experimental/pallas/ops/gpu/attention_mgpu.py,sha256=2p2WCtiDrMeHN7cn80ui1kdQ2tGVj-cGSRJTxCJgVvc,36296 +jax/experimental/pallas/ops/gpu/blackwell_matmul_mgpu.py,sha256=62e5y4tysd0jOd4UJICqIyEiqUyJ6ENMBaZEHkYi6v4,8453 +jax/experimental/pallas/ops/gpu/collective_matmul_mgpu.py,sha256=AKorrKmQexqSEdNSUKyT1Elu21CVed9QO1Qv7NXh3X4,7646 +jax/experimental/pallas/ops/gpu/decode_attention.py,sha256=1BvVgUAtMZni4kM_pBTjYMl7Lns8Axg4u5-jc7sUen4,17080 +jax/experimental/pallas/ops/gpu/layer_norm.py,sha256=3LL6x4gxSVlMhob33M1-0XUrLaYEo3E4sZe0neY0vE4,11127 +jax/experimental/pallas/ops/gpu/paged_attention.py,sha256=yviTcP15OFIWOu4UtYgT7q9r3BbsuhVbjOJIm546ChQ,16221 +jax/experimental/pallas/ops/gpu/ragged_dot_mgpu.py,sha256=g1KB4Y4aRVuCMd4ZG89ZwWYx_hDmxCNLDQNVJx99V1Q,11406 +jax/experimental/pallas/ops/gpu/rms_norm.py,sha256=LdiTCNLeuTYPu15TFM1VmJypLBeqLitTc-ITa_PwbzY,10027 +jax/experimental/pallas/ops/gpu/softmax.py,sha256=sKeVjcAwN4va31DeFhMO_-ZLkLkGbgOtXucbG7G2GUE,2768 +jax/experimental/pallas/ops/tpu/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/experimental/pallas/ops/tpu/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/__pycache__/all_gather.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/__pycache__/example_kernel.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/__pycache__/flash_attention.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/__pycache__/matmul.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/all_gather.py,sha256=9XXcBpb_pXZGn8EOa-daiO_EJecOLdBtx9QCxCowEL8,5573 +jax/experimental/pallas/ops/tpu/example_kernel.py,sha256=jzsyvU-Lk0PIorE9XCw2NDdqdp8Cn4bqsSe76DBxeEM,802 +jax/experimental/pallas/ops/tpu/flash_attention.py,sha256=faIwM9av0WKRRW3Q1yOmhg2_DDvtMKtsW9LztFIiNPM,49874 +jax/experimental/pallas/ops/tpu/matmul.py,sha256=x-2MCTChhr6BwQMQXzKcRT8PDVQ0ZvPjGxYOCaAgb7g,2717 +jax/experimental/pallas/ops/tpu/megablox/__init__.py,sha256=HRWx7FtM9_17OLitbxwIZp-A9RM61uSL6QAcBGJyw_w,650 +jax/experimental/pallas/ops/tpu/megablox/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/megablox/__pycache__/common.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/megablox/__pycache__/gmm.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/megablox/__pycache__/ops.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/megablox/common.py,sha256=9zg98VzHJh5l4Sf_SKly1nrXFWeWeyKoe7ZSPn6Ht38,1969 +jax/experimental/pallas/ops/tpu/megablox/gmm.py,sha256=PnH6tp1yv31d5QPtedi7oI7sBgqu0iQ2Pm2lJ4EzqTA,27243 +jax/experimental/pallas/ops/tpu/megablox/ops.py,sha256=4Xg3O0bnP5HTWsawS0hAm8mF9HTvRHVK65RlopkA1rw,2903 +jax/experimental/pallas/ops/tpu/paged_attention/__init__.py,sha256=Q6gFLakYVRJDRxxvqq6vmtDYup-edUHZy54j9194JfY,700 +jax/experimental/pallas/ops/tpu/paged_attention/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/paged_attention/__pycache__/paged_attention_kernel.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/paged_attention/__pycache__/quantization_utils.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/paged_attention/__pycache__/util.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/paged_attention/paged_attention_kernel.py,sha256=MRVFNdCdETdHNS1SAAXWV_fufPJHpMsMfSQhiEHKxFQ,22026 +jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py,sha256=5y0QHJo2yDsafF_lgeSO_izChspLHpVOvbFWZ-2d0ss,2556 +jax/experimental/pallas/ops/tpu/paged_attention/util.py,sha256=t1_5K06BjSyQKaa-zqQnJDpW4dX1iQ-URfb_hEUJ53g,3254 +jax/experimental/pallas/ops/tpu/ragged_paged_attention/__init__.py,sha256=XuQq_I5Pn_5EDon__0hWN9NOrOJ3grU3y0qqc8qKSsg,1055 +jax/experimental/pallas/ops/tpu/ragged_paged_attention/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/ragged_paged_attention/__pycache__/kernel.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/ragged_paged_attention/__pycache__/tuned_block_sizes.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/ragged_paged_attention/kernel.py,sha256=t4sYYuwb6-P6TZ3PZsgDYUXrmjC23iVVrmgXHJE4-WA,31994 +jax/experimental/pallas/ops/tpu/ragged_paged_attention/tuned_block_sizes.py,sha256=_QZBjMU41ln_i9Fo6QSHjclzxCd0f4xAdiTTy-39iXU,25959 +jax/experimental/pallas/ops/tpu/random/__init__.py,sha256=gEMCMS8LKTvoFm0t7khiAnQg78EDUuMI-fvTvw250eo,682 +jax/experimental/pallas/ops/tpu/random/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/random/__pycache__/philox.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/random/__pycache__/prng_utils.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/random/__pycache__/threefry.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/random/philox.py,sha256=ySUyKx2lromSM1Wez6nRYEuzy2srOzAGb8KbiMoeuUo,7485 +jax/experimental/pallas/ops/tpu/random/prng_utils.py,sha256=CH1W4SuTJtdKNVA-7G64qf_RwtJM7zteTuQsfsRieMk,1771 +jax/experimental/pallas/ops/tpu/random/threefry.py,sha256=0HyU9Y_PUpAe_4ypcaqmGgDHeZRmEwsPVOnFhNho18I,4330 +jax/experimental/pallas/ops/tpu/splash_attention/__init__.py,sha256=8y556G1Vpmglvw8FbNzeB4x6QK6PLkKUBnMsL4vleNs,2738 +jax/experimental/pallas/ops/tpu/splash_attention/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/splash_attention/__pycache__/splash_attention_kernel.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/splash_attention/__pycache__/splash_attention_mask.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/splash_attention/__pycache__/splash_attention_mask_info.cpython-312.pyc,, +jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py,sha256=2par2bNjSjBCTHl8LExI1T1yuYt9VAYu74nbfcBYKfY,75020 +jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py,sha256=ncsRlbb-oHneOkZqkSpOB6r7V0p_lZY60zBEsar364c,16307 +jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask_info.py,sha256=UTG7D_TWynzs4oQS82DQE9ydLrQ-z372PvrfMZ2h5cQ,40286 +jax/experimental/pallas/tpu.py,sha256=dQZUek8Z-FyMXteRONkj-KvGW-k-SAQz3IlfBk0FsN8,5157 +jax/experimental/pallas/triton.py,sha256=HWFJ51-oRjRLY5fiMmlX2DwvE2hT6--7ghBzIMv1Fgo,1459 +jax/experimental/pjit.py,sha256=2Qi4A4tKn1p6pjxysiCY5UAsfQq_KVZ7QpMX3gRJw30,749 +jax/experimental/profiler.py,sha256=Rxlgbb4TPJsfeWXwLYG58gW0PCqBjDVWswlCCLr7fBg,1413 +jax/experimental/rnn.py,sha256=q__NeQnA8uZspzC5zFU5a-593i3VOEAbrRmsiJwYEfU,20203 +jax/experimental/roofline/__init__.py,sha256=ftyNH95ANQHFYSq9hsweKfJNP47sfipMm-3XFsr32yw,1260 +jax/experimental/roofline/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/roofline/__pycache__/roofline.cpython-312.pyc,, +jax/experimental/roofline/__pycache__/rooflines.cpython-312.pyc,, +jax/experimental/roofline/roofline.py,sha256=cMzOBEADpaY4jDtivkAGDCTIgfsdPvm4hdQYkKMGjfY,11167 +jax/experimental/roofline/rooflines.py,sha256=aTQzp55zF-mpfB682LsrpbN0a88Y-35NIRKzNNcv8eI,20404 +jax/experimental/serialize_executable.py,sha256=hiR59Fn_4PhECvMXftzwT5lHKx2_xSS9__OAl_RQQu4,4228 +jax/experimental/shard.py,sha256=xTXar7eZIDvVAXyXUdgCPaqHEUmbl8zPh6iF5oLt380,696 +jax/experimental/shard_alike.py,sha256=dbrhVCnWEX39TsQYRyGoClFByDmqtmDlKGtOmlT-m2M,646 +jax/experimental/shard_map.py,sha256=zkBPC3rKW787yjzwqz0vjc_2GHpRI18CuK_ocmo5rlg,4427 +jax/experimental/source_mapper/__init__.py,sha256=g5b_71QFD84RscRTmCDm7l_TfUYkcW6gZuRd8rgFg9Q,1698 +jax/experimental/source_mapper/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/source_mapper/__pycache__/common.cpython-312.pyc,, +jax/experimental/source_mapper/__pycache__/generate_map.cpython-312.pyc,, +jax/experimental/source_mapper/__pycache__/hlo.cpython-312.pyc,, +jax/experimental/source_mapper/__pycache__/jaxpr.cpython-312.pyc,, +jax/experimental/source_mapper/__pycache__/mlir.cpython-312.pyc,, +jax/experimental/source_mapper/common.py,sha256=2wh5nZMvCdhjDBQKw539R5WTnmFJWNzMBRgaZxqI__s,2481 +jax/experimental/source_mapper/generate_map.py,sha256=rCr8YPEZI1OAjw_GZFUndUkhgVVS7gcv6dDVszTey3w,2102 +jax/experimental/source_mapper/hlo.py,sha256=ItS2ytK1D4cBQOZsap0UzyWA-saoI_T_fWH2DVoMSFA,4112 +jax/experimental/source_mapper/jaxpr.py,sha256=PXa9zMzP2_fD_0vxo8Za-mw21pXp2Aao6IQkQIqmoJU,2595 +jax/experimental/source_mapper/mlir.py,sha256=U2YSWC9tp_DlnsrRzuzsAU7W2PY6ZwtWedHiuMSTQ5M,4686 +jax/experimental/sparse/__init__.py,sha256=iYfDK0sdq3ErijcE7Va7cRjEHjzuJ3ykCwnHSYxNMPs,11186 +jax/experimental/sparse/__pycache__/__init__.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/_base.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/_lowerings.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/ad.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/api.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/bcoo.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/bcsr.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/coo.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/csr.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/linalg.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/nm.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/random.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/test_util.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/transform.cpython-312.pyc,, +jax/experimental/sparse/__pycache__/util.cpython-312.pyc,, +jax/experimental/sparse/_base.py,sha256=qyiBgPa12uwS1nLpSDw8dTD1VEq0v9P2_CGTNyPCA_g,3239 +jax/experimental/sparse/_lowerings.py,sha256=nNviA0Ed0Dq-J_mRF1us4DQ4GUP69Gu3WBFzuSbLlWI,13334 +jax/experimental/sparse/ad.py,sha256=zJLXiDufoAVcLTHdFitEXdbQUM_XtDiJoIktwDVuNZU,7789 +jax/experimental/sparse/api.py,sha256=DrqEZmlIr6n6kpJjNli9J_rqMX3UO3sPPW7E8_t-u4g,6596 +jax/experimental/sparse/bcoo.py,sha256=D2n0P_IQOqOhyF0f2jWIpZeDA9EgFpK3G-V7YICHm-g,129450 +jax/experimental/sparse/bcsr.py,sha256=qSvCId7ZjWHNZNDVpEPdc_dTnB9446V5xsMiIFdpAxs,41314 +jax/experimental/sparse/coo.py,sha256=_R22aml359eVXXBA_3BP4mQfrJAfmdCtD_BzCDLy2vw,24165 +jax/experimental/sparse/csr.py,sha256=dhOQNlU57XwMZom4n8VVfhc8t4TP1OxPcwtDurK0il0,24332 +jax/experimental/sparse/linalg.py,sha256=Zk0pMWAwHMExcC2VaAu8Pelr1rRcVW7K2G1io_XKh0Q,23411 +jax/experimental/sparse/nm.py,sha256=ypXA8WaigylNbaRqJRlfXyurJC00f41VF1jxqUAiI3I,8568 +jax/experimental/sparse/random.py,sha256=o_g5_F8_EN4vmncmIkFKChU5uX4L3MVM6z-_qdoYUKI,3887 +jax/experimental/sparse/test_util.py,sha256=hBw1SDgjVL2KkadjSdvIs5DcHqmdrtQHTHUCwj-MBfw,9433 +jax/experimental/sparse/transform.py,sha256=HzxzEfAwUqwrpFXPx8ahQlARBZLOxWR4XBf8_9L_cuk,37484 +jax/experimental/sparse/util.py,sha256=zb8BrK9aG5DC9ubS1ZmjSKfLhnnGVKA5ydy9i0hKzA8,4337 +jax/experimental/topologies.py,sha256=YnSqioiXZqwsX-WzVhHVUO44lAib22-TkfIzC0KRfLA,2083 +jax/experimental/transfer.py,sha256=E8dFkOjF0jnpEYk6--VEdnozMEcC-ntdSG-GkKln9eI,2327 +jax/experimental/x64_context.py,sha256=XXTsGH7SavrMuT1hXzThT8f04SAFWdrhjZiyfEAaqVU,2394 +jax/experimental/xla_metadata.py,sha256=YoNAzPbdARYfGzGTUVoxTfHG9dDrobUvWaPI4uvHRJk,658 +jax/export.py,sha256=OzLiZq2zwjC4gDUs-3VcHVFF5IUZtIhMaaTdnV89qIA,1537 +jax/extend/__init__.py,sha256=tFbMTUdo-HwWjrmedD-df0hndkPkqGWPuZT_Tb-Fspc,1600 +jax/extend/__pycache__/__init__.cpython-312.pyc,, +jax/extend/__pycache__/backend.cpython-312.pyc,, +jax/extend/__pycache__/ffi.cpython-312.pyc,, +jax/extend/__pycache__/ifrt_programs.cpython-312.pyc,, +jax/extend/__pycache__/linear_util.cpython-312.pyc,, +jax/extend/__pycache__/random.cpython-312.pyc,, +jax/extend/__pycache__/source_info_util.cpython-312.pyc,, +jax/extend/backend.py,sha256=WOpw4RNsuCR_EMkNrikaWrtyUSp200m09z7QnXr2wgQ,1183 +jax/extend/core/__init__.py,sha256=o_q4S8jW_Tc0986SMqpjcifigZq-Ez2OhFZo6aBLwzM,1036 +jax/extend/core/__pycache__/__init__.cpython-312.pyc,, +jax/extend/core/__pycache__/primitives.cpython-312.pyc,, +jax/extend/core/primitives.py,sha256=GaZ_MirytqtZR9haKV_xv44I3TDS4Da9ZXf7a9OhZME,6299 +jax/extend/ffi.py,sha256=31OhFUi5t8Msov6VnqpTj8U8bpDe9V746tMb1enGh9w,1783 +jax/extend/ifrt_programs.py,sha256=TCWvR-K8nHQ9PuUNoMWVAfEuYsutTNrefKwLg4AIRao,787 +jax/extend/linear_util.py,sha256=xag9NUqPndR7mh3NDQ4TluFpc6hFFd4r7Q5LarAFqvY,1592 +jax/extend/mlir/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/extend/mlir/__pycache__/__init__.cpython-312.pyc,, +jax/extend/mlir/__pycache__/ir.cpython-312.pyc,, +jax/extend/mlir/__pycache__/passmanager.cpython-312.pyc,, +jax/extend/mlir/dialects/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/extend/mlir/dialects/__pycache__/__init__.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/arith.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/builtin.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/chlo.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/func.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/math.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/memref.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/scf.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/sdy.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/sparse_tensor.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/stablehlo.cpython-312.pyc,, +jax/extend/mlir/dialects/__pycache__/vector.cpython-312.pyc,, +jax/extend/mlir/dialects/arith.py,sha256=Au6mT9C4OrdpaGGwJ4_bauTFjGFQKF7wilv62mxzP1E,643 +jax/extend/mlir/dialects/builtin.py,sha256=Y1QDRes-Arh7uBLJpySSqygBwUovalHyBq71m3uPbiQ,645 +jax/extend/mlir/dialects/chlo.py,sha256=sfxvYEEBgGVd8fDXOlyfGtOLCCAW0xquLrSlTJFA81A,642 +jax/extend/mlir/dialects/func.py,sha256=sCnRWz5gKtZ8Cf5NpeCIQ0zVh-nM6H95ttjzksTRrXk,642 +jax/extend/mlir/dialects/math.py,sha256=G2gFkarEChMUEjv-vjDc4O09e-1orPhh_zHJhjbPPRQ,642 +jax/extend/mlir/dialects/memref.py,sha256=nPR3oOrsENZ-mHjHKFSD48PpQMZHsVLfUVCwomBhv_w,644 +jax/extend/mlir/dialects/scf.py,sha256=hmcJIF7RUqzeeP_NIOampnvCB5Jb6T8Xex4T03IeKrI,641 +jax/extend/mlir/dialects/sdy.py,sha256=4dpcOKEHHkDh6cXdyEm2VGE9W-8701MD9egZmWDlkRM,641 +jax/extend/mlir/dialects/sparse_tensor.py,sha256=TaFY58y273rRITr8WxSM7LB1-sTAa03dCAjH4F8ZWaE,651 +jax/extend/mlir/dialects/stablehlo.py,sha256=AbJQc7zghgrJh-BgRB31L7iHrNLVaEk4AELejcq7QiE,647 +jax/extend/mlir/dialects/vector.py,sha256=xP03nScJg-t7olD8_P8SiFGVnV6Qi0Fwn9uGK0MHOXI,644 +jax/extend/mlir/ir.py,sha256=1IirtLROpBL2nVDNSlP_3c6u09xXaKLqBkzF1JtmGz4,631 +jax/extend/mlir/passmanager.py,sha256=1rfuCocMdFlx6It95ynBCP-8JC5xEAEG7rBdLJ7SpFI,640 +jax/extend/random.py,sha256=w1OM6RCcGwmzIr9bdGJJTNKIcMO4ypXbzmeEORlBHjQ,1083 +jax/extend/source_info_util.py,sha256=IxZYjLDlwOH1uE3A_vc25dy25QZ6FABMb4RqrkiA5hU,1215 +jax/ffi.py,sha256=S4EjUxeohrl-Kmmnu8rykPCTxMl2LAxGdaerWLhd5ac,1052 +jax/flatten_util.py,sha256=jGwQUB80s2jr78XuEaT1_OP2OUyVm8Pk-yAQq-C1SsY,645 +jax/image/__init__.py,sha256=cthOdx-HsZ6SgvW19tdNCDHmC4Proc8da1hY1hRztTI,1027 +jax/image/__pycache__/__init__.cpython-312.pyc,, +jax/interpreters/__init__.py,sha256=HNgKpgKpz4svFyTlHE9wMrDp5iQtg6XeeUshYBOnRko,690 +jax/interpreters/__pycache__/__init__.cpython-312.pyc,, +jax/interpreters/__pycache__/ad.cpython-312.pyc,, +jax/interpreters/__pycache__/batching.cpython-312.pyc,, +jax/interpreters/__pycache__/mlir.cpython-312.pyc,, +jax/interpreters/__pycache__/partial_eval.cpython-312.pyc,, +jax/interpreters/__pycache__/pxla.cpython-312.pyc,, +jax/interpreters/__pycache__/xla.cpython-312.pyc,, +jax/interpreters/ad.py,sha256=p0gJFj9VvrsZbZavI-xg00Y-PzEu5Rw_6d3upq5u92Y,2759 +jax/interpreters/batching.py,sha256=QqKOP4uX4F1PSf96ZrXi6x3DOIrU8wyWqXGTlt1nC2g,2574 +jax/interpreters/mlir.py,sha256=H_cKoKAmfXBH7FEmMRthJ7M2Hjs5HeD4c-FkLFHLb1o,3411 +jax/interpreters/partial_eval.py,sha256=DJBwBbcrQ7Wrj9EA_TyFNsiq6ZSymxqYpGgPZscdvvI,3924 +jax/interpreters/pxla.py,sha256=VN0Mlb4IreJ9Tqez8i-QWn1EXVcrDWTLPeioTkeL-qE,1801 +jax/interpreters/xla.py,sha256=JD6CBHHS9gTmO83age6Xwe9CxuoHLlYYBoD3RxyL41U,1584 +jax/lax/__init__.py,sha256=0fm8wqN5TQHHNqzs5vlyEV77RplzZdp-JL4Km0tPr_0,12449 +jax/lax/__pycache__/__init__.cpython-312.pyc,, +jax/lax/__pycache__/linalg.cpython-312.pyc,, +jax/lax/linalg.py,sha256=I9ZzEhenoEzcBnfnU-jCjIspi-aOXHc5KJY3t_45uWs,1631 +jax/lib/__init__.py,sha256=wy3yxhlsb9k2th9Dfsr6eS59L2qLIxH_IoTM4cPfx3M,774 +jax/lib/__pycache__/__init__.cpython-312.pyc,, +jax/lib/__pycache__/xla_bridge.cpython-312.pyc,, +jax/lib/__pycache__/xla_client.cpython-312.pyc,, +jax/lib/__pycache__/xla_extension.cpython-312.pyc,, +jax/lib/xla_bridge.py,sha256=NtW-LD_Dh_TkdCT-19CZ91nvJPWy27aUzCon8ij3CWU,1246 +jax/lib/xla_client.py,sha256=UEViLrEA2wi-MUO6ZYNF22r4yboy9TKekN645jEBkrM,5094 +jax/lib/xla_extension.py,sha256=J5ldZNiB9BxU8wGkl1rWNUVTAGZP4jHSkZiMuVuOXf8,4428 +jax/monitoring.py,sha256=xWZF_CyFg7Vv7MYmIyb3JWNA-AwsvIm9oc-MbGX4Bbw,1415 +jax/nn/__init__.py,sha256=vC3v2Eg_WOW8kJWDzbpKS35jDaabCP9iwnOyV1HQEJ8,1730 +jax/nn/__init__.pyi,sha256=GwG0FR6g3QtjFcmSM9jsARRM2QwXBNv2hRgaKkMPi9I,3833 +jax/nn/__pycache__/__init__.cpython-312.pyc,, +jax/nn/__pycache__/initializers.cpython-312.pyc,, +jax/nn/initializers.py,sha256=finfAJmOEZdPIzY2roSIBTOmC4rKEW-rchpH9d6Dc2g,1469 +jax/numpy/__init__.py,sha256=-OT1qZuRyMi0dhKSfQ7DC1zkRfng2cNBh4AfqVnkuFY,12228 +jax/numpy/__init__.pyi,sha256=sF36SyNjqOZNDV0KuB9RdJl_05VgP4p9mYU5xTYTY-M,44304 +jax/numpy/__pycache__/__init__.cpython-312.pyc,, +jax/numpy/__pycache__/fft.cpython-312.pyc,, +jax/numpy/__pycache__/linalg.cpython-312.pyc,, +jax/numpy/fft.py,sha256=iNatBIYRSwpXquPSgtNRMe6-dhbKkv2yoH6UJ6PFoGM,1084 +jax/numpy/linalg.py,sha256=bnzLmLpLYSDRIICkjCEsH1WmA7wNOdSKhmO25gPvTqI,1419 +jax/ops/__init__.py,sha256=VIAczIKYAFWawHdNmLmptUYnFQiBwHwlsa4LpgGEbIc,870 +jax/ops/__pycache__/__init__.cpython-312.pyc,, +jax/profiler.py,sha256=_aALYj1kkwBxGCHmiIzcdafpIBoJV2M5Kqw7VBNXQME,1387 +jax/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jax/random.py,sha256=-1oFQ0v1HFzwvFTipdl1JQVqsk8dXRJe2ZH4xTyU51g,9434 +jax/scipy/__init__.py,sha256=DXszF0t3ZbfDeoFEP_GyBb0OOr6F-4yqsZzmen7pY58,1474 +jax/scipy/__pycache__/__init__.cpython-312.pyc,, +jax/scipy/__pycache__/fft.cpython-312.pyc,, +jax/scipy/__pycache__/integrate.cpython-312.pyc,, +jax/scipy/__pycache__/linalg.cpython-312.pyc,, +jax/scipy/__pycache__/ndimage.cpython-312.pyc,, +jax/scipy/__pycache__/signal.cpython-312.pyc,, +jax/scipy/__pycache__/special.cpython-312.pyc,, +jax/scipy/cluster/__init__.py,sha256=sgIbEEx62OubzDO36E3EkqjbYY_3qsErPOTQE6lsj5E,768 +jax/scipy/cluster/__pycache__/__init__.cpython-312.pyc,, +jax/scipy/cluster/__pycache__/vq.cpython-312.pyc,, +jax/scipy/cluster/vq.py,sha256=lkLSlkWFi6TLjwuzTX7hVSiC1IkCYd3OWgn8YtIAJd0,776 +jax/scipy/fft.py,sha256=PVKQ4r-vl4J9Ct6LrhZWZ7jMF7frIXggiO98Bh0oVIE,809 +jax/scipy/integrate.py,sha256=H9iq7YKgsZQ1d0SUvGcgPnEgD1TBdWJXHYjfUOGzT8Y,777 +jax/scipy/interpolate/__init__.py,sha256=RI5oUXPC-8tKmYURnnrnA-e1LDbnNVOVVqkGSpagEBM,760 +jax/scipy/interpolate/__pycache__/__init__.cpython-312.pyc,, +jax/scipy/linalg.py,sha256=GXC1BgLMztvwRMxddJhvJS3obG81HLQ0OJFVt_Iv4V8,1370 +jax/scipy/ndimage.py,sha256=ei-ZfRiDXrlY4nYC1SFL7nnGHFrC_emD_NAicGhH4vU,788 +jax/scipy/optimize/__init__.py,sha256=cAw1rT1e0Mu-22vBUuJb6Q-CQF8fbIUBlKYpynB7e2s,822 +jax/scipy/optimize/__pycache__/__init__.cpython-312.pyc,, +jax/scipy/signal.py,sha256=nW4h017jShZBLL3J2NMhLwlOv46wK1MhEPeKlPTj710,975 +jax/scipy/sparse/__init__.py,sha256=ugltlihEjwgorQxgfziHC-03UeYy4JzdQmTxrt1cnTo,757 +jax/scipy/sparse/__pycache__/__init__.cpython-312.pyc,, +jax/scipy/sparse/__pycache__/linalg.cpython-312.pyc,, +jax/scipy/sparse/linalg.py,sha256=wpjjS1G1UNISyhZVFoJMMgIkqs-L8ASdvtQAbvEBsuk,810 +jax/scipy/spatial/__init__.py,sha256=t5wRc_z8eIDwV0votvqn8WtOUEd53ZNf_J4VRYLJepc,581 +jax/scipy/spatial/__pycache__/__init__.cpython-312.pyc,, +jax/scipy/spatial/__pycache__/transform.cpython-312.pyc,, +jax/scipy/spatial/transform.py,sha256=cm7lKi8aUepI3cOwTnjrldhFh7hBv89CR_m3pFj3r2o,802 +jax/scipy/special.py,sha256=s-0P9YKfZmmTze9BVkrr125COCf6H17G-GFvsmzvCOc,2406 +jax/scipy/stats/__init__.py,sha256=ssiwAm2AdZ81MPMM11015yMNogj4DGsNfWfq507yhlo,1995 +jax/scipy/stats/__pycache__/__init__.cpython-312.pyc,, +jax/scipy/stats/__pycache__/bernoulli.cpython-312.pyc,, +jax/scipy/stats/__pycache__/beta.cpython-312.pyc,, +jax/scipy/stats/__pycache__/betabinom.cpython-312.pyc,, +jax/scipy/stats/__pycache__/binom.cpython-312.pyc,, +jax/scipy/stats/__pycache__/cauchy.cpython-312.pyc,, +jax/scipy/stats/__pycache__/chi2.cpython-312.pyc,, +jax/scipy/stats/__pycache__/dirichlet.cpython-312.pyc,, +jax/scipy/stats/__pycache__/expon.cpython-312.pyc,, +jax/scipy/stats/__pycache__/gamma.cpython-312.pyc,, +jax/scipy/stats/__pycache__/gennorm.cpython-312.pyc,, +jax/scipy/stats/__pycache__/geom.cpython-312.pyc,, +jax/scipy/stats/__pycache__/laplace.cpython-312.pyc,, +jax/scipy/stats/__pycache__/logistic.cpython-312.pyc,, +jax/scipy/stats/__pycache__/multinomial.cpython-312.pyc,, +jax/scipy/stats/__pycache__/multivariate_normal.cpython-312.pyc,, +jax/scipy/stats/__pycache__/nbinom.cpython-312.pyc,, +jax/scipy/stats/__pycache__/norm.cpython-312.pyc,, +jax/scipy/stats/__pycache__/pareto.cpython-312.pyc,, +jax/scipy/stats/__pycache__/poisson.cpython-312.pyc,, +jax/scipy/stats/__pycache__/t.cpython-312.pyc,, +jax/scipy/stats/__pycache__/truncnorm.cpython-312.pyc,, +jax/scipy/stats/__pycache__/uniform.cpython-312.pyc,, +jax/scipy/stats/__pycache__/vonmises.cpython-312.pyc,, +jax/scipy/stats/__pycache__/wrapcauchy.cpython-312.pyc,, +jax/scipy/stats/bernoulli.py,sha256=llkwAlvFH0qNU1BHdxn9CXXOBAPg0ffnbW_WQQ4LKVg,819 +jax/scipy/stats/beta.py,sha256=5UIf6_JtqVZfAl1dDc2N3K8SkG0OV1bBkC3vWpY8-Hs,851 +jax/scipy/stats/betabinom.py,sha256=5T6965_jHQxG4oR2YocPQRKcDo5AGxkhIyrk2iz-Kk0,792 +jax/scipy/stats/binom.py,sha256=XGO5jDk3nRRgGwHQU6KEl9_kQ5X2qF-2TLgvm3ZUvvs,659 +jax/scipy/stats/cauchy.py,sha256=MfAMnK9eG2wcutA5FVAyhU6iVYSSNgzI1XFT1xtNIfg,881 +jax/scipy/stats/chi2.py,sha256=f-6i-0twBiOrak26tc7bEnWgOODA3iFwEFgi_An9udo,851 +jax/scipy/stats/dirichlet.py,sha256=FUHSEmXKmVUneXuxgaIZM28s6GxlusbymdRYEPnDiUE,792 +jax/scipy/stats/expon.py,sha256=YClw5PcqAXgq3VD4ukZ19HfTmRCMtrGk6E2BpXb6U9E,866 +jax/scipy/stats/gamma.py,sha256=TvP4BE8MROMxQL6YNDQIHSaZCfxumHkjGbCXw9O2iUo,852 +jax/scipy/stats/gennorm.py,sha256=hqwz7ueAgdtzs1v0LHTTro2PLKRDjWxTFuu9jXwXOyI,804 +jax/scipy/stats/geom.py,sha256=pdp2tCdXOa3CUWyKJCyrFrMR7TBX0La5tVI4ALAETI4,787 +jax/scipy/stats/laplace.py,sha256=7Lap3E3_neHYpG5mUFlYxZnwAT1J8mTrNPnn8BSEGrA,804 +jax/scipy/stats/logistic.py,sha256=IoHe_TMB0CH5EMAXjmqRMP8LjR4lTS_x9Zf4K7K5e2g,845 +jax/scipy/stats/multinomial.py,sha256=hfRYQL_GeszF4sJXx5Y416JgXoXVw5vxtQIt1NmkCDU,794 +jax/scipy/stats/multivariate_normal.py,sha256=YYqtLLZmjsLWeCIoDpxUk-rHde-g9unfo6ofg44nSBQ,802 +jax/scipy/stats/nbinom.py,sha256=hWMMt7D_rLRtiGjlpHcbOXJF03BfA3v9Cu972twYKCY,660 +jax/scipy/stats/norm.py,sha256=qNMz53OSiWOZGt6TZkJZvWAFocdUMUu-DsysM9kg2K4,879 +jax/scipy/stats/pareto.py,sha256=xOqP9JMLAYdVXMFpCfCoRqxJNXVeWfJXkEqpOsrUjHc,789 +jax/scipy/stats/poisson.py,sha256=Guu0WOaGAwtujTTWVlBZiBg2fLu4JOjx0fumX4m4Ems,804 +jax/scipy/stats/t.py,sha256=kPmOWYVodYyD6cTxzX98qNxiFeWpDHBM1WwrdK5Ztoc,784 +jax/scipy/stats/truncnorm.py,sha256=q5aSLcidwhZqFi9sNjqvFF9RxT_YLcYBMW2DofDoE5M,855 +jax/scipy/stats/uniform.py,sha256=KCmUJttnFPbr-_ECG7O5xd-fy8CqvysIhepltRj_6SU,818 +jax/scipy/stats/vonmises.py,sha256=NYGQbIKES93vjVumCkF6IihydEhrhH7JMaJFmGDfCwM,791 +jax/scipy/stats/wrapcauchy.py,sha256=pcs6O0cdJTyhsN6LGTOxBm4TyuKkm3HRIdxfZVoz8r4,793 +jax/sharding.py,sha256=PHXvo9WjCtsXIzX5wAdpPCX8031W91yoiZjMto4VJs4,2072 +jax/stages.py,sha256=M5yM7y1ubMHqBm6KJor_kJGnJDH8UXVoudgZ15cvaJI,1308 +jax/test_util.py,sha256=DVJAPxzZMKdM01Nhx7s2kPe5mcdv8ZL8a_37sgyZPUs,835 +jax/tools/__init__.py,sha256=BTyMF0yh0M75AsNwF_0NSd5gHnIVpxhsLznsWkxu3XQ,581 +jax/tools/__pycache__/__init__.cpython-312.pyc,, +jax/tools/__pycache__/colab_tpu.cpython-312.pyc,, +jax/tools/__pycache__/jax_to_ir.cpython-312.pyc,, +jax/tools/__pycache__/pgo_nsys_converter.cpython-312.pyc,, +jax/tools/colab_tpu.py,sha256=IPEQ1HZB4xW0MRSPGDeFAw9GoMFaphNQ0kLRIwGypmo,890 +jax/tools/jax_to_ir.py,sha256=fFvvhbWBsHJel1cBJJOBhLeacpk-OJVJzRE-hZHxK90,8711 +jax/tools/pgo_nsys_converter.py,sha256=BCxXmHnvcorM62adEbOFNYcsnTyv-Hkqnf4K7lo_wt4,3413 +jax/tree.py,sha256=cqFvisf_oyq5BWE18iwtiJc_PQpZ6O1FbZqAOiVfB8M,1106 +jax/tree_util.py,sha256=XPwdmupZXBqEdw6EP2oM8Er6uyGv6Hi4ueV_W99g9CM,3676 +jax/typing.py,sha256=zijMsLWzFOqn-u8__DbGxxI7MyjePxpUwU5nFE_P78Y,3319 +jax/util.py,sha256=Ny5dah5vtOF0NJtr2UMJlxSJKl9AvdIX_vsbxo-zbho,4486 +jax/version.py,sha256=q0iokoxglukg_Be9ST0SfrrRJipJZXBlt8AYrTuR4DI,6725 diff --git a/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9c3ae630da0f5fa7185edeb5c45a2df4a75b0f5d --- /dev/null +++ b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (76.0.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/top_level.txt b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e2f394bff9ab7d41eccc7a1f9e61322304d4c597 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax-0.6.2.dist-info/top_level.txt @@ -0,0 +1 @@ +jax diff --git a/python_embeded/Lib/site-packages/jax/__init__.py b/python_embeded/Lib/site-packages/jax/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18465c28bc8445b0e4df2d8b2261c2470ff79139 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/__init__.py @@ -0,0 +1,227 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Set default C++ logging level before any logging happens. +import os as _os +_os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '1') +del _os + +# Import version first, because other submodules may reference it. +from jax.version import __version__ as __version__ +from jax.version import __version_info__ as __version_info__ + +# Set Cloud TPU env vars if necessary before transitively loading C++ backend +from jax._src.cloud_tpu_init import cloud_tpu_init as _cloud_tpu_init +try: + _cloud_tpu_init() +except Exception as exc: + # Defensively swallow any exceptions to avoid making jax unimportable + from warnings import warn as _warn + _warn(f"cloud_tpu_init failed: {exc!r}\n This a JAX bug; please report " + f"an issue at https://github.com/jax-ml/jax/issues") + del _warn +del _cloud_tpu_init + +# Force early import, allowing use of `jax.core` after importing `jax`. +import jax.core as _core +del _core + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.basearray import Array as Array +from jax import tree as tree +from jax import typing as typing + +from jax._src.config import ( + config as config, + enable_checks as enable_checks, + debug_key_reuse as debug_key_reuse, + check_tracer_leaks as check_tracer_leaks, + checking_leaks as checking_leaks, + enable_custom_prng as enable_custom_prng, + softmax_custom_jvp as softmax_custom_jvp, + enable_custom_vjp_by_custom_transpose as enable_custom_vjp_by_custom_transpose, + debug_nans as debug_nans, + debug_infs as debug_infs, + log_compiles as log_compiles, + no_tracing as no_tracing, + explain_cache_misses as explain_cache_misses, + default_device as default_device, + default_matmul_precision as default_matmul_precision, + default_prng_impl as default_prng_impl, + numpy_dtype_promotion as numpy_dtype_promotion, + numpy_rank_promotion as numpy_rank_promotion, + jax2tf_associative_scan_reductions as jax2tf_associative_scan_reductions, + legacy_prng_key as legacy_prng_key, + threefry_partitionable as threefry_partitionable, + transfer_guard as transfer_guard, + transfer_guard_host_to_device as transfer_guard_host_to_device, + transfer_guard_device_to_device as transfer_guard_device_to_device, + transfer_guard_device_to_host as transfer_guard_device_to_host, +) +from jax._src.core import ensure_compile_time_eval as ensure_compile_time_eval +from jax._src.environment_info import print_environment_info as print_environment_info + +from jax._src.lib import xla_client as _xc +Device = _xc.Device +del _xc + +from jax._src.core import typeof as typeof +from jax._src.api import effects_barrier as effects_barrier +from jax._src.api import block_until_ready as block_until_ready +from jax._src.ad_checkpoint import checkpoint_wrapper as checkpoint # noqa: F401 +from jax._src.ad_checkpoint import checkpoint_policies as checkpoint_policies +from jax._src.api import clear_caches as clear_caches +from jax._src.api import copy_to_host_async as copy_to_host_async +from jax._src.custom_derivatives import closure_convert as closure_convert +from jax._src.custom_derivatives import custom_gradient as custom_gradient +from jax._src.custom_derivatives import custom_jvp as custom_jvp +from jax._src.custom_derivatives import custom_vjp as custom_vjp +from jax._src.xla_bridge import default_backend as default_backend +from jax._src.xla_bridge import device_count as device_count +from jax._src.api import device_get as device_get +from jax._src.api import device_put as device_put +from jax._src.api import device_put_sharded as device_put_sharded +from jax._src.api import device_put_replicated as device_put_replicated +from jax._src.xla_bridge import devices as devices +from jax._src.api import disable_jit as disable_jit +from jax._src.api import eval_shape as eval_shape +from jax._src.dtypes import float0 as float0 +from jax._src.api import fwd_and_bwd as fwd_and_bwd +from jax._src.api import grad as grad +from jax._src.api import hessian as hessian +from jax._src.xla_bridge import host_count as host_count +from jax._src.xla_bridge import host_id as host_id +from jax._src.xla_bridge import host_ids as host_ids +from jax._src.api import jacobian as jacobian +from jax._src.api import jacfwd as jacfwd +from jax._src.api import jacrev as jacrev +from jax._src.api import jit as jit +from jax._src.api import jvp as jvp +from jax._src.xla_bridge import local_device_count as local_device_count +from jax._src.xla_bridge import local_devices as local_devices +from jax._src.api import linearize as linearize +from jax._src.api import linear_transpose as linear_transpose +from jax._src.api import live_arrays as live_arrays +from jax._src.api import make_jaxpr as make_jaxpr +from jax._src.api import named_call as named_call +from jax._src.api import named_scope as named_scope +from jax._src.api import pmap as pmap +from jax._src.xla_bridge import process_count as process_count +from jax._src.xla_bridge import process_index as process_index +from jax._src.xla_bridge import process_indices as process_indices +from jax._src.callback import pure_callback as pure_callback +from jax._src.ad_checkpoint import checkpoint_wrapper as remat # noqa: F401 +from jax._src.api import ShapeDtypeStruct as ShapeDtypeStruct +from jax._src.api import value_and_grad as value_and_grad +from jax._src.api import vjp as vjp +from jax._src.api import vmap as vmap +from jax._src.sharding_impls import NamedSharding as NamedSharding +from jax._src.sharding_impls import make_mesh as make_mesh + +from jax._src.shard_map import shard_map as shard_map + +# Force import, allowing jax.interpreters.* to be used after import jax. +from jax.interpreters import ad, batching, mlir, partial_eval, pxla, xla +del ad, batching, mlir, partial_eval, pxla, xla + +from jax._src.array import ( + make_array_from_single_device_arrays as make_array_from_single_device_arrays, + make_array_from_callback as make_array_from_callback, + make_array_from_process_local_data as make_array_from_process_local_data, +) + +# These submodules are separate because they are in an import cycle with +# jax and rely on the names imported above. +from jax import custom_derivatives as custom_derivatives +from jax import custom_batching as custom_batching +from jax import custom_transpose as custom_transpose +from jax import api_util as api_util +from jax import distributed as distributed +from jax import debug as debug +from jax import dlpack as dlpack +from jax import dtypes as dtypes +from jax import errors as errors +from jax import ffi as ffi +from jax import image as image +from jax import lax as lax +from jax import monitoring as monitoring +from jax import nn as nn +from jax import numpy as numpy +from jax import ops as ops +from jax import profiler as profiler +from jax import random as random +from jax import scipy as scipy +from jax import sharding as sharding +from jax import stages as stages +from jax import tree_util as tree_util +from jax import util as util + +# Also circular dependency. +from jax._src.array import Shard as Shard + +import jax.experimental.compilation_cache.compilation_cache as _ccache +del _ccache + +_deprecations = { + # Finalized 2025-03-25; remove after 2025-06-25 + "treedef_is_leaf": ( + "jax.treedef_is_leaf was removed in JAX v0.6.0: use jax.tree_util.treedef_is_leaf.", + None + ), + "tree_flatten": ( + "jax.tree_flatten was removed in JAX v0.6.0: use jax.tree.flatten (jax v0.4.25 or newer) " + "or jax.tree_util.tree_flatten (any JAX version).", + None + ), + "tree_leaves": ( + "jax.tree_leaves was removed in JAX v0.6.0: use jax.tree.leaves (jax v0.4.25 or newer) " + "or jax.tree_util.tree_leaves (any JAX version).", + None + ), + "tree_structure": ( + "jax.tree_structure was removed in JAX v0.6.0: use jax.tree.structure (jax v0.4.25 or newer) " + "or jax.tree_util.tree_structure (any JAX version).", + None + ), + "tree_transpose": ( + "jax.tree_transpose was removed in JAX v0.6.0: use jax.tree.transpose (jax v0.4.25 or newer) " + "or jax.tree_util.tree_transpose (any JAX version).", + None + ), + "tree_unflatten": ( + "jax.tree_unflatten was removed in JAX v0.6.0: use jax.tree.unflatten (jax v0.4.25 or newer) " + "or jax.tree_util.tree_unflatten (any JAX version).", + None + ), + "tree_map": ( + "jax.tree_map was removed in JAX v0.6.0: use jax.tree.map (jax v0.4.25 or newer) " + "or jax.tree_util.tree_map (any JAX version).", + None + ), +} + +import typing as _typing +if _typing.TYPE_CHECKING: + pass +else: + from jax._src.deprecations import deprecation_getattr as _deprecation_getattr + __getattr__ = _deprecation_getattr(__name__, _deprecations) + del _deprecation_getattr +del _typing + +import jax.lib # TODO(phawkins): remove this export. # noqa: F401 + +# trailer diff --git a/python_embeded/Lib/site-packages/jax/ad_checkpoint.py b/python_embeded/Lib/site-packages/jax/ad_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..44c13e37933014fac7ee7d2866a03eb0513c60cb --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/ad_checkpoint.py @@ -0,0 +1,26 @@ +# Copyright 2021 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from jax._src.ad_checkpoint import ( + checkpoint as checkpoint, + checkpoint_policies as checkpoint_policies, + checkpoint_name as checkpoint_name, + print_saved_residuals as print_saved_residuals, + remat as remat, +) +from jax._src.interpreters.partial_eval import ( + Recompute as Recompute, + Saveable as Saveable, + Offloadable as Offloadable, +) diff --git a/python_embeded/Lib/site-packages/jax/api_util.py b/python_embeded/Lib/site-packages/jax/api_util.py new file mode 100644 index 0000000000000000000000000000000000000000..78f984f4b9f2d49004a08d0fd99fea34284651fc --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/api_util.py @@ -0,0 +1,29 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from jax._src.core import ( + shaped_abstractify as shaped_abstractify +) + +from jax._src.api_util import ( + argnums_partial as argnums_partial, + debug_info as debug_info, + donation_vector as donation_vector, + flatten_axes as flatten_axes, + flatten_fun as flatten_fun, + flatten_fun_nokwargs as flatten_fun_nokwargs, + rebase_donate_argnums as rebase_donate_argnums, + safe_map as safe_map, +) diff --git a/python_embeded/Lib/site-packages/jax/cloud_tpu_init.py b/python_embeded/Lib/site-packages/jax/cloud_tpu_init.py new file mode 100644 index 0000000000000000000000000000000000000000..8b886eb6b450ac60ef931b0e1755c242ffc6e71f --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/cloud_tpu_init.py @@ -0,0 +1,15 @@ +# Copyright 2021 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from jax._src.cloud_tpu_init import cloud_tpu_init as cloud_tpu_init diff --git a/python_embeded/Lib/site-packages/jax/collect_profile.py b/python_embeded/Lib/site-packages/jax/collect_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..2c725ce8e9e2a6288bf72fe7c9fc70d4294dc5fb --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/collect_profile.py @@ -0,0 +1,105 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import argparse +import gzip +import os +import pathlib +import tempfile + +# pytype: disable=import-error +from jax._src import profiler as jax_profiler +try: + from xprof.convert import _pywrap_profiler_plugin + from xprof.convert import raw_to_tool_data as convert +except ImportError: + raise ImportError( + "This script requires `xprof` to be installed.") +# pytype: enable=import-error + + +_DESCRIPTION = """ +To profile running JAX programs, you first need to start the profiler server +in the program of interest. You can do this via +`jax.profiler.start_server()`. Once the program is running and the +profiler server has started, you can run `collect_profile` to trace the execution +for a provided duration. The trace file will be dumped into a directory +(determined by `--log_dir`) and by default, a Perfetto UI link will be generated +to view the resulting trace. +""" +parser = argparse.ArgumentParser(description=_DESCRIPTION) +parser.add_argument("--log_dir", default=None, + help=("Directory to store log files. " + "Uses a temporary directory if none provided."), + type=str) +parser.add_argument("port", help="Port to collect trace", type=int) +parser.add_argument("duration_in_ms", + help="Duration to collect trace in milliseconds", type=int) +parser.add_argument("--no_perfetto_link", + help="Disable creating a perfetto link", + action="store_true") +parser.add_argument("--host", default="127.0.0.1", + help="Host to collect trace. Defaults to 127.0.0.1", + type=str) +parser.add_argument("--host_tracer_level", default=2, + help="Profiler host tracer level", type=int) +parser.add_argument("--device_tracer_level", default=1, + help="Profiler device tracer level", type=int) +parser.add_argument("--python_tracer_level", default=1, + help="Profiler Python tracer level", type=int) + +def collect_profile(port: int, duration_in_ms: int, host: str, + log_dir: os.PathLike | str | None, host_tracer_level: int, + device_tracer_level: int, python_tracer_level: int, + no_perfetto_link: bool): + options = { + "host_tracer_level": host_tracer_level, + "device_tracer_level": device_tracer_level, + "python_tracer_level": python_tracer_level, + } + log_dir_ = pathlib.Path(log_dir if log_dir is not None else tempfile.mkdtemp()) + _pywrap_profiler_plugin.trace( + f"{host}:{port}", + str(log_dir_), + duration_in_ms, + options=options) + print(f"Dumped profiling information in: {log_dir_}") + # The profiler dumps `xplane.pb` to the logging directory. To upload it to + # the Perfetto trace viewer, we need to convert it to a `trace.json` file. + # We do this by first finding the `xplane.pb` file, then passing it into + # tensorflow_profile_plugin's `xplane` conversion function. + curr_path = log_dir_.resolve() + root_trace_folder = curr_path / "plugins" / "profile" + trace_folders = [root_trace_folder / trace_folder for trace_folder + in root_trace_folder.iterdir()] + latest_folder = max(trace_folders, key=os.path.getmtime) + xplane = next(latest_folder.glob("*.xplane.pb")) + result, _ = convert.xspace_to_tool_data([xplane], "trace_viewer", {}) + + with gzip.open(str(latest_folder / "remote.trace.json.gz"), "wb") as fp: + fp.write(result.encode("utf-8")) + + if not no_perfetto_link: + path = jax_profiler._write_perfetto_trace_file(log_dir_) + jax_profiler._host_perfetto_trace_file(path) + +def main(args): + collect_profile(args.port, args.duration_in_ms, args.host, args.log_dir, + args.host_tracer_level, args.device_tracer_level, + args.python_tracer_level, args.no_perfetto_link) + +if __name__ == "__main__": + main(parser.parse_args()) diff --git a/python_embeded/Lib/site-packages/jax/core.py b/python_embeded/Lib/site-packages/jax/core.py new file mode 100644 index 0000000000000000000000000000000000000000..50b50d935024ee3c2433a9e937b9430c5448af75 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/core.py @@ -0,0 +1,162 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.core import ( + AbstractToken as AbstractToken, + AbstractValue as AbstractValue, + Atom as Atom, + CallPrimitive as CallPrimitive, + DebugInfo as DebugInfo, + DShapedArray as DShapedArray, + DropVar as DropVar, + Effect as Effect, + Effects as Effects, + get_opaque_trace_state as get_opaque_trace_state, + InconclusiveDimensionOperation as InconclusiveDimensionOperation, + JaxprPpContext as JaxprPpContext, + JaxprPpSettings as JaxprPpSettings, + JaxprTypeError as JaxprTypeError, + nonempty_axis_env as nonempty_axis_env_DO_NOT_USE, # noqa: F401 + OutputType as OutputType, + ParamDict as ParamDict, + ShapedArray as ShapedArray, + Trace as Trace, + Tracer as Tracer, + unsafe_am_i_under_a_jit as unsafe_am_i_under_a_jit_DO_NOT_USE, # noqa: F401 + unsafe_am_i_under_a_vmap as unsafe_am_i_under_a_vmap_DO_NOT_USE, # noqa: F401 + unsafe_get_axis_names as unsafe_get_axis_names_DO_NOT_USE, # noqa: F401 + UnshapedArray as UnshapedArray, + Value as Value, + abstract_token as abstract_token, + aval_mapping_handlers as aval_mapping_handlers, + call as call, + call_impl as call_impl, + check_jaxpr as check_jaxpr, + concrete_or_error as concrete_or_error, + concretization_function_error as concretization_function_error, + custom_typechecks as custom_typechecks, + ensure_compile_time_eval as ensure_compile_time_eval, + eval_context as eval_context, + eval_jaxpr as eval_jaxpr, + find_top_trace as find_top_trace, + gensym as gensym, + get_aval as get_aval, + is_concrete as is_concrete, + is_constant_dim as is_constant_dim, + is_constant_shape as is_constant_shape, + jaxprs_in_params as jaxprs_in_params, + literalable_types as literalable_types, + mapped_aval as mapped_aval, + max_dim as max_dim, + min_dim as min_dim, + new_jaxpr_eqn as new_jaxpr_eqn, + no_axis_name as no_axis_name, + no_effects as no_effects, + primal_dtype_to_tangent_dtype as primal_dtype_to_tangent_dtype, + pytype_aval_mappings as pytype_aval_mappings, + set_current_trace as set_current_trace, + subjaxprs as subjaxprs, + take_current_trace as take_current_trace, + trace_ctx as trace_ctx, + TraceTag as TraceTag, + traverse_jaxpr_params as traverse_jaxpr_params, + unmapped_aval as unmapped_aval, + valid_jaxtype as valid_jaxtype, +) + + +from jax._src import core as _src_core +_deprecations = { + # Added 2024-12-11 + "axis_frame": ("jax.core.axis_frame is deprecated.", _src_core.axis_frame), + "AxisName": ("jax.core.AxisName is deprecated.", _src_core.AxisName), + "ConcretizationTypeError": ("jax.core.ConcretizationTypeError is deprecated; " + "use jax.errors.ConcretizationTypeError.", + _src_core.ConcretizationTypeError), + "call_p": ("jax.core.call_p is deprecated. Use jax.extend.core.primitives.call_p", + _src_core.call_p), + "closed_call_p": ("jax.core.closed_call_p is deprecated. Use jax.extend.core.primitives.closed_call_p", + _src_core.closed_call_p), + "get_type": ("jax.core.get_type is deprecated.", _src_core.get_aval), + "trace_state_clean": ("jax.core.trace_state_clean is deprecated.", + _src_core.trace_state_clean), + "typecheck": ("jax.core.typecheck is deprecated.", _src_core.typecheck), + "typematch": ("jax.core.typematch is deprecated.", _src_core.typematch), + # Added 2024-12-10 + "full_lower": ("jax.core.full_lower is deprecated. It is a no-op as of JAX v0.4.36.", None), + "jaxpr_as_fun": ("jax.core.jaxpr_as_fun was removed in JAX v0.6.0. Use jax.extend.core.jaxpr_as_fun instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", + None), + "lattice_join": ("jax.core.lattice_join is deprecated. It is a no-op as of JAX v0.4.36.", None), + # Finalized 2025-03-25 for JAX v0.6.0; remove after 2025-06-25 + "AxisSize": ("jax.core.AxisSize was removed in JAX v0.6.0.", None), + "ClosedJaxpr": ("jax.core.ClosedJaxpr was removed in JAX v0.6.0. Use jax.extend.core.ClosedJaxpr instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", None), + "EvalTrace": ("jax.core.EvalTrace was removed in JAX v0.6.0.", None), + "InDBIdx": ("jax.core.InDBIdx was removed in JAX v0.6.0.", None), + "InputType": ("jax.core.InputType was removed in JAX v0.6.0.", None), + "Jaxpr": ("jax.core.Jaxpr was removed in JAX v0.6.0. Use jax.extend.core.Jaxpr instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", None), + "JaxprEqn": ("jax.core.JaxprEqn was removed in JAX v0.6.0. Use jax.extend.core.JaxprEqn instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", None), + "Literal": ("jax.core.Literal was removed in JAX v0.6.0. Use jax.extend.core.Literal instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", None), + "MapPrimitive": ("jax.core.MapPrimitive was removed in JAX v0.6.0.", None), + "OpaqueTraceState": ("jax.core.OpaqueTraceState was removed in JAX v0.6.0.", None), + "OutDBIdx": ("jax.core.OutDBIdx was removed in JAX v0.6.0.", None), + "Primitive": ("jax.core.Primitive was removed in JAX v0.6.0. Use jax.extend.core.Primitive instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", None), + "Token": ("jax.core.Token was removed in JAX v0.6.0. Use jax.extend.core.Token instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", None), + "TRACER_LEAK_DEBUGGER_WARNING": ("jax.core.TRACER_LEAK_DEBUGGER_WARNING was removed in JAX v0.6.0.", None), + "Var": ("jax.core.Var was removed in JAX v0.6.0. Use jax.extend.core.Var instead, " + "and see https://docs.jax.dev/en/latest/jax.extend.html for details.", None), + "concrete_aval": ("jax.core.concrete_aval was removed in JAX v0.6.0.", None), + "dedup_referents": ("jax.core.dedup_referents was removed in JAX v0.6.0.", None), + "escaped_tracer_error": ("jax.core.escaped_tracer_error was removed in JAX v0.6.0.", None), + "extend_axis_env_nd": ("jax.core.extend_axis_env_nd was removed in JAX v0.6.0.", None), + "get_referent": ("jax.core.get_referent was removed in JAX v0.6.0.", None), + "join_effects": ("jax.core.join_effects was removed in JAX v0.6.0.", None), + "leaked_tracer_error": ("jax.core.leaked_tracer_error was removed in JAX v0.6.0.", None), + "maybe_find_leaked_tracers": ("jax.core.maybe_find_leaked_tracers was removed in JAX v0.6.0.", None), + "raise_to_shaped": ("jax.core.raise_to_shaped was removed in JAX v0.6.0. It is a no-op as of JAX v0.4.36.", None), + "raise_to_shaped_mappings": ("jax.core.raise_to_shaped_mappings was removed in JAX v0.6.0." + " It is unused as of jax v0.4.36.", None), + "reset_trace_state": ("jax.core.reset_trace_state was removed in JAX v0.6.0.", None), + "str_eqn_compact": ("jax.core.str_eqn_compact was removed in JAX v0.6.0.", None), + "substitute_vars_in_output_ty": ("jax.core.substitute_vars_in_output_ty was removed in JAX v0.6.0.", None), + "typecompat": ("jax.core.typecompat was removed in JAX v0.6.0.", None), + "used_axis_names_jaxpr": ("jax.core.used_axis_names_jaxpr was removed in JAX v0.6.0.", None), +} + +import typing +if typing.TYPE_CHECKING: + AxisName = _src_core.AxisName + ConcretizationTypeError = _src_core.ConcretizationTypeError + axis_frame = _src_core.axis_frame + call_p = _src_core.call_p + closed_call_p = _src_core.closed_call_p + get_type = _src_core.get_aval + trace_state_clean = _src_core.trace_state_clean + typecheck = _src_core.typecheck + typematch = _src_core.typematch +else: + from jax._src.deprecations import deprecation_getattr as _deprecation_getattr + __getattr__ = _deprecation_getattr(__name__, _deprecations) + del _deprecation_getattr +del typing +del _src_core diff --git a/python_embeded/Lib/site-packages/jax/custom_batching.py b/python_embeded/Lib/site-packages/jax/custom_batching.py new file mode 100644 index 0000000000000000000000000000000000000000..9b8dc8f8709af2b4af25d90cfa3b7fb09089e6e5 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/custom_batching.py @@ -0,0 +1,18 @@ +# Copyright 2021 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from jax._src.custom_batching import ( + custom_vmap as custom_vmap, + sequential_vmap as sequential_vmap, +) diff --git a/python_embeded/Lib/site-packages/jax/custom_derivatives.py b/python_embeded/Lib/site-packages/jax/custom_derivatives.py new file mode 100644 index 0000000000000000000000000000000000000000..6674046dd8e847c47cc6046cebf283761e0557f9 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/custom_derivatives.py @@ -0,0 +1,57 @@ +# Copyright 2020 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.custom_derivatives import ( + _initial_style_jaxpr, # noqa: F401 + _sum_tangents, # noqa: F401 + _zeros_like_pytree, # noqa: F401 + closure_convert as closure_convert, + custom_gradient as custom_gradient, + custom_jvp as custom_jvp, + custom_jvp_call_p as custom_jvp_call_p, + custom_jvp_call_jaxpr_p as _custom_jvp_call_jaxpr_p, + custom_vjp as custom_vjp, + custom_vjp_call_p as custom_vjp_call_p, + custom_vjp_primal_tree_values as custom_vjp_primal_tree_values, + CustomVJPPrimal as CustomVJPPrimal, + linear_call as linear_call, + remat_opt_p as remat_opt_p, +) + +from jax._src.ad_util import ( + SymbolicZero as SymbolicZero, + zero_from_primal as zero_from_primal +) + +_deprecations = { + # Added May 12, 2025 + "custom_jvp_call_jaxpr_p": ( + ("jax.custom_derivatives.custom_jvp_call_jaxpr_p is deprecated, use " + "jax.extend.core.primitives.custom_jvp_call_p instead."), + _custom_jvp_call_jaxpr_p, + ), +} + +import typing +if typing.TYPE_CHECKING: + custom_jvp_call_jaxpr_p = _custom_jvp_call_jaxpr_p +else: + from jax._src.deprecations import deprecation_getattr as _deprecation_getattr + __getattr__ = _deprecation_getattr(__name__, _deprecations) + del _deprecation_getattr +del typing +del _custom_jvp_call_jaxpr_p diff --git a/python_embeded/Lib/site-packages/jax/custom_transpose.py b/python_embeded/Lib/site-packages/jax/custom_transpose.py new file mode 100644 index 0000000000000000000000000000000000000000..314163c4684aa7899f35ea61e671e8f2f673d8ed --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/custom_transpose.py @@ -0,0 +1,17 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from jax._src.custom_transpose import ( + custom_transpose as custom_transpose, +) diff --git a/python_embeded/Lib/site-packages/jax/debug.py b/python_embeded/Lib/site-packages/jax/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..64578524d0960862010968d785fa063dcacde6bd --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/debug.py @@ -0,0 +1,22 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +__all__ = ["callback", "print", "DebugEffect", "visualize_array_sharding", + "inspect_array_sharding", "visualize_sharding", "breakpoint"] +from jax._src.debugging import debug_callback as callback +from jax._src.debugging import debug_print as print +from jax._src.debugging import DebugEffect +from jax._src.debugging import visualize_array_sharding +from jax._src.debugging import inspect_array_sharding +from jax._src.debugging import visualize_sharding +from jax._src.debugger import breakpoint diff --git a/python_embeded/Lib/site-packages/jax/distributed.py b/python_embeded/Lib/site-packages/jax/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c5af19531b635d87f363d118bb6b2c16bc9fa0 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/distributed.py @@ -0,0 +1,19 @@ +# Copyright 2021 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from jax._src.distributed import ( + initialize as initialize, + is_initialized as is_initialized, + shutdown as shutdown, +) diff --git a/python_embeded/Lib/site-packages/jax/dlpack.py b/python_embeded/Lib/site-packages/jax/dlpack.py new file mode 100644 index 0000000000000000000000000000000000000000..d008608fc356bd99634f959b0345b9b86036992c --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/dlpack.py @@ -0,0 +1,46 @@ +# Copyright 2020 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import jax._src.dlpack +import jax._src.deprecations + +from jax._src.dlpack import ( + from_dlpack as from_dlpack, + SUPPORTED_DTYPES as SUPPORTED_DTYPES, +) + +_deprecations = { + "to_dlpack": ( + ( + "jax.dlpack.to_dlpack was deprecated in JAX v0.6.0 and will be" + " removed in JAX v0.7.0. Please use the newer DLPack API based on" + " __dlpack__ and __dlpack_device__ instead. Typically, you can pass" + " a JAX array directly to the `from_dlpack` function of another" + " framework without using `to_dlpack`." + ), + jax._src.dlpack.to_dlpack, + ), +} + + +import typing as _typing + +if _typing.TYPE_CHECKING: + to_dlpack = jax._src.dlpack.to_dlpack +else: + __getattr__ = jax._src.deprecations.deprecation_getattr( + __name__, _deprecations + ) +del _typing diff --git a/python_embeded/Lib/site-packages/jax/dtypes.py b/python_embeded/Lib/site-packages/jax/dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..4c1136360687e5ee28dc754ea8a2b41c36d1606f --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/dtypes.py @@ -0,0 +1,29 @@ +# Copyright 2019 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.dtypes import ( + bfloat16 as bfloat16, + canonicalize_dtype as canonicalize_dtype, + finfo, # TODO(phawkins): switch callers to jnp.finfo? # noqa: F401 + float0 as float0, + iinfo, # TODO(phawkins): switch callers to jnp.iinfo? # noqa: F401 + issubdtype, # TODO(phawkins): switch callers to jnp.issubdtype? # noqa: F401 + extended as extended, + prng_key as prng_key, + result_type as result_type, + scalar_type_of as scalar_type_of, +) diff --git a/python_embeded/Lib/site-packages/jax/errors.py b/python_embeded/Lib/site-packages/jax/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..6da7b717cb5fd253b7ad09dc3dd4d7e2fe6ec319 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/errors.py @@ -0,0 +1,34 @@ +# Copyright 2021 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.errors import ( + JAXTypeError as JAXTypeError, + JAXIndexError as JAXIndexError, + ConcretizationTypeError as ConcretizationTypeError, + NonConcreteBooleanIndexError as NonConcreteBooleanIndexError, + TracerArrayConversionError as TracerArrayConversionError, + TracerBoolConversionError as TracerBoolConversionError, + TracerIntegerConversionError as TracerIntegerConversionError, + UnexpectedTracerError as UnexpectedTracerError, + KeyReuseError as KeyReuseError, +) + +from jax._src.lib import xla_client as _xc +JaxRuntimeError = _xc.XlaRuntimeError +del _xc + +from jax._src.traceback_util import SimplifiedTraceback as SimplifiedTraceback diff --git a/python_embeded/Lib/site-packages/jax/export.py b/python_embeded/Lib/site-packages/jax/export.py new file mode 100644 index 0000000000000000000000000000000000000000..d9559909f158234027f7b75b36c900bdf42812c0 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/export.py @@ -0,0 +1,40 @@ +# Copyright 2024 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +__all__ = ["DisabledSafetyCheck", "Exported", "export", "deserialize", + "register_pytree_node_serialization", + "register_namedtuple_serialization", + "maximum_supported_calling_convention_version", + "minimum_supported_calling_convention_version", + "default_export_platform", + "SymbolicScope", "is_symbolic_dim", + "symbolic_shape", "symbolic_args_specs"] + +from jax._src.export._export import ( + DisabledSafetyCheck, + Exported, + export, + deserialize, + register_pytree_node_serialization, + register_namedtuple_serialization, + maximum_supported_calling_convention_version, + minimum_supported_calling_convention_version, + default_export_platform) + +from jax._src.export import shape_poly_decision # Import only to set the decision procedure +del shape_poly_decision +from jax._src.export.shape_poly import ( + SymbolicScope, + is_symbolic_dim, + symbolic_shape, + symbolic_args_specs) diff --git a/python_embeded/Lib/site-packages/jax/ffi.py b/python_embeded/Lib/site-packages/jax/ffi.py new file mode 100644 index 0000000000000000000000000000000000000000..6606c58a035320de4c0c524a8c43d010d30679b5 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/ffi.py @@ -0,0 +1,26 @@ +# Copyright 2024 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.ffi import ( + ffi_call as ffi_call, + ffi_lowering as ffi_lowering, + include_dir as include_dir, + pycapsule as pycapsule, + register_ffi_target as register_ffi_target, + register_ffi_type_id as register_ffi_type_id, + register_ffi_target_as_batch_partitionable as register_ffi_target_as_batch_partitionable, +) diff --git a/python_embeded/Lib/site-packages/jax/flatten_util.py b/python_embeded/Lib/site-packages/jax/flatten_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0f0dad46d80ff6d78e8ceb987dba14806abcda80 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/flatten_util.py @@ -0,0 +1,15 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from jax._src.flatten_util import ravel_pytree as ravel_pytree diff --git a/python_embeded/Lib/site-packages/jax/monitoring.py b/python_embeded/Lib/site-packages/jax/monitoring.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ab8124f219fd2ac26d1d6f1a985ad56a23f71b --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/monitoring.py @@ -0,0 +1,34 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for instrumenting code. + +Code points can be marked as a named event. Every time an event is reached +during program execution, the registered listeners will be invoked. + +A typical listener callback is to send an event to a metrics collector for +aggregation/exporting. +""" + +from jax._src.monitoring import ( + clear_event_listeners as clear_event_listeners, + record_event_duration_secs as record_event_duration_secs, + record_event_time_span as record_event_time_span, + record_event as record_event, + record_scalar as record_scalar, + register_event_duration_secs_listener as register_event_duration_secs_listener, + register_event_listener as register_event_listener, + register_event_time_span_listener as register_event_time_span_listener, + register_scalar_listener as register_scalar_listener, +) diff --git a/python_embeded/Lib/site-packages/jax/profiler.py b/python_embeded/Lib/site-packages/jax/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..d776791e9200682be22b93b1d0dc5ce579d7e83d --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/profiler.py @@ -0,0 +1,37 @@ +# Copyright 2020 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 +from typing import Any + +from jax._src.profiler import ( + ProfileOptions as ProfileOptions, + StepTraceAnnotation as StepTraceAnnotation, + TraceAnnotation as TraceAnnotation, + annotate_function as annotate_function, + device_memory_profile as device_memory_profile, + save_device_memory_profile as save_device_memory_profile, + start_server as start_server, + start_trace as start_trace, + stop_server as stop_server, + stop_trace as stop_trace, + trace as trace, +) + +# this is a temporary shim to please pytype in the meantime before the migration +# is complete for cl/760646494 +ProfileData: Any = None +ProfileEvent: Any = None +ProfilePlane: Any = None diff --git a/python_embeded/Lib/site-packages/jax/py.typed b/python_embeded/Lib/site-packages/jax/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/jax/random.py b/python_embeded/Lib/site-packages/jax/random.py new file mode 100644 index 0000000000000000000000000000000000000000..89d68a24ccafe1e61bf974c4583f9ca454729715 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/random.py @@ -0,0 +1,254 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for pseudo-random number generation. + +The :mod:`jax.random` package provides a number of routines for deterministic +generation of sequences of pseudorandom numbers. + +Basic usage +----------- + +>>> seed = 1701 +>>> num_steps = 100 +>>> key = jax.random.key(seed) +>>> for i in range(num_steps): +... key, subkey = jax.random.split(key) +... params = compiled_update(subkey, params, next(batches)) # doctest: +SKIP + +PRNG keys +--------- + +Unlike the *stateful* pseudorandom number generators (PRNGs) that users of NumPy and +SciPy may be accustomed to, JAX random functions all require an explicit PRNG state to +be passed as a first argument. +The random state is described by a special array element type that we call a **key**, +usually generated by the :py:func:`jax.random.key` function:: + + >>> from jax import random + >>> key = random.key(0) + >>> key + Array((), dtype=key) overlaying: + [0 0] + +This key can then be used in any of JAX's random number generation routines:: + + >>> random.uniform(key) + Array(0.947667, dtype=float32) + +Note that using a key does not modify it, so reusing the same key will lead to the same result:: + + >>> random.uniform(key) + Array(0.947667, dtype=float32) + +If you need a new random number, you can use :meth:`jax.random.split` to generate new subkeys:: + + >>> key, subkey = random.split(key) + >>> random.uniform(subkey) + Array(0.00729382, dtype=float32) + +.. note:: + + Typed key arrays, with element types such as ``key`` above, + were introduced in JAX v0.4.16. Before then, keys were + conventionally represented in ``uint32`` arrays, whose final + dimension represented the key's bit-level representation. + + Both forms of key array can still be created and used with the + :mod:`jax.random` module. New-style typed key arrays are made with + :py:func:`jax.random.key`. Legacy ``uint32`` key arrays are made + with :py:func:`jax.random.PRNGKey`. + + To convert between the two, use :py:func:`jax.random.key_data` and + :py:func:`jax.random.wrap_key_data`. The legacy key format may be + needed when interfacing with systems outside of JAX (e.g. exporting + arrays to a serializable format), or when passing keys to JAX-based + libraries that assume the legacy format. + + Otherwise, typed keys are recommended. Caveats of legacy keys + relative to typed ones include: + + * They have an extra trailing dimension. + + * They have a numeric dtype (``uint32``), allowing for operations + that are typically not meant to be carried out over keys, such as + integer arithmetic. + + * They do not carry information about the RNG implementation. When + legacy keys are passed to :mod:`jax.random` functions, a global + configuration setting determines the RNG implementation (see + "Advanced RNG configuration" below). + + To learn more about this upgrade, and the design of key types, see + `JEP 9263 + `_. + +Advanced +-------- + +Design and background +===================== + +**TLDR**: JAX PRNG = `Threefry counter PRNG `_ ++ a functional array-oriented `splitting model `_ + +See `docs/jep/263-prng.md `_ +for more details. + +To summarize, among other requirements, the JAX PRNG aims to: + +1. ensure reproducibility, +2. parallelize well, both in terms of vectorization (generating array values) + and multi-replica, multi-core computation. In particular it should not use + sequencing constraints between random function calls. + +Advanced RNG configuration +========================== + +JAX provides several PRNG implementations. A specific one can be +selected with the optional ``impl`` keyword argument to +``jax.random.key``. When no ``impl`` option is passed to the ``key`` +constructor, the implementation is determined by the global +``jax_default_prng_impl`` configuration flag. The string names of +available implementations are: + +- ``"threefry2x32"`` (**default**): + A counter-based PRNG based on a variant of the Threefry hash function, + as described in `this paper by Salmon et al., 2011 + `_. + +- ``"rbg"`` and ``"unsafe_rbg"`` (**experimental**): PRNGs built atop + `XLA's Random Bit Generator (RBG) algorithm + `_. + + - ``"rbg"`` uses XLA RBG for random number generation, whereas for + key derivation (as in ``jax.random.split`` and + ``jax.random.fold_in``) it uses the same method as + ``"threefry2x32"``. + + - ``"unsafe_rbg"`` uses XLA RBG for both generation as well as key + derivation. + + Random numbers generated by these experimental schemes have not + been subject to empirical randomness testing (e.g. BigCrush). + + Key derivation in ``"unsafe_rbg"`` has also not been empirically + tested. The name emphasizes "unsafe" because key derivation + quality and generation quality are not well understood. + + Additionally, both ``"rbg"`` and ``"unsafe_rbg"`` behave unusually + under ``jax.vmap``. When vmapping a random function over a batch + of keys, its output values can differ from its true map over the + same keys. Instead, under ``vmap``, the entire batch of output + random numbers is generated from only the first key in the input + key batch. For example, if ``keys`` is a vector of 8 keys, then + ``jax.vmap(jax.random.normal)(keys)`` equals + ``jax.random.normal(keys[0], shape=(8,))``. This peculiarity + reflects a workaround to XLA RBG's limited batching support. + +Reasons to use an alternative to the default RNG include that: + +1. It may be slow to compile for TPUs. +2. It is relatively slower to execute on TPUs. + +**Automatic partitioning:** + +In order for ``jax.jit`` to efficiently auto-partition functions that +generate sharded random number arrays (or key arrays), all PRNG +implementations require extra flags: + +- For ``"threefry2x32"``, and ``"rbg"`` key derivation, set + ``jax_threefry_partitionable=True``. +- For ``"unsafe_rbg"``, and ``"rbg"`` random generation", set the XLA + flag ``--xla_tpu_spmd_rng_bit_generator_unsafe=1``. + +The XLA flag can be set using an the ``XLA_FLAGS`` environment +variable, e.g. as +``XLA_FLAGS=--xla_tpu_spmd_rng_bit_generator_unsafe=1``. + +For more about ``jax_threefry_partitionable``, see +https://docs.jax.dev/en/latest/notebooks/Distributed_arrays_and_automatic_parallelization.html#generating-random-numbers + +**Summary:** + +.. table:: + :widths: auto + + ================================= ======== ========= === ========== ===== ============ + Property Threefry Threefry* rbg unsafe_rbg rbg** unsafe_rbg** + ================================= ======== ========= === ========== ===== ============ + Fastest on TPU ✅ ✅ ✅ ✅ + efficiently shardable (w/ pjit) ✅ ✅ ✅ + identical across shardings ✅ ✅ ✅ ✅ + identical across CPU/GPU/TPU ✅ ✅ + exact ``jax.vmap`` over keys ✅ ✅ + ================================= ======== ========= === ========== ===== ============ + +(*): with ``jax_threefry_partitionable=1`` set + +(**): with ``XLA_FLAGS=--xla_tpu_spmd_rng_bit_generator_unsafe=1`` set +""" + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.random import ( + PRNGKey as PRNGKey, + ball as ball, + bernoulli as bernoulli, + binomial as binomial, + beta as beta, + bits as bits, + categorical as categorical, + cauchy as cauchy, + chisquare as chisquare, + choice as choice, + clone as clone, + dirichlet as dirichlet, + double_sided_maxwell as double_sided_maxwell, + exponential as exponential, + f as f, + fold_in as fold_in, + gamma as gamma, + generalized_normal as generalized_normal, + geometric as geometric, + gumbel as gumbel, + key as key, + key_data as key_data, + key_impl as key_impl, + laplace as laplace, + logistic as logistic, + loggamma as loggamma, + lognormal as lognormal, + maxwell as maxwell, + multinomial as multinomial, + multivariate_normal as multivariate_normal, + normal as normal, + orthogonal as orthogonal, + pareto as pareto, + permutation as permutation, + poisson as poisson, + rademacher as rademacher, + randint as randint, + random_gamma_p as random_gamma_p, + rayleigh as rayleigh, + split as split, + t as t, + triangular as triangular, + truncated_normal as truncated_normal, + uniform as uniform, + wald as wald, + weibull_min as weibull_min, + wrap_key_data as wrap_key_data, +) diff --git a/python_embeded/Lib/site-packages/jax/sharding.py b/python_embeded/Lib/site-packages/jax/sharding.py new file mode 100644 index 0000000000000000000000000000000000000000..66692069d19b92b0bceb4816485dd1b413510a9b --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/sharding.py @@ -0,0 +1,64 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.sharding import Sharding as Sharding +from jax._src.sharding_impls import ( + NamedSharding as NamedSharding, + SingleDeviceSharding as SingleDeviceSharding, + PmapSharding as PmapSharding, + GSPMDSharding as _deprecated_GSPMDSharding, + PositionalSharding as _deprecated_PositionalSharding, + use_mesh as use_mesh, + set_mesh as set_mesh, +) +from jax._src.partition_spec import ( + PartitionSpec as PartitionSpec, +) +from jax._src.mesh import ( + Mesh as Mesh, + AbstractMesh as AbstractMesh, + AxisType as AxisType, + get_abstract_mesh as get_abstract_mesh, +) + +_deprecations = { + # Added April 11, 2025. + "PositionalSharding": ( + ( + "jax.sharding.PositionalSharding is deprecated. Use" + " jax.NamedSharding instead." + ), + _deprecated_PositionalSharding, + ), + "GSPMDSharding": ( + ( + "jax.sharding.GSPMDSharding is deprecated. Use" + " jax.NamedSharding instead." + ), + _deprecated_GSPMDSharding, + ), +} + +import typing +if typing.TYPE_CHECKING: + PositionalSharding = _deprecated_PositionalSharding + GSPMDSharding = _deprecated_GSPMDSharding +else: + from jax._src.deprecations import deprecation_getattr as _deprecation_getattr + __getattr__ = _deprecation_getattr(__name__, _deprecations) + del _deprecation_getattr +del typing diff --git a/python_embeded/Lib/site-packages/jax/stages.py b/python_embeded/Lib/site-packages/jax/stages.py new file mode 100644 index 0000000000000000000000000000000000000000..aa4c96168b3fbab4e1504f445793e755ae2732b1 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/stages.py @@ -0,0 +1,35 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Interfaces to stages of the compiled execution process. + +JAX transformations that compile just in time for execution, such as +``jax.jit`` and ``jax.pmap``, also support a common means of explicit +lowering and compilation *ahead of time*. This module defines types +that represent the stages of this process. + +For more, see the `AOT walkthrough `_. +""" + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.stages import ( + Compiled as Compiled, + CompilerOptions as CompilerOptions, + Lowered as Lowered, + Wrapped as Wrapped, + ArgInfo as ArgInfo, + OutInfo as OutInfo, + Traced as Traced, +) diff --git a/python_embeded/Lib/site-packages/jax/test_util.py b/python_embeded/Lib/site-packages/jax/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..176f4521b28193e9a93fee05d79ebdd25c820213 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/test_util.py @@ -0,0 +1,22 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.public_test_util import ( + check_grads as check_grads, + check_jvp as check_jvp, + check_vjp as check_vjp, +) diff --git a/python_embeded/Lib/site-packages/jax/tree.py b/python_embeded/Lib/site-packages/jax/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..03ca503f3a41989f022b18944b3ddf36b8865fbc --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/tree.py @@ -0,0 +1,33 @@ +# Copyright 2024 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for working with tree-like container data structures. + +The :mod:`jax.tree` namespace contains aliases of utilities from :mod:`jax.tree_util`. +""" + +from jax._src.tree import ( + all as all, + broadcast as broadcast, + flatten_with_path as flatten_with_path, + flatten as flatten, + leaves_with_path as leaves_with_path, + leaves as leaves, + map_with_path as map_with_path, + map as map, + reduce as reduce, + structure as structure, + transpose as transpose, + unflatten as unflatten, +) diff --git a/python_embeded/Lib/site-packages/jax/tree_util.py b/python_embeded/Lib/site-packages/jax/tree_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b35890dfc8876cb8205276c8960e15eb4556bca7 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/tree_util.py @@ -0,0 +1,95 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for working with tree-like container data structures. + +This module provides a small set of utility functions for working with tree-like +data structures, such as nested tuples, lists, and dicts. We call these +structures pytrees. They are trees in that they are defined recursively (any +non-pytree is a pytree, i.e. a leaf, and any pytree of pytrees is a pytree) and +can be operated on recursively (object identity equivalence is not preserved by +mapping operations, and the structures cannot contain reference cycles). + +The set of Python types that are considered pytree nodes (e.g. that can be +mapped over, rather than treated as leaves) is extensible. There is a single +module-level registry of types, and class hierarchy is ignored. By registering a +new pytree node type, that type in effect becomes transparent to the utility +functions in this file. + +The primary purpose of this module is to enable the interoperability between +user defined data structures and JAX transformations (e.g. `jit`). This is not +meant to be a general purpose tree-like data structure handling library. + +See the `JAX pytrees note `_ +for examples. +""" + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +from jax._src.tree_util import ( + DictKey as DictKey, + FlattenedIndexKey as FlattenedIndexKey, + GetAttrKey as GetAttrKey, + KeyEntry as KeyEntry, + KeyPath as KeyPath, + Partial as Partial, + PyTreeDef as PyTreeDef, + SequenceKey as SequenceKey, + all_leaves as all_leaves, + build_tree as _deprecated_build_tree, + default_registry as default_registry, + keystr as keystr, + register_dataclass as register_dataclass, + register_pytree_node_class as register_pytree_node_class, + register_pytree_node as register_pytree_node, + register_pytree_with_keys_class as register_pytree_with_keys_class, + register_pytree_with_keys as register_pytree_with_keys, + register_static as register_static, + tree_all as tree_all, + tree_broadcast as tree_broadcast, + tree_flatten_with_path as tree_flatten_with_path, + tree_flatten as tree_flatten, + tree_leaves_with_path as tree_leaves_with_path, + tree_leaves as tree_leaves, + tree_map_with_path as tree_map_with_path, + tree_map as tree_map, + tree_reduce as tree_reduce, + tree_structure as tree_structure, + tree_transpose as tree_transpose, + tree_unflatten as tree_unflatten, + treedef_children as treedef_children, + treedef_is_leaf as treedef_is_leaf, + treedef_tuple as treedef_tuple, +) + +_deprecations = { + # Added March 21, 2025: + "build_tree": ( + ( + "jax.tree_util.build_tree is deprecated. Use jax.tree.unflatten" + " instead." + ), + _deprecated_build_tree, + ), +} + +import typing as _typing +if _typing.TYPE_CHECKING: + from jax._src.tree_util import build_tree as build_tree +else: + from jax._src.deprecations import deprecation_getattr + __getattr__ = deprecation_getattr(__name__, _deprecations) + del deprecation_getattr +del _typing diff --git a/python_embeded/Lib/site-packages/jax/typing.py b/python_embeded/Lib/site-packages/jax/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..0530c69e60ca4a11169d1467397030987dba2acc --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/typing.py @@ -0,0 +1,75 @@ +# Copyright 2023 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +The JAX typing module is where JAX-specific static type annotations live. +This submodule is a work in progress; to see the proposal behind the types exported +here, see https://docs.jax.dev/en/latest/jep/12049-type-annotations.html. + +The currently-available types are: + +- :class:`jax.Array`: annotation for any JAX array or tracer (i.e. representations of arrays + within JAX transforms). +- :obj:`jax.typing.ArrayLike`: annotation for any value that is safe to implicitly cast to + a JAX array; this includes :class:`jax.Array`, :class:`numpy.ndarray`, as well as Python + builtin numeric values (e.g. :class:`int`, :class:`float`, etc.) and numpy scalar values + (e.g. :class:`numpy.int32`, :class:`numpy.float64`, etc.) +- :obj:`jax.typing.DTypeLike`: annotation for any value that can be cast to a JAX-compatible + dtype; this includes strings (e.g. `'float32'`, `'int32'`), scalar types (e.g. `float`, + `np.float32`), dtypes (e.g. `np.dtype('float32')`), or objects with a dtype attribute + (e.g. `jnp.float32`, `jnp.int32`). + +We may add additional types here in future releases. + +JAX Typing Best Practices +------------------------- +When annotating JAX arrays in public API functions, we recommend using :class:`~jax.typing.ArrayLike` +for array inputs, and :class:`~jax.Array` for array outputs. + +For example, your function might look like this:: + + import numpy as np + import jax.numpy as jnp + from jax import Array + from jax.typing import ArrayLike + + def my_function(x: ArrayLike) -> Array: + # Runtime type validation, Python 3.10 or newer: + if not isinstance(x, ArrayLike): + raise TypeError(f"Expected arraylike input; got {x}") + # Runtime type validation, any Python version: + if not (isinstance(x, (np.ndarray, Array)) or np.isscalar(x)): + raise TypeError(f"Expected arraylike input; got {x}") + + # Convert input to jax.Array: + x_arr = jnp.asarray(x) + + # ... do some computation; JAX functions will return Array types: + result = x_arr.sum(0) / x_arr.shape[0] + + # return an Array + return result + +Most of JAX's public APIs follow this pattern. Note in particular that we recommend JAX functions +to not accept sequences such as :class:`list` or :class:`tuple` in place of arrays, as this can +cause extra overhead in JAX transforms like :func:`~jax.jit` and can behave in unexpected ways with +batch-wise transforms like :func:`~jax.vmap` or :func:`jax.pmap`. For more information on this, +see `Non-array inputs NumPy vs JAX`_ + +.. _Non-array inputs NumPy vs JAX: https://docs.jax.dev/en/latest/notebooks/Common_Gotchas_in_JAX.html#non-array-inputs-numpy-vs-jax +""" +from jax._src.typing import ( + ArrayLike as ArrayLike, + DTypeLike as DTypeLike, +) diff --git a/python_embeded/Lib/site-packages/jax/util.py b/python_embeded/Lib/site-packages/jax/util.py new file mode 100644 index 0000000000000000000000000000000000000000..b2c9df20520631285010f0b93f1c43f76bc72357 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/util.py @@ -0,0 +1,149 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Note: import as is required for names to be exported. +# See PEP 484 & https://github.com/jax-ml/jax/issues/7570 + +import jax._src.deprecations +import jax._src.util + + +_deprecations = { + "to_dlpack": ( + ( + "jax.dlpack.to_dlpack was deprecated in JAX v0.6.0 and will be" + " removed in JAX v0.7.0. Please use the newer DLPack API based on" + " __dlpack__ and __dlpack_device__ instead. Typically, you can pass" + " a JAX array directly to the `from_dlpack` function of another" + " framework without using `to_dlpack`." + ), + jax._src.dlpack.to_dlpack, + ), + "HashableFunction": ( + ( + "HashableFunction was deprecated in JAX v0.6.0 and will be removed" + " in JAX v0.7.0." + ), + jax._src.util.HashableFunction, + ), + "as_hashable_function": ( + ( + "as_hashable_function was deprecated in JAX v0.6.0 and will be" + " removed in JAX v0.7.0." + ), + jax._src.util.as_hashable_function, + ), + "cache": ( + "cache was deprecated in JAX v0.6.0 and will be removed in JAX v0.7.0.", + jax._src.util.cache, + ), + "safe_map": ( + ( + "safe_map was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.safe_map, + ), + "safe_zip": ( + ( + "safe_zip was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.safe_zip, + ), + "split_dict": ( + ( + "split_dict was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.split_dict, + ), + "split_list": ( + ( + "split_list was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.split_list, + ), + "split_list_checked": ( + ( + "split_list_checked was deprecated in JAX v0.6.0 and will be" + " removed in JAX v0.7.0." + ), + jax._src.util.split_list_checked, + ), + "split_merge": ( + ( + "split_merge was deprecated in JAX v0.6.0 and will be removed in" + " JAX v0.7.0." + ), + jax._src.util.split_merge, + ), + "subvals": ( + ( + "subvals was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.subvals, + ), + "toposort": ( + ( + "toposort was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.toposort, + ), + "unzip2": ( + ( + "unzip2 was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.unzip2, + ), + "wrap_name": ( + ( + "wrap_name was deprecated in JAX v0.6.0 and will be removed in JAX" + " v0.7.0." + ), + jax._src.util.wrap_name, + ), + "wraps": ( + "wraps was deprecated in JAX v0.6.0 and will be removed in JAX v0.7.0.", + jax._src.util.wraps, + ), +} + + +import typing as _typing + +if _typing.TYPE_CHECKING: + HashableFunction = jax._src.util.HashableFunction + as_hashable_function = jax._src.util.as_hashable_function + cache = jax._src.util.cache + safe_map = jax._src.util.safe_map + safe_zip = jax._src.util.safe_zip + split_dict = jax._src.util.split_dict + split_list = jax._src.util.split_list + split_list_checked = jax._src.util.split_list_checked + split_merge = jax._src.util.split_merge + subvals = jax._src.util.subvals + toposort = jax._src.util.toposort + unzip2 = jax._src.util.unzip2 + wrap_name = jax._src.util.wrap_name + wraps = jax._src.util.wraps +else: + __getattr__ = jax._src.deprecations.deprecation_getattr( + __name__, _deprecations + ) +del _typing diff --git a/python_embeded/Lib/site-packages/jax/version.py b/python_embeded/Lib/site-packages/jax/version.py new file mode 100644 index 0000000000000000000000000000000000000000..a05698c10cc17ea6375269e7b8fb9c7ce0916539 --- /dev/null +++ b/python_embeded/Lib/site-packages/jax/version.py @@ -0,0 +1,161 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file is included as part of both jax and jaxlib. It is also +# eval()-ed by setup.py, so it should not have any dependencies. +from __future__ import annotations + +import datetime +import os +import pathlib +import subprocess + +_version = "0.6.2" +# The following line is overwritten by build scripts in distributions & +# releases. Do not modify this manually, or jax/jaxlib build will fail. +_release_version: str = '0.6.2' + +# The following line is overwritten by build scripts in distributions & +# releases. Do not modify this manually, or jax/jaxlib build will fail. +_git_hash: str | None = None + +def _get_version_string() -> str: + # The build/source distribution for jax & jaxlib overwrites _release_version. + # In this case we return it directly. + if _release_version is not None: + return _release_version + if os.getenv("WHEEL_VERSION_SUFFIX"): + return _version + os.getenv("WHEEL_VERSION_SUFFIX", "") + return _version_from_git_tree(_version) or _version_from_todays_date(_version) + + +def _version_from_todays_date(base_version: str) -> str: + datestring = datetime.date.today().strftime("%Y%m%d") + return f"{base_version}.dev{datestring}" + + +def _version_from_git_tree(base_version: str) -> str | None: + try: + root_directory = os.path.dirname(os.path.realpath(__file__)) + + # Get date string from date of most recent git commit, and the abbreviated + # hash of that commit. + p = subprocess.Popen(["git", "show", "-s", "--format=%at-%h", "HEAD"], + cwd=root_directory, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, _ = p.communicate() + timestamp, commit_hash = stdout.decode().strip().split('-', 1) + datestring = datetime.date.fromtimestamp(int(timestamp)).strftime("%Y%m%d") + assert datestring.isnumeric() + assert commit_hash.isalnum() + except: + return None + else: + version = f"{base_version}.dev{datestring}+{commit_hash}" + suffix = os.environ.get("JAX_CUSTOM_VERSION_SUFFIX", None) + if suffix: + return version + "." + suffix + return version + + +def _get_version_for_build() -> str: + """Determine the version at build time. + + The returned version string depends on which environment variables are set: + - if WHEEL_VERSION_SUFFIX is set: version looks like "0.5.1.dev20230906+ge58560fdc" + Here the WHEEL_VERSION_SUFFIX value is ".dev20230906+ge58560fdc". + Please note that the WHEEL_VERSION_SUFFIX value is not the same as the + JAX_CUSTOM_VERSION_SUFFIX value, and WHEEL_VERSION_SUFFIX is set by Bazel + wheel build rule. + - if JAX_RELEASE or JAXLIB_RELEASE are set: version looks like "0.4.16" + - if JAX_NIGHTLY or JAXLIB_NIGHTLY are set: version looks like "0.4.16.dev20230906" + - if none are set: version looks like "0.4.16.dev20230906+ge58560fdc + """ + if _release_version is not None: + return _release_version + if os.getenv("WHEEL_VERSION_SUFFIX"): + return _version + os.getenv("WHEEL_VERSION_SUFFIX", "") + if os.getenv("JAX_RELEASE") or os.getenv("JAXLIB_RELEASE"): + return _version + if os.getenv("JAX_NIGHTLY") or os.getenv("JAXLIB_NIGHTLY"): + return _version_from_todays_date(_version) + return _version_from_git_tree(_version) or _version_from_todays_date(_version) + + +def _is_prerelease() -> bool: + """Determine if this is a pre-release ("rc" wheels) build.""" + rc_version = os.getenv("WHEEL_VERSION_SUFFIX", "") + return True if rc_version.startswith("rc") else False + + +def _write_version(fname: str) -> None: + """Used by setup.py to write the specified version info into the source tree.""" + release_version = _get_version_for_build() + old_version_string = "_release_version: str = '0.6.2'" + new_version_string = f"_release_version: str = {release_version!r}" + fhandle = pathlib.Path(fname) + contents = fhandle.read_text() + # Expect two occurrences: one above, and one here. + if contents.count(old_version_string) != 2: + raise RuntimeError(f"Build: could not find {old_version_string!r} in {fname}") + contents = contents.replace(old_version_string, new_version_string) + + githash = os.environ.get("JAX_GIT_HASH") + if githash: + old_githash_string = "_git_hash: str | None = None" + new_githash_string = f"_git_hash: str = {githash!r}" + if contents.count(old_githash_string) != 2: + raise RuntimeError(f"Build: could not find {old_githash_string!r} in {fname}") + contents = contents.replace(old_githash_string, new_githash_string) + fhandle.write_text(contents) + + +def _get_cmdclass(pkg_source_path): + from setuptools.command.build_py import build_py as build_py_orig # pytype: disable=import-error + from setuptools.command.sdist import sdist as sdist_orig # pytype: disable=import-error + + class _build_py(build_py_orig): + def run(self): + if _release_version is None: + this_file_in_build_dir = os.path.join(self.build_lib, pkg_source_path, + os.path.basename(__file__)) + # super().run() only copies files from source -> build if they are + # missing or outdated. Because _write_version(...) modifies the copy of + # this file in the build tree, re-building from the same JAX directory + # would not automatically re-copy a clean version, and _write_version + # would fail without this deletion. See jax-ml/jax#18252. + if os.path.isfile(this_file_in_build_dir): + os.unlink(this_file_in_build_dir) + super().run() + if _release_version is None: + _write_version(this_file_in_build_dir) + + class _sdist(sdist_orig): + def make_release_tree(self, base_dir, files): + super().make_release_tree(base_dir, files) + if _release_version is None: + _write_version(os.path.join(base_dir, pkg_source_path, + os.path.basename(__file__))) + + return dict(sdist=_sdist, build_py=_build_py) + + +__version__ = _get_version_string() +_minimum_jaxlib_version = "0.6.2" + +def _version_as_tuple(version_str): + return tuple(int(i) for i in version_str.split(".") if i.isdigit()) + +__version_info__ = _version_as_tuple(__version__) +_minimum_jaxlib_version_info = _version_as_tuple(_minimum_jaxlib_version) diff --git a/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/INSTALLER b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/LICENSE.txt b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c7416993e2d7263e7ead1568269614806f8c650 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/LICENSE.txt @@ -0,0 +1,4506 @@ +-------------------------------------------------------------------------------- +License for JAX: + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +-------------------------------------------------------------------------------- +License for BoringSSL: +BoringSSL is a fork of OpenSSL. As such, large parts of it fall under OpenSSL +licensing. Files that are completely new have a Google copyright and an ISC +license. This license is reproduced at the bottom of this file. + +Contributors to BoringSSL are required to follow the CLA rules for Chromium: +https://cla.developers.google.com/clas + +Files in third_party/ have their own licenses, as described therein. The MIT +license, for third_party/fiat, which, unlike other third_party directories, is +compiled into non-test libraries, is included below. + +The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the +OpenSSL License and the original SSLeay license apply to the toolkit. See below +for the actual license texts. Actually both licenses are BSD-style Open Source +licenses. In case of any license issues related to OpenSSL please contact +openssl-core@openssl.org. + +The following are Google-internal bug numbers where explicit permission from +some authors is recorded for use of their work. (This is purely for our own +record keeping.) + 27287199 + 27287880 + 27287883 + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + + +ISC license used for completely new code in BoringSSL: + +/* Copyright (c) 2015, Google Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + + +The code in third_party/fiat carries the MIT license: + +Copyright (c) 2015-2016 the fiat-crypto authors (see +https://github.com/mit-plv/fiat-crypto/blob/main/AUTHORS). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +Licenses for support code +------------------------- + +Parts of the TLS test suite are under the Go license. This code is not included +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so +distributing code linked against BoringSSL does not trigger this license: + +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BoringSSL uses the Chromium test infrastructure to run a continuous build, +trybots etc. The scripts which manage this, and the script for generating build +metadata, are under the Chromium license. Distributing code linked against +BoringSSL does not trigger this license. + +Copyright 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +-------------------------------------------------------------------------------- +License for gRPC: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +License for Abseil: + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +-------------------------------------------------------------------------------- +License for Protocol buffers: +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. + +-------------------------------------------------------------------------------- +License for RE2: +// Copyright (c) 2009 The RE2 Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +-------------------------------------------------------------------------------- +License for DLPack: + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 by Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +License for double-conversion: +Copyright 2006-2011, the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +-------------------------------------------------------------------------------- +License for Eigen: +Eigen 3.3.90 +The corresponding source for this library is available at +https://eigen.googlesource.com/mirror/ + +Eigen is primarily MPL2 licensed. See COPYING.MPL2 and these links: + http://www.mozilla.org/MPL/2.0/ + http://www.mozilla.org/MPL/2.0/FAQ.html + +Some files contain third-party code under BSD, whence +the other COPYING.* files here. + +If you want to guarantee that the Eigen code that you are #including +is licensed under the MPL2 and possibly more permissive licenses (like +BSD), #define this preprocessor symbol: EIGEN_MPL2_ONLY +For example, with most compilers, you could add this to your project + CXXFLAGS: -DEIGEN_MPL2_ONLY +This will cause a compilation error to be generated if you #include +any code that is covered by more restrictive licences than MPL2. + +---------------------------------------------------------------------- +Following applies to: +./test/sparseqr.cpp +./test/half_float.cpp +./test/zerosized.cpp +./test/nesting_ops.cpp +./test/sizeoverflow.cpp +./test/swap.cpp +./test/product_mmtr.cpp +./test/stdvector_overload.cpp +./test/product_symm.cpp +./test/sparse_block.cpp +./test/eigen2support.cpp +./test/upperbidiagonalization.cpp +./test/numext.cpp +./test/adjoint.cpp +./test/AnnoyingScalar.h +./test/mpl2only.cpp +./test/stddeque.cpp +./test/householder.cpp +./test/product_small.cpp +./test/product_syrk.cpp +./test/inplace_decomposition.cpp +./test/vectorwiseop.cpp +./test/meta.cpp +./test/stdvector.cpp +./test/sparseLM.cpp +./test/diagonalmatrices.cpp +./test/stdlist_overload.cpp +./test/block.cpp +./test/cholmod_support.cpp +./test/basicstuff.cpp +./test/triangular.cpp +./test/product.h +./test/vectorization_logic.cpp +./test/dontalign.cpp +./test/first_aligned.cpp +./test/mapped_matrix.cpp +./test/umfpack_support.cpp +./test/product_selfadjoint.cpp +./test/smallvectors.cpp +./test/corners.cpp +./test/product_trsolve.cpp +./test/determinant.cpp +./test/stdlist.cpp +./test/unalignedcount.cpp +./test/qr.cpp +./test/svd_common.h +./test/ref.cpp +./test/symbolic_index.cpp +./test/geo_transformations.cpp +./test/geo_eulerangles.cpp +./test/eigensolver_selfadjoint.cpp +./test/stddeque_overload.cpp +./test/jacobisvd.cpp +./test/nullary.cpp +./test/inverse.cpp +./test/integer_types.cpp +./test/metis_support.cpp +./test/exceptions.cpp +./test/packetmath.cpp +./test/schur_complex.cpp +./test/type_alias.cpp +./test/unalignedassert.cpp +./test/geo_quaternion.cpp +./test/lu.cpp +./test/qr_fullpivoting.cpp +./test/denseLM.cpp +./test/linearstructure.cpp +./test/rand.cpp +./test/conservative_resize.cpp +./test/eigensolver_generalized_real.cpp +./test/pastix_support.cpp +./test/sparse_solver.h +./test/num_dimensions.cpp +./test/simplicial_cholesky.cpp +./test/hessenberg.cpp +./test/array_reverse.cpp +./test/special_numbers.cpp +./test/array_for_matrix.cpp +./test/product_large.cpp +./test/resize.cpp +./test/sparse_solvers.cpp +./test/selfadjoint.cpp +./test/schur_real.cpp +./test/sparse_basic.cpp +./test/conjugate_gradient.cpp +./test/real_qz.cpp +./test/bandmatrix.cpp +./test/dense_storage.cpp +./test/permutationmatrices.cpp +./test/array_cwise.cpp +./test/qr_colpivoting.cpp +./test/array_replicate.cpp +./test/rvalue_types.cpp +./test/stable_norm.cpp +./test/geo_homogeneous.cpp +./test/main.h +./test/eigensolver_complex.cpp +./test/product_trmm.cpp +./test/bicgstab.cpp +./test/redux.cpp +./test/klu_support.cpp +./test/geo_alignedbox.cpp +./test/is_same_dense.cpp +./test/sparse_permutations.cpp +./test/sparse_vector.cpp +./test/diagonal.cpp +./test/sparse.h +./test/mapstride.cpp +./test/visitor.cpp +./test/geo_hyperplane.cpp +./test/bdcsvd.cpp +./test/product_trmv.cpp +./test/nestbyvalue.cpp +./test/array_of_string.cpp +./test/superlu_support.cpp +./test/sizeof.cpp +./test/boostmultiprec.cpp +./test/commainitializer.cpp +./test/constructor.cpp +./test/mixingtypes.cpp +./test/miscmatrices.cpp +./test/mapstaticmethods.cpp +./test/product_notemporary.cpp +./test/initializer_list_construction.cpp +./test/incomplete_cholesky.cpp +./test/geo_parametrizedline.cpp +./test/indexed_view.cpp +./test/qtvector.cpp +./test/sparselu.cpp +./test/sparse_product.cpp +./test/dynalloc.cpp +./test/fastmath.cpp +./test/prec_inverse_4x4.cpp +./test/umeyama.cpp +./test/reshape.cpp +./test/product_extra.cpp +./test/jacobi.cpp +./test/sparse_ref.cpp +./test/nomalloc.cpp +./test/spqr_support.cpp +./test/lscg.cpp +./test/cholesky.cpp +./test/eigensolver_generic.cpp +./test/geo_orthomethods.cpp +./test/svd_fill.h +./test/stl_iterators.cpp +./Eigen/src/MetisSupport/MetisSupport.h +./Eigen/src/CholmodSupport/CholmodSupport.h +./Eigen/src/QR/CompleteOrthogonalDecomposition.h +./Eigen/src/QR/FullPivHouseholderQR.h +./Eigen/src/QR/HouseholderQR.h +./Eigen/src/QR/ColPivHouseholderQR.h +./Eigen/src/plugins/CommonCwiseUnaryOps.h +./Eigen/src/plugins/BlockMethods.h +./Eigen/src/plugins/CommonCwiseBinaryOps.h +./Eigen/src/plugins/MatrixCwiseUnaryOps.h +./Eigen/src/plugins/IndexedViewMethods.h +./Eigen/src/plugins/MatrixCwiseBinaryOps.h +./Eigen/src/SVD/UpperBidiagonalization.h +./Eigen/src/SVD/SVDBase.h +./Eigen/src/SVD/BDCSVD.h +./Eigen/src/SVD/JacobiSVD.h +./Eigen/src/SparseLU/SparseLU_relax_snode.h +./Eigen/src/SparseLU/SparseLU_column_dfs.h +./Eigen/src/SparseLU/SparseLU_SupernodalMatrix.h +./Eigen/src/SparseLU/SparseLU_pivotL.h +./Eigen/src/SparseLU/SparseLU.h +./Eigen/src/SparseLU/SparseLU_pruneL.h +./Eigen/src/SparseLU/SparseLU_copy_to_ucol.h +./Eigen/src/SparseLU/SparseLU_heap_relax_snode.h +./Eigen/src/SparseLU/SparseLU_kernel_bmod.h +./Eigen/src/SparseLU/SparseLU_panel_dfs.h +./Eigen/src/SparseLU/SparseLU_panel_bmod.h +./Eigen/src/SparseLU/SparseLU_Structs.h +./Eigen/src/SparseLU/SparseLUImpl.h +./Eigen/src/SparseLU/SparseLU_Memory.h +./Eigen/src/SparseLU/SparseLU_column_bmod.h +./Eigen/src/SparseLU/SparseLU_gemm_kernel.h +./Eigen/src/SparseLU/SparseLU_Utils.h +./Eigen/src/OrderingMethods/Eigen_Colamd.h +./Eigen/src/OrderingMethods/Ordering.h +./Eigen/src/OrderingMethods/Amd.h +./Eigen/src/UmfPackSupport/UmfPackSupport.h +./Eigen/src/Geometry/Umeyama.h +./Eigen/src/Geometry/Transform.h +./Eigen/src/Geometry/OrthoMethods.h +./Eigen/src/Geometry/Hyperplane.h +./Eigen/src/Geometry/Homogeneous.h +./Eigen/src/Geometry/RotationBase.h +./Eigen/src/Geometry/EulerAngles.h +./Eigen/src/Geometry/Translation.h +./Eigen/src/Geometry/Rotation2D.h +./Eigen/src/Geometry/Scaling.h +./Eigen/src/Geometry/AlignedBox.h +./Eigen/src/Geometry/ParametrizedLine.h +./Eigen/src/Geometry/Quaternion.h +./Eigen/src/Geometry/AngleAxis.h +./Eigen/src/Geometry/arch/Geometry_SSE.h +./Eigen/src/KLUSupport/KLUSupport.h +./Eigen/src/misc/Kernel.h +./Eigen/src/misc/RealSvd2x2.h +./Eigen/src/misc/Image.h +./Eigen/src/StlSupport/details.h +./Eigen/src/StlSupport/StdList.h +./Eigen/src/StlSupport/StdDeque.h +./Eigen/src/StlSupport/StdVector.h +./Eigen/src/SparseQR/SparseQR.h +./Eigen/src/SuperLUSupport/SuperLUSupport.h +./Eigen/src/Householder/Householder.h +./Eigen/src/Householder/HouseholderSequence.h +./Eigen/src/Householder/BlockHouseholder.h +./Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h +./Eigen/src/Eigenvalues/EigenSolver.h +./Eigen/src/Eigenvalues/GeneralizedEigenSolver.h +./Eigen/src/Eigenvalues/Tridiagonalization.h +./Eigen/src/Eigenvalues/HessenbergDecomposition.h +./Eigen/src/Eigenvalues/RealQZ.h +./Eigen/src/Eigenvalues/RealSchur.h +./Eigen/src/Eigenvalues/ComplexSchur.h +./Eigen/src/Eigenvalues/ComplexEigenSolver.h +./Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h +./Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h +./Eigen/src/SparseCholesky/SimplicialCholesky.h +./Eigen/src/SparseCholesky/SimplicialCholesky_impl.h +./Eigen/src/Cholesky/LLT.h +./Eigen/src/Cholesky/LDLT.h +./Eigen/src/Jacobi/Jacobi.h +./Eigen/src/PaStiXSupport/PaStiXSupport.h +./Eigen/src/SPQRSupport/SuiteSparseQRSupport.h +./Eigen/src/LU/Determinant.h +./Eigen/src/LU/InverseImpl.h +./Eigen/src/LU/PartialPivLU.h +./Eigen/src/LU/arch/Inverse_SSE.h +./Eigen/src/LU/FullPivLU.h +./Eigen/src/Core/Map.h +./Eigen/src/Core/VectorwiseOp.h +./Eigen/src/Core/VectorBlock.h +./Eigen/src/Core/Array.h +./Eigen/src/Core/Assign.h +./Eigen/src/Core/Dot.h +./Eigen/src/Core/NestByValue.h +./Eigen/src/Core/CoreEvaluators.h +./Eigen/src/Core/ReturnByValue.h +./Eigen/src/Core/SelfCwiseBinaryOp.h +./Eigen/src/Core/GlobalFunctions.h +./Eigen/src/Core/Transpositions.h +./Eigen/src/Core/Fuzzy.h +./Eigen/src/Core/NoAlias.h +./Eigen/src/Core/CwiseNullaryOp.h +./Eigen/src/Core/NumTraits.h +./Eigen/src/Core/IndexedView.h +./Eigen/src/Core/ArrayWrapper.h +./Eigen/src/Core/util/SymbolicIndex.h +./Eigen/src/Core/util/BlasUtil.h +./Eigen/src/Core/util/Constants.h +./Eigen/src/Core/util/IntegralConstant.h +./Eigen/src/Core/util/ReshapedHelper.h +./Eigen/src/Core/util/StaticAssert.h +./Eigen/src/Core/util/IndexedViewHelper.h +./Eigen/src/Core/util/ConfigureVectorization.h +./Eigen/src/Core/util/ForwardDeclarations.h +./Eigen/src/Core/util/Meta.h +./Eigen/src/Core/util/XprHelper.h +./Eigen/src/Core/util/Macros.h +./Eigen/src/Core/util/Memory.h +./Eigen/src/Core/Product.h +./Eigen/src/Core/Replicate.h +./Eigen/src/Core/ArrayBase.h +./Eigen/src/Core/functors/NullaryFunctors.h +./Eigen/src/Core/functors/StlFunctors.h +./Eigen/src/Core/functors/AssignmentFunctors.h +./Eigen/src/Core/functors/UnaryFunctors.h +./Eigen/src/Core/functors/TernaryFunctors.h +./Eigen/src/Core/functors/BinaryFunctors.h +./Eigen/src/Core/Redux.h +./Eigen/src/Core/EigenBase.h +./Eigen/src/Core/SolverBase.h +./Eigen/src/Core/ProductEvaluators.h +./Eigen/src/Core/Block.h +./Eigen/src/Core/SolveTriangular.h +./Eigen/src/Core/ArithmeticSequence.h +./Eigen/src/Core/MatrixBase.h +./Eigen/src/Core/PlainObjectBase.h +./Eigen/src/Core/Transpose.h +./Eigen/src/Core/IO.h +./Eigen/src/Core/MathFunctions.h +./Eigen/src/Core/Stride.h +./Eigen/src/Core/MathFunctionsImpl.h +./Eigen/src/Core/StableNorm.h +./Eigen/src/Core/DiagonalProduct.h +./Eigen/src/Core/products/GeneralMatrixMatrix.h +./Eigen/src/Core/products/GeneralMatrixVector.h +./Eigen/src/Core/products/SelfadjointMatrixVector.h +./Eigen/src/Core/products/GeneralBlockPanelKernel.h +./Eigen/src/Core/products/TriangularSolverMatrix.h +./Eigen/src/Core/products/SelfadjointMatrixMatrix.h +./Eigen/src/Core/products/Parallelizer.h +./Eigen/src/Core/products/SelfadjointRank2Update.h +./Eigen/src/Core/products/TriangularMatrixMatrix.h +./Eigen/src/Core/products/TriangularMatrixVector.h +./Eigen/src/Core/products/SelfadjointProduct.h +./Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h +./Eigen/src/Core/products/TriangularSolverVector.h +./Eigen/src/Core/CwiseUnaryView.h +./Eigen/src/Core/CommaInitializer.h +./Eigen/src/Core/DenseStorage.h +./Eigen/src/Core/DenseBase.h +./Eigen/src/Core/PartialReduxEvaluator.h +./Eigen/src/Core/CoreIterators.h +./Eigen/src/Core/PermutationMatrix.h +./Eigen/src/Core/CwiseTernaryOp.h +./Eigen/src/Core/Reverse.h +./Eigen/src/Core/Reshaped.h +./Eigen/src/Core/Inverse.h +./Eigen/src/Core/TriangularMatrix.h +./Eigen/src/Core/BooleanRedux.h +./Eigen/src/Core/ForceAlignedAccess.h +./Eigen/src/Core/Ref.h +./Eigen/src/Core/StlIterators.h +./Eigen/src/Core/BandMatrix.h +./Eigen/src/Core/ConditionEstimator.h +./Eigen/src/Core/Diagonal.h +./Eigen/src/Core/DiagonalMatrix.h +./Eigen/src/Core/AssignEvaluator.h +./Eigen/src/Core/CwiseBinaryOp.h +./Eigen/src/Core/Visitor.h +./Eigen/src/Core/GenericPacketMath.h +./Eigen/src/Core/SelfAdjointView.h +./Eigen/src/Core/Random.h +./Eigen/src/Core/Solve.h +./Eigen/src/Core/arch/AltiVec/MathFunctions.h +./Eigen/src/Core/arch/AltiVec/PacketMath.h +./Eigen/src/Core/arch/AltiVec/Complex.h +./Eigen/src/Core/arch/MSA/MathFunctions.h +./Eigen/src/Core/arch/MSA/Complex.h +./Eigen/src/Core/arch/MSA/PacketMath.h +./Eigen/src/Core/arch/GPU/Half.h +./Eigen/src/Core/arch/GPU/PacketMathHalf.h +./Eigen/src/Core/arch/GPU/MathFunctions.h +./Eigen/src/Core/arch/GPU/PacketMath.h +./Eigen/src/Core/arch/GPU/TypeCasting.h +./Eigen/src/Core/arch/NEON/MathFunctions.h +./Eigen/src/Core/arch/NEON/Complex.h +./Eigen/src/Core/arch/NEON/PacketMath.h +./Eigen/src/Core/arch/NEON/TypeCasting.h +./Eigen/src/Core/arch/AVX/MathFunctions.h +./Eigen/src/Core/arch/AVX/TypeCasting.h +./Eigen/src/Core/arch/AVX/Complex.h +./Eigen/src/Core/arch/AVX/PacketMath.h +./Eigen/src/Core/arch/SYCL/InteropHeaders.h +./Eigen/src/Core/arch/SYCL/PacketMath.h +./Eigen/src/Core/arch/SYCL/TypeCasting.h +./Eigen/src/Core/arch/SYCL/MathFunctions.h +./Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h +./Eigen/src/Core/arch/Default/ConjHelper.h +./Eigen/src/Core/arch/Default/Settings.h +./Eigen/src/Core/arch/AVX512/MathFunctions.h +./Eigen/src/Core/arch/AVX512/PacketMath.h +./Eigen/src/Core/arch/AVX512/Complex.h +./Eigen/src/Core/arch/SSE/PacketMath.h +./Eigen/src/Core/arch/SSE/Complex.h +./Eigen/src/Core/arch/SSE/TypeCasting.h +./Eigen/src/Core/arch/SSE/MathFunctions.h +./Eigen/src/Core/arch/ZVector/MathFunctions.h +./Eigen/src/Core/arch/ZVector/PacketMath.h +./Eigen/src/Core/arch/ZVector/Complex.h +./Eigen/src/Core/arch/CUDA/Complex.h +./Eigen/src/Core/Swap.h +./Eigen/src/Core/MapBase.h +./Eigen/src/Core/GeneralProduct.h +./Eigen/src/Core/Matrix.h +./Eigen/src/Core/Select.h +./Eigen/src/Core/CwiseUnaryOp.h +./Eigen/src/Core/DenseCoeffsBase.h +./Eigen/src/SparseCore/SparseCwiseUnaryOp.h +./Eigen/src/SparseCore/TriangularSolver.h +./Eigen/src/SparseCore/SparseView.h +./Eigen/src/SparseCore/SparseSolverBase.h +./Eigen/src/SparseCore/SparseTranspose.h +./Eigen/src/SparseCore/SparseDenseProduct.h +./Eigen/src/SparseCore/SparseMap.h +./Eigen/src/SparseCore/SparseProduct.h +./Eigen/src/SparseCore/SparseUtil.h +./Eigen/src/SparseCore/SparsePermutation.h +./Eigen/src/SparseCore/SparseTriangularView.h +./Eigen/src/SparseCore/SparseSelfAdjointView.h +./Eigen/src/SparseCore/SparseMatrixBase.h +./Eigen/src/SparseCore/AmbiVector.h +./Eigen/src/SparseCore/SparseAssign.h +./Eigen/src/SparseCore/SparseRedux.h +./Eigen/src/SparseCore/SparseDot.h +./Eigen/src/SparseCore/SparseCwiseBinaryOp.h +./Eigen/src/SparseCore/SparseCompressedBase.h +./Eigen/src/SparseCore/SparseSparseProductWithPruning.h +./Eigen/src/SparseCore/SparseColEtree.h +./Eigen/src/SparseCore/SparseRef.h +./Eigen/src/SparseCore/CompressedStorage.h +./Eigen/src/SparseCore/MappedSparseMatrix.h +./Eigen/src/SparseCore/SparseDiagonalProduct.h +./Eigen/src/SparseCore/SparseFuzzy.h +./Eigen/src/SparseCore/ConservativeSparseSparseProduct.h +./Eigen/src/SparseCore/SparseMatrix.h +./Eigen/src/SparseCore/SparseVector.h +./Eigen/src/SparseCore/SparseBlock.h +./Eigen/src/IterativeLinearSolvers/SolveWithGuess.h +./Eigen/src/IterativeLinearSolvers/IterativeSolverBase.h +./Eigen/src/IterativeLinearSolvers/BiCGSTAB.h +./Eigen/src/IterativeLinearSolvers/ConjugateGradient.h +./Eigen/src/IterativeLinearSolvers/BasicPreconditioners.h +./Eigen/src/IterativeLinearSolvers/IncompleteCholesky.h +./Eigen/src/IterativeLinearSolvers/IncompleteLUT.h +./Eigen/src/IterativeLinearSolvers/LeastSquareConjugateGradient.h +./unsupported/Eigen/src/Eigenvalues/ArpackSelfAdjointEigenSolver.h +./unsupported/Eigen/src/SpecialFunctions/arch/GPU/GpuSpecialFunctions.h +./unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsHalf.h +./unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsImpl.h +./unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsFunctors.h +./unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsArrayAPI.h +./unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsPacketMath.h +./unsupported/Eigen/src/Polynomials/Companion.h +./unsupported/Eigen/src/Polynomials/PolynomialUtils.h +./unsupported/Eigen/src/Polynomials/PolynomialSolver.h +./unsupported/Eigen/src/Splines/Spline.h +./unsupported/Eigen/src/Splines/SplineFwd.h +./unsupported/Eigen/src/Splines/SplineFitting.h +./unsupported/Eigen/src/BVH/KdBVH.h +./unsupported/Eigen/src/BVH/BVAlgorithms.h +./unsupported/Eigen/src/AutoDiff/AutoDiffJacobian.h +./unsupported/Eigen/src/AutoDiff/AutoDiffVector.h +./unsupported/Eigen/src/AutoDiff/AutoDiffScalar.h +./unsupported/Eigen/src/MatrixFunctions/MatrixSquareRoot.h +./unsupported/Eigen/src/MatrixFunctions/MatrixPower.h +./unsupported/Eigen/src/MatrixFunctions/MatrixExponential.h +./unsupported/Eigen/src/MatrixFunctions/MatrixLogarithm.h +./unsupported/Eigen/src/MatrixFunctions/StemFunction.h +./unsupported/Eigen/src/MatrixFunctions/MatrixFunction.h +./unsupported/Eigen/src/Skyline/SkylineStorage.h +./unsupported/Eigen/src/Skyline/SkylineMatrixBase.h +./unsupported/Eigen/src/Skyline/SkylineMatrix.h +./unsupported/Eigen/src/Skyline/SkylineInplaceLU.h +./unsupported/Eigen/src/Skyline/SkylineProduct.h +./unsupported/Eigen/src/Skyline/SkylineUtil.h +./unsupported/Eigen/src/FFT/ei_kissfft_impl.h +./unsupported/Eigen/src/FFT/ei_fftw_impl.h +./unsupported/Eigen/src/LevenbergMarquardt/LevenbergMarquardt.h +./unsupported/Eigen/src/NonLinearOptimization/HybridNonLinearSolver.h +./unsupported/Eigen/src/NonLinearOptimization/LevenbergMarquardt.h +./unsupported/Eigen/src/KroneckerProduct/KroneckerTensorProduct.h +./unsupported/Eigen/src/NumericalDiff/NumericalDiff.h +./unsupported/Eigen/src/IterativeSolvers/IncompleteLU.h +./unsupported/Eigen/src/IterativeSolvers/MINRES.h +./unsupported/Eigen/src/IterativeSolvers/DGMRES.h +./unsupported/Eigen/src/IterativeSolvers/Scaling.h +./unsupported/Eigen/src/IterativeSolvers/GMRES.h +./unsupported/Eigen/src/MoreVectorization/MathFunctions.h +./unsupported/Eigen/src/EulerAngles/EulerAngles.h +./unsupported/Eigen/src/EulerAngles/EulerSystem.h +./unsupported/Eigen/src/SparseExtra/BlockOfDynamicSparseMatrix.h +./unsupported/Eigen/src/SparseExtra/DynamicSparseMatrix.h +./unsupported/Eigen/src/SparseExtra/BlockSparseMatrix.h +./unsupported/Eigen/src/SparseExtra/RandomSetter.h +./unsupported/Eigen/src/SparseExtra/MatrixMarketIterator.h +./unsupported/Eigen/src/SparseExtra/MarketIO.h +./unsupported/Eigen/CXX11/src/TensorSymmetry/StaticSymmetry.h +./unsupported/Eigen/CXX11/src/TensorSymmetry/Symmetry.h +./unsupported/Eigen/CXX11/src/TensorSymmetry/DynamicSymmetry.h +./unsupported/Eigen/CXX11/src/TensorSymmetry/util/TemplateGroupTheory.h +./unsupported/Eigen/CXX11/src/util/EmulateCXX11Meta.h +./unsupported/Eigen/CXX11/src/util/CXX11Meta.h +./unsupported/Eigen/CXX11/src/util/MaxSizeVector.h +./unsupported/Eigen/CXX11/src/util/EmulateArray.h +./unsupported/Eigen/CXX11/src/util/CXX11Workarounds.h +./unsupported/Eigen/CXX11/src/ThreadPool/ThreadYield.h +./unsupported/Eigen/CXX11/src/ThreadPool/NonBlockingThreadPool.h +./unsupported/Eigen/CXX11/src/ThreadPool/RunQueue.h +./unsupported/Eigen/CXX11/src/ThreadPool/ThreadCancel.h +./unsupported/Eigen/CXX11/src/ThreadPool/ThreadPoolInterface.h +./unsupported/Eigen/CXX11/src/ThreadPool/ThreadLocal.h +./unsupported/Eigen/CXX11/src/ThreadPool/Barrier.h +./unsupported/Eigen/CXX11/src/ThreadPool/EventCount.h +./unsupported/Eigen/CXX11/src/ThreadPool/ThreadEnvironment.h +./unsupported/Eigen/CXX11/src/Tensor/TensorRef.h +./unsupported/Eigen/CXX11/src/Tensor/TensorFixedSize.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclRun.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclTuple.h +./unsupported/Eigen/CXX11/src/Tensor/TensorTraits.h +./unsupported/Eigen/CXX11/src/Tensor/TensorStorage.h +./unsupported/Eigen/CXX11/src/Tensor/TensorTrace.h +./unsupported/Eigen/CXX11/src/Tensor/TensorDeviceThreadPool.h +./unsupported/Eigen/CXX11/src/Tensor/TensorReductionGpu.h +./unsupported/Eigen/CXX11/src/Tensor/TensorContractionThreadPool.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclPlaceHolderExpr.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclExprConstructor.h +./unsupported/Eigen/CXX11/src/Tensor/TensorIntDiv.h +./unsupported/Eigen/CXX11/src/Tensor/TensorExecutor.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclConvertToDeviceExpression.h +./unsupported/Eigen/CXX11/src/Tensor/Tensor.h +./unsupported/Eigen/CXX11/src/Tensor/TensorDeviceGpu.h +./unsupported/Eigen/CXX11/src/Tensor/TensorPatch.h +./unsupported/Eigen/CXX11/src/Tensor/TensorMorphing.h +./unsupported/Eigen/CXX11/src/Tensor/TensorInflation.h +./unsupported/Eigen/CXX11/src/Tensor/TensorStriding.h +./unsupported/Eigen/CXX11/src/Tensor/TensorScan.h +./unsupported/Eigen/CXX11/src/Tensor/TensorChipping.h +./unsupported/Eigen/CXX11/src/Tensor/TensorCustomOp.h +./unsupported/Eigen/CXX11/src/Tensor/TensorDeviceSycl.h +./unsupported/Eigen/CXX11/src/Tensor/TensorGenerator.h +./unsupported/Eigen/CXX11/src/Tensor/TensorReductionSycl.h +./unsupported/Eigen/CXX11/src/Tensor/TensorArgMaxSycl.h +./unsupported/Eigen/CXX11/src/Tensor/TensorConvolution.h +./unsupported/Eigen/CXX11/src/Tensor/TensorBase.h +./unsupported/Eigen/CXX11/src/Tensor/TensorDimensions.h +./unsupported/Eigen/CXX11/src/Tensor/TensorReduction.h +./unsupported/Eigen/CXX11/src/Tensor/TensorPadding.h +./unsupported/Eigen/CXX11/src/Tensor/TensorUInt128.h +./unsupported/Eigen/CXX11/src/Tensor/TensorArgMax.h +./unsupported/Eigen/CXX11/src/Tensor/TensorMeta.h +./unsupported/Eigen/CXX11/src/Tensor/TensorExpr.h +./unsupported/Eigen/CXX11/src/Tensor/TensorIO.h +./unsupported/Eigen/CXX11/src/Tensor/TensorContraction.h +./unsupported/Eigen/CXX11/src/Tensor/TensorDeviceDefault.h +./unsupported/Eigen/CXX11/src/Tensor/TensorReverse.h +./unsupported/Eigen/CXX11/src/Tensor/TensorShuffling.h +./unsupported/Eigen/CXX11/src/Tensor/TensorConvolutionSycl.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclFunctors.h +./unsupported/Eigen/CXX11/src/Tensor/TensorMap.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSycl.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclExtractFunctors.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclExtractAccessor.h +./unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h +./unsupported/Eigen/CXX11/src/Tensor/TensorConcatenation.h +./unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaDefines.h +./unsupported/Eigen/CXX11/src/Tensor/TensorInitializer.h +./unsupported/Eigen/CXX11/src/Tensor/TensorBlock.h +./unsupported/Eigen/CXX11/src/Tensor/TensorIndexList.h +./unsupported/Eigen/CXX11/src/Tensor/TensorGpuHipCudaUndefines.h +./unsupported/Eigen/CXX11/src/Tensor/TensorContractionMapper.h +./unsupported/Eigen/CXX11/src/Tensor/TensorCostModel.h +./unsupported/Eigen/CXX11/src/Tensor/TensorForcedEval.h +./unsupported/Eigen/CXX11/src/Tensor/TensorGlobalFunctions.h +./unsupported/Eigen/CXX11/src/Tensor/TensorContractionSycl.h +./unsupported/Eigen/CXX11/src/Tensor/TensorImagePatch.h +./unsupported/Eigen/CXX11/src/Tensor/TensorContractionBlocking.h +./unsupported/Eigen/CXX11/src/Tensor/TensorMacros.h +./unsupported/Eigen/CXX11/src/Tensor/TensorDevice.h +./unsupported/Eigen/CXX11/src/Tensor/TensorBroadcasting.h +./unsupported/Eigen/CXX11/src/Tensor/TensorSyclLeafCount.h +./unsupported/Eigen/CXX11/src/Tensor/TensorRandom.h +./unsupported/Eigen/CXX11/src/Tensor/TensorFFT.h +./unsupported/Eigen/CXX11/src/Tensor/TensorFunctors.h +./unsupported/Eigen/CXX11/src/Tensor/TensorContractionGpu.h +./unsupported/Eigen/CXX11/src/Tensor/TensorForwardDeclarations.h +./unsupported/Eigen/CXX11/src/Tensor/TensorDimensionList.h +./unsupported/Eigen/CXX11/src/Tensor/TensorConversion.h +./unsupported/Eigen/CXX11/src/Tensor/TensorEvalTo.h +./unsupported/Eigen/CXX11/src/Tensor/TensorAssign.h +./unsupported/Eigen/CXX11/src/Tensor/TensorLayoutSwap.h +./unsupported/Eigen/CXX11/src/FixedPoint/MatMatProduct.h +./unsupported/Eigen/CXX11/src/FixedPoint/MatMatProductNEON.h +./unsupported/Eigen/CXX11/src/FixedPoint/MatVecProduct.h +./unsupported/Eigen/CXX11/src/FixedPoint/FixedPointTypes.h +./unsupported/Eigen/CXX11/src/FixedPoint/MatMatProductAVX2.h +./unsupported/bench/bench_svd.cpp +./unsupported/test/cxx11_tensor_image_patch_sycl.cpp +./unsupported/test/cxx11_tensor_expr.cpp +./unsupported/test/FFTW.cpp +./unsupported/test/cxx11_tensor_reverse_sycl.cpp +./unsupported/test/cxx11_tensor_comparisons.cpp +./unsupported/test/cxx11_tensor_intdiv.cpp +./unsupported/test/autodiff.cpp +./unsupported/test/cxx11_tensor_executor.cpp +./unsupported/test/cxx11_tensor_reduction.cpp +./unsupported/test/cxx11_tensor_device_sycl.cpp +./unsupported/test/minres.cpp +./unsupported/test/cxx11_tensor_striding.cpp +./unsupported/test/cxx11_tensor_chipping.cpp +./unsupported/test/cxx11_tensor_convolution_sycl.cpp +./unsupported/test/openglsupport.cpp +./unsupported/test/cxx11_tensor_ifft.cpp +./unsupported/test/polynomialutils.cpp +./unsupported/test/cxx11_tensor_block_access.cpp +./unsupported/test/cxx11_tensor_block_eval.cpp +./unsupported/test/cxx11_tensor_block_io.cpp +./unsupported/test/cxx11_tensor_morphing.cpp +./unsupported/test/cxx11_tensor_casts.cpp +./unsupported/test/cxx11_tensor_shuffling_sycl.cpp +./unsupported/test/cxx11_tensor_morphing_sycl.cpp +./unsupported/test/forward_adolc.cpp +./unsupported/test/cxx11_tensor_layout_swap.cpp +./unsupported/test/cxx11_tensor_move.cpp +./unsupported/test/EulerAngles.cpp +./unsupported/test/cxx11_tensor_trace.cpp +./unsupported/test/alignedvector3.cpp +./unsupported/test/cxx11_tensor_lvalue.cpp +./unsupported/test/cxx11_tensor_argmax.cpp +./unsupported/test/cxx11_tensor_broadcast_sycl.cpp +./unsupported/test/autodiff_scalar.cpp +./unsupported/test/sparse_extra.cpp +./unsupported/test/cxx11_tensor_of_strings.cpp +./unsupported/test/cxx11_tensor_empty.cpp +./unsupported/test/cxx11_tensor_patch.cpp +./unsupported/test/cxx11_tensor_sycl.cpp +./unsupported/test/cxx11_tensor_forced_eval_sycl.cpp +./unsupported/test/cxx11_tensor_inflation_sycl.cpp +./unsupported/test/BVH.cpp +./unsupported/test/cxx11_tensor_generator.cpp +./unsupported/test/cxx11_meta.cpp +./unsupported/test/matrix_functions.h +./unsupported/test/kronecker_product.cpp +./unsupported/test/matrix_function.cpp +./unsupported/test/cxx11_tensor_thread_pool.cpp +./unsupported/test/cxx11_non_blocking_thread_pool.cpp +./unsupported/test/cxx11_tensor_fft.cpp +./unsupported/test/cxx11_tensor_assign.cpp +./unsupported/test/cxx11_tensor_simple.cpp +./unsupported/test/cxx11_tensor_of_complex.cpp +./unsupported/test/cxx11_tensor_inflation.cpp +./unsupported/test/cxx11_tensor_map.cpp +./unsupported/test/cxx11_tensor_shuffling.cpp +./unsupported/test/cxx11_tensor_padding.cpp +./unsupported/test/cxx11_tensor_argmax_sycl.cpp +./unsupported/test/matrix_square_root.cpp +./unsupported/test/dgmres.cpp +./unsupported/test/cxx11_tensor_custom_op_sycl.cpp +./unsupported/test/cxx11_tensor_reduction_sycl.cpp +./unsupported/test/cxx11_runqueue.cpp +./unsupported/test/cxx11_tensor_const.cpp +./unsupported/test/matrix_power.cpp +./unsupported/test/cxx11_tensor_contraction.cpp +./unsupported/test/cxx11_tensor_random.cpp +./unsupported/test/cxx11_tensor_volume_patch_sycl.cpp +./unsupported/test/cxx11_tensor_contract_sycl.cpp +./unsupported/test/cxx11_tensor_math.cpp +./unsupported/test/splines.cpp +./unsupported/test/cxx11_tensor_ref.cpp +./unsupported/test/cxx11_tensor_concatenation_sycl.cpp +./unsupported/test/gmres.cpp +./unsupported/test/cxx11_tensor_fixed_size.cpp +./unsupported/test/cxx11_tensor_custom_op.cpp +./unsupported/test/cxx11_tensor_generator_sycl.cpp +./unsupported/test/cxx11_tensor_uint128.cpp +./unsupported/test/cxx11_tensor_builtins_sycl.cpp +./unsupported/test/polynomialsolver.cpp +./unsupported/test/cxx11_tensor_concatenation.cpp +./unsupported/test/cxx11_tensor_broadcasting.cpp +./unsupported/test/cxx11_tensor_convolution.cpp +./unsupported/test/cxx11_tensor_forced_eval.cpp +./unsupported/test/levenberg_marquardt.cpp +./unsupported/test/cxx11_tensor_reverse.cpp +./unsupported/test/cxx11_tensor_notification.cpp +./unsupported/test/cxx11_tensor_patch_sycl.cpp +./unsupported/test/cxx11_tensor_image_patch.cpp +./unsupported/test/cxx11_tensor_scan.cpp +./unsupported/test/cxx11_tensor_padding_sycl.cpp +./unsupported/test/cxx11_tensor_index_list.cpp +./unsupported/test/cxx11_tensor_io.cpp +./unsupported/test/cxx11_tensor_mixed_indices.cpp +./unsupported/test/cxx11_tensor_striding_sycl.cpp +./unsupported/test/cxx11_tensor_of_const_values.cpp +./unsupported/test/cxx11_tensor_symmetry.cpp +./unsupported/test/cxx11_tensor_custom_index.cpp +./unsupported/test/cxx11_tensor_chipping_sycl.cpp +./unsupported/test/cxx11_tensor_roundings.cpp +./unsupported/test/matrix_exponential.cpp +./unsupported/test/cxx11_eventcount.cpp +./unsupported/test/special_functions.cpp +./unsupported/test/cxx11_tensor_dimension.cpp +./unsupported/test/cxx11_tensor_layout_swap_sycl.cpp +./lapack/eigenvalues.cpp +./lapack/single.cpp +./lapack/svd.cpp +./lapack/complex_single.cpp +./lapack/lu.cpp +./lapack/double.cpp +./lapack/complex_double.cpp +./lapack/cholesky.cpp +./lapack/lapack_common.h +./blas/level2_impl.h +./blas/PackedTriangularMatrixVector.h +./blas/level3_impl.h +./blas/complex_double.cpp +./blas/common.h +./blas/GeneralRank1Update.h +./blas/double.cpp +./blas/complex_single.cpp +./blas/Rank2Update.h +./blas/level1_impl.h +./blas/level2_real_impl.h +./blas/level1_real_impl.h +./blas/single.cpp +./blas/PackedSelfadjointProduct.h +./blas/BandTriangularSolver.h +./blas/level2_cplx_impl.h +./blas/PackedTriangularSolverVector.h +./blas/level1_cplx_impl.h +./bench/analyze-blocking-sizes.cpp +./bench/BenchTimer.h +./bench/spbench/spbenchsolver.h +./bench/spbench/spbenchstyle.h +./bench/benchFFT.cpp +./bench/eig33.cpp +./bench/benchmark-blocking-sizes.cpp +./demos/opengl/quaternion_demo.cpp +./demos/opengl/camera.h +./demos/opengl/gpuhelper.cpp +./demos/opengl/gpuhelper.h +./demos/opengl/icosphere.cpp +./demos/opengl/quaternion_demo.h +./demos/opengl/trackball.h +./demos/opengl/icosphere.h +./demos/opengl/camera.cpp +./demos/opengl/trackball.cpp +./demos/mix_eigen_and_c/binary_library.h +./demos/mix_eigen_and_c/binary_library.cpp +./demos/mandelbrot/mandelbrot.cpp +./demos/mandelbrot/mandelbrot.h + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + +---------------------------------------------------------------------- +Following applies to: +./doc/UsingIntelMKL.dox +./doc/UsingIntelMKL.dox +./Eigen/src/Eigenvalues/ComplexSchur_MKL.h +./Eigen/src/Eigenvalues/ComplexSchur_MKL.h +./Eigen/src/Eigenvalues/SelfAdjointEigenSolver_MKL.h +./Eigen/src/Eigenvalues/SelfAdjointEigenSolver_MKL.h +./Eigen/src/Eigenvalues/RealSchur_MKL.h +./Eigen/src/Eigenvalues/RealSchur_MKL.h +./Eigen/src/LU/arch/Inverse_SSE.h +./Eigen/src/LU/arch/Inverse_SSE.h +./Eigen/src/LU/PartialPivLU_MKL.h +./Eigen/src/LU/PartialPivLU_MKL.h +./Eigen/src/QR/HouseholderQR_MKL.h +./Eigen/src/QR/HouseholderQR_MKL.h +./Eigen/src/QR/ColPivHouseholderQR_MKL.h +./Eigen/src/QR/ColPivHouseholderQR_MKL.h +./Eigen/src/SVD/JacobiSVD_MKL.h +./Eigen/src/SVD/JacobiSVD_MKL.h +./Eigen/src/PardisoSupport/PardisoSupport.h +./Eigen/src/PardisoSupport/PardisoSupport.h +./Eigen/src/Core/Assign_MKL.h +./Eigen/src/Core/Assign_MKL.h +./Eigen/src/Core/products/SelfadjointMatrixVector_MKL.h +./Eigen/src/Core/products/SelfadjointMatrixVector_MKL.h +./Eigen/src/Core/products/GeneralMatrixVector_MKL.h +./Eigen/src/Core/products/GeneralMatrixVector_MKL.h +./Eigen/src/Core/products/SelfadjointMatrixMatrix_MKL.h +./Eigen/src/Core/products/SelfadjointMatrixMatrix_MKL.h +./Eigen/src/Core/products/TriangularMatrixMatrix_MKL.h +./Eigen/src/Core/products/TriangularMatrixMatrix_MKL.h +./Eigen/src/Core/products/GeneralMatrixMatrix_MKL.h +./Eigen/src/Core/products/GeneralMatrixMatrix_MKL.h +./Eigen/src/Core/products/TriangularMatrixVector_MKL.h +./Eigen/src/Core/products/TriangularMatrixVector_MKL.h +./Eigen/src/Core/products/GeneralMatrixMatrixTriangular_MKL.h +./Eigen/src/Core/products/GeneralMatrixMatrixTriangular_MKL.h +./Eigen/src/Core/products/TriangularSolverMatrix_MKL.h +./Eigen/src/Core/products/TriangularSolverMatrix_MKL.h +./Eigen/src/Core/util/MKL_support.h +./Eigen/src/Core/util/MKL_support.h +./Eigen/src/Cholesky/LLT_MKL.h +./Eigen/src/Cholesky/LLT_MKL.h + +/* + Copyright (c) 2011, Intel Corporation. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. * + Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. * Neither the name of Intel Corporation nor the + names of its contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +---------------------------------------------------------------------- +Following applies to: +./unsupported/Eigen/src/LevenbergMarquardt/LevenbergMarquardt.h +./unsupported/Eigen/src/LevenbergMarquardt/LMcovar.h +./unsupported/Eigen/src/LevenbergMarquardt/LMonestep.h +./unsupported/Eigen/src/LevenbergMarquardt/LMpar.h +./unsupported/Eigen/src/LevenbergMarquardt/LMqrsolv.h + +Minpack Copyright Notice (1999) University of Chicago. All rights +reserved + +Redistribution and use in source and binary forms, with or +without modification, are permitted provided that the +following conditions are met: + +1. Redistributions of source code must retain the above +copyright notice, this list of conditions and the following +disclaimer. + +2. Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials +provided with the distribution. + +3. The end-user documentation included with the +redistribution, if any, must include the following +acknowledgment: + + "This product includes software developed by the + University of Chicago, as Operator of Argonne National + Laboratory. + +Alternately, this acknowledgment may appear in the software +itself, if and wherever such third-party acknowledgments +normally appear. + +4. WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" +WITHOUT WARRANTY OF ANY KIND. THE COPYRIGHT HOLDER, THE +UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND +THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE +OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY +OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR +USEFULNESS OF THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF +THE SOFTWARE WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS, (4) +DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION +UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL +BE CORRECTED. + +5. LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT +HOLDER, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF +ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, +INCIDENTAL, CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF +ANY KIND OR NATURE, INCLUDING BUT NOT LIMITED TO LOSS OF +PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, WHETHER +SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT +(INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE, +EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE +POSSIBILITY OF SUCH LOSS OR DAMAGES. + + +Copyright (c) 1992-2013 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. +Copyright (c) 2000-2013 The University of California Berkeley. All + rights reserved. +Copyright (c) 2006-2013 The University of Colorado Denver. All rights + reserved. + +Following applies to: +./lapack/*.c + +$COPYRIGHT$ + +Additional copyrights may follow + +$HEADER$ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + +- Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +The copyright holders provide no reassurances that the source code +provided does not infringe any patent, copyright, or any other +intellectual property rights of third parties. The copyright holders +disclaim any liability to any recipient for claims brought against +recipient by any third party for infringement of that parties +intellectual property rights. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +---------------------------------------------------------------------- +Following applies to: + +./cmake/FindComputeCpp.cmake + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +License for Farmhash: +// Copyright (c) 2014 Google, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +-------------------------------------------------------------------------------- +License for Flatbuffers: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +License for highwayhash: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +-------------------------------------------------------------------------------- +License for libjpeg-turbo: +For a summary of these license terms, see LICENSE.md. + +libjpeg-turbo license +--------------------- + This license covers the TurboJPEG API library and associated programs. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +- Neither the name of the libjpeg-turbo Project nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + +libjpeg license, Independent JPEG Group +--------------------------------------- + This license applies to the libjpeg API library and associated programs + (any code inherited from libjpeg, and any modifications to that code.) + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-2016, Thomas G. Lane, Guido Vollbeding. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +The Unix configuration script "configure" was produced with GNU Autoconf. +It is copyright by the Free Software Foundation but is freely distributable. +The same holds for its supporting scripts (config.guess, config.sub, +ltmain.sh). Another support script, install-sh, is copyright by X Consortium +but is also freely distributable. + +The IJG distribution formerly included code to read and write GIF files. +To avoid entanglement with the Unisys LZW patent (now expired), GIF reading +support has been removed altogether, and the GIF writer has been simplified +to produce "uncompressed GIFs". This technique does not use the LZW +algorithm; the resulting GIF files are larger than usual, but are readable +by all standard GIF decoders. + +We are required to state that + "The Graphics Interchange Format(c) is the Copyright property of + CompuServe Incorporated. GIF(sm) is a Service Mark property of + CompuServe Incorporated." + + +zlib License +------------ + This license is a subset of the other two, and it covers the libjpeg-turbo + SIMD extensions. + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +-------------------------------------------------------------------------------- +License for fft2d: +Copyright(C) 1997,2001 Takuya OOURA (email: ooura@kurims.kyoto-u.ac.jp). +You may use, copy, modify this code for any purpose and +without fee. You may distribute this ORIGINAL package. + +-------------------------------------------------------------------------------- +License for giflib: +The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +-------------------------------------------------------------------------------- +License for llvm-project: +Copied from llvm-project/llvm/LICENSE.TXT: +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== +============================================================================== +Copied from llvm-project/llvm/utils/unittest/googletest/LICENSE.TXT and +llvm-project/llvm/utils/unittest/googlemock/LICENSE.txt: + +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +============================================================================== +============================================================================== +Copied from llvm-project/llvm/lib/Support/COPYRIGHT.regex: +$OpenBSD: COPYRIGHT,v 1.3 2003/06/02 20:18:36 millert Exp $ + +Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved. +This software is not subject to any license of the American Telephone +and Telegraph Company or of the Regents of the University of California. + +Permission is granted to anyone to use this software for any purpose on +any computer system, and to alter it and redistribute it, subject +to the following restrictions: + +1. The author is not responsible for the consequences of use of this + software, no matter how awful, even if they arise from flaws in it. + +2. The origin of this software must not be misrepresented, either by + explicit claim or by omission. Since few users ever read sources, + credits must appear in the documentation. + +3. Altered versions must be plainly marked as such, and must not be + misrepresented as being the original software. Since few users + ever read sources, credits must appear in the documentation. + +4. This notice may not be removed or altered. + +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +/*- + * Copyright (c) 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)COPYRIGHT 8.1 (Berkeley) 3/16/94 + */ + +============================================================================== +============================================================================== +Copied from llvm-project/llvm/include/llvm/Support/LICENSE.TXT: + +LLVM System Interface Library +------------------------------------------------------------------------------- +The LLVM System Interface Library is licensed under the Illinois Open Source +License and has the following additional copyright: + +Copyright (C) 2004 eXtensible Systems, Inc. + +============================================================================== +============================================================================== +Copied from llvm-project/llvm/test/YAMLParser/LICENSE.txt: + +Copyright (c) 2006 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +-------------------------------------------------------------------------------- +License for mkl_dnn: + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +------------------------------------------------------------------------ + +The below applies to src/cpu/xbyak/*. + + +Copyright (c) 2007 MITSUNARI Shigeo +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. +Neither the name of the copyright owner nor the names of its contributors may +be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +ソースコード形式かバイナリ形式か、変更するかしないかを問わず、以下の条件を満た +す場合に限り、再頒布および使用が許可されます。 + +ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、および下記免責条項 +を含めること。 +バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の資料に、上記の著作 +権表示、本条件一覧、および下記免責条項を含めること。 +書面による特別の許可なしに、本ソフトウェアから派生した製品の宣伝または販売促進 +に、著作権者の名前またはコントリビューターの名前を使用してはならない。 +本ソフトウェアは、著作権者およびコントリビューターによって「現状のまま」提供さ +れており、明示黙示を問わず、商業的な使用可能性、および特定の目的に対する適合性 +に関する暗黙の保証も含め、またそれに限定されない、いかなる保証もありません。 +著作権者もコントリビューターも、事由のいかんを問わず、 損害発生の原因いかんを +問わず、かつ責任の根拠が契約であるか厳格責任であるか(過失その他の)不法行為で +あるかを問わず、仮にそのような損害が発生する可能性を知らされていたとしても、 +本ソフトウェアの使用によって発生した(代替品または代用サービスの調達、使用の +喪失、データの喪失、利益の喪失、業務の中断も含め、またそれに限定されない)直接 +損害、間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害について、 +一切責任を負わないものとします。 + +-------------------------------------------------------------------------------- +License for nsync: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +License for TensorFlow: +Copyright 2019 The TensorFlow Authors. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +License for pybind11: +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. + +-------------------------------------------------------------------------------- +License for snappy: +Copyright 2011, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=== + +Some of the benchmark data in util/zippy/testdata is licensed differently: + + - fireworks.jpeg is Copyright 2013 Steinar H. Gunderson, and + is licensed under the Creative Commons Attribution 3.0 license + (CC-BY-3.0). See https://creativecommons.org/licenses/by/3.0/ + for more information. + + - kppkn.gtb is taken from the Gaviota chess tablebase set, and + is licensed under the MIT License. See + https://sites.google.com/site/gaviotachessengine/Home/endgame-tablebases-1 + for more information. + + - paper-100k.pdf is an excerpt (bytes 92160 to 194560) from the paper + “Combinatorial Modeling of Chromatin Features Quantitatively Predicts DNA + Replication Timing in _Drosophila_” by Federico Comoglio and Renato Paro, + which is licensed under the CC-BY license. See + http://www.ploscompbiol.org/static/license for more ifnormation. + + - alice29.txt, asyoulik.txt, plrabn12.txt and lcet10.txt are from Project + Gutenberg. The first three have expired copyrights and are in the public + domain; the latter does not have expired copyright, but is still in the + public domain according to the license information + (http://www.gutenberg.org/ebooks/53). + +-------------------------------------------------------------------------------- +License for upb: + +Copyright (c) 2009-2011, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Google Inc. nor the names of any other + contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL GOOGLE INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +-------------------------------------------------------------------------------- +License for zlib: +(extracted from README, except for match.S) + +Copyright notice: + + (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + +(extracted from match.S, for match.S only) + +Copyright (C) 1998, 2007 Brian Raiter + +This software is provided 'as-is', without any express or implied +warranty. In no event will the author be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. diff --git a/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/METADATA b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..cd71462f9562ea648989a2c4b496d04920417a91 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/METADATA @@ -0,0 +1,38 @@ +Metadata-Version: 2.2 +Name: jaxlib +Version: 0.6.2 +Summary: XLA library for JAX +Home-page: https://github.com/jax-ml/jax +Author: JAX team +Author-email: jax-dev@google.com +License: Apache-2.0 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE.txt +Requires-Dist: scipy>=1.12 +Requires-Dist: numpy>=1.26 +Requires-Dist: ml_dtypes>=0.5.0 +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# jaxlib: support library for JAX + +jaxlib is the support library for JAX. While JAX itself is a pure Python package, +jaxlib contains the binary (C/C++) parts of the library, including Python bindings, +the XLA compiler, the PJRT runtime, and a handful of handwritten kernels. +For more information, including installation and build instructions, refer to main +JAX README: https://github.com/jax-ml/jax/. diff --git a/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/RECORD b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5ffd305aaa302728e89a444874f66e0407c517cb --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/RECORD @@ -0,0 +1,180 @@ +jaxlib-0.6.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jaxlib-0.6.2.dist-info/LICENSE.txt,sha256=49hoiix11OM2QcyIBGqKFZPueYIkEfpFp70y43-EfSk,229029 +jaxlib-0.6.2.dist-info/METADATA,sha256=PQ86qjSlxOeh8fZfsTa68zfvYP0ynnzcBz6jOqRX4as,1356 +jaxlib-0.6.2.dist-info/RECORD,, +jaxlib-0.6.2.dist-info/WHEEL,sha256=A8mRFNvJcDL8dRPZ6k2ICKEOXwE8pzYFXYxEla0rR0g,101 +jaxlib-0.6.2.dist-info/top_level.txt,sha256=CI2zJo00KhS7K9sB-iBQXkCb4HWO44Q-xte8CXUhKD0,7 +jaxlib/__init__.py,sha256=Kls3sryYAnafRcpD3nzcGotTLwr9K_lUITGraPZJxKM,629 +jaxlib/__pycache__/__init__.cpython-312.pyc,, +jaxlib/__pycache__/cpu_sparse.cpython-312.pyc,, +jaxlib/__pycache__/gpu_common_utils.cpython-312.pyc,, +jaxlib/__pycache__/gpu_linalg.cpython-312.pyc,, +jaxlib/__pycache__/gpu_prng.cpython-312.pyc,, +jaxlib/__pycache__/gpu_rnn.cpython-312.pyc,, +jaxlib/__pycache__/gpu_solver.cpython-312.pyc,, +jaxlib/__pycache__/gpu_sparse.cpython-312.pyc,, +jaxlib/__pycache__/gpu_triton.cpython-312.pyc,, +jaxlib/__pycache__/hlo_helpers.cpython-312.pyc,, +jaxlib/__pycache__/lapack.cpython-312.pyc,, +jaxlib/__pycache__/plugin_support.cpython-312.pyc,, +jaxlib/__pycache__/version.cpython-312.pyc,, +jaxlib/__pycache__/xla_client.cpython-312.pyc,, +jaxlib/_jax.pyd,sha256=HV7mE5GGWP2Z_r2XIhwCKMPQeE9K5quzk1YAlksJJ8o,8704 +jaxlib/_pretty_printer.pyd,sha256=-TusZQvmkBzO4bR86KCkULCw5TUBqBS_GzPVeAiBJ08,8704 +jaxlib/_profiler.pyd,sha256=BfoT3FB8osKPxCVMQIyAUs8h5haP8Rs0iQITkVVi-Os,8704 +jaxlib/cpu/_lapack.pyd,sha256=Om6rfozu2TO77oBes3HLFCjoxHEEVWvbtPBtnQfeEv0,997888 +jaxlib/cpu/_sparse.pyd,sha256=sO8ulQmvTCa_omHIKQWyKLswbAIoQrF203fImHDNjb4,250880 +jaxlib/cpu_feature_guard.pyd,sha256=NwfHUaPdoCstVtwHtLnKULAG2FjEDFU-bHerz8GJxks,9728 +jaxlib/cpu_sparse.py,sha256=xcXEe6BpvBIySyfEjSpIaZkfUFrs5JVwSeAk9kf94DY,849 +jaxlib/gpu_common_utils.py,sha256=xxA1St-TNpnh5lZpS8OJPQCSZi9TuhZCvObmYq1X8f0,905 +jaxlib/gpu_linalg.py,sha256=4S1MeEdIEEFYFNLUaeNdkeGq2RsPpXqY-Y-JBKRolHc,1394 +jaxlib/gpu_prng.py,sha256=bkM3t1W9lb1edT1Iv-tFnt6arwCjGrzaWgtOaBuZ4Pc,1181 +jaxlib/gpu_rnn.py,sha256=6-h1SRWpXo70THabxhYStycdtaAb8HEKAFiZPnphCA8,6410 +jaxlib/gpu_solver.py,sha256=dKQbwTgq4ePF_lWJ_Uo08lfuU0xKwIRsyqn4me5QPQ4,2141 +jaxlib/gpu_sparse.py,sha256=Lm30SvusJi9aQU8M-XMGcF_FgatLNaQbsNNReK0hWFw,1615 +jaxlib/gpu_triton.py,sha256=QGUCMsmUnKuzvKkvq-T_WGGYiu6laiLy9CnLNdv0uHA,2079 +jaxlib/hlo_helpers.py,sha256=q9Hj8fq3liu2AsImtYZWk4jpDo8SscMq6lhQAOJhOCU,10860 +jaxlib/include/xla/ffi/api/api.h,sha256=gIBq_wKLkFZcVzeE8D6EsQ5my-YBbx4EhcSKUYMS4CI,74125 +jaxlib/include/xla/ffi/api/c_api.h,sha256=FcKUNuFUT4-XEeSw838sC1FiPUe1bVDSzEOZ7t2L6ac,26130 +jaxlib/include/xla/ffi/api/ffi.h,sha256=Dc4m1iZv1sZlrYz0ja40W7GilhCYGYjahz337GhYb2c,55078 +jaxlib/jax_common.dll,sha256=CjVejAuaMiRXHpdhIZj8rDF58OqPwnYQHocq3gXrm5o,207744000 +jaxlib/lapack.py,sha256=SeyPky7jJ9dPxX-oZ7MadlQwzBLHxcuqerwRFst563o,1820 +jaxlib/mlir/__pycache__/ir.cpython-312.pyc,, +jaxlib/mlir/__pycache__/passmanager.cpython-312.pyc,, +jaxlib/mlir/_mlir_libs/__init__.py,sha256=L2l-Jz1n7h70j3LaMC1IuiTSLgjY6bM0IGZpU4eSRXs,8994 +jaxlib/mlir/_mlir_libs/__pycache__/__init__.cpython-312.pyc,, +jaxlib/mlir/_mlir_libs/_chlo.pyd,sha256=J0oCwQ7fJkBQ8CYq8Ff37OdWm1ZhSIbD0hJqclgWTKs,8704 +jaxlib/mlir/_mlir_libs/_mlir.pyd,sha256=DT_paoVBCwlS63UAbuX3zL2Qnd8CmLZwTmiFzzI6rhc,8704 +jaxlib/mlir/_mlir_libs/_mlirDialectsGPU.pyd,sha256=En2upZKdFwoWLV5RunaU_UdhkELdOrnu7ULUtO01S3U,8704 +jaxlib/mlir/_mlir_libs/_mlirDialectsLLVM.pyd,sha256=XEWkSLXdI-M2Rsbf_G0ws_iajn7-w7zn2P3yNIRjWqQ,8704 +jaxlib/mlir/_mlir_libs/_mlirDialectsNVGPU.pyd,sha256=pvhv4_s87f0QoHHzh9FV5pn8Gna0_Rk6g57rguuZkbc,8704 +jaxlib/mlir/_mlir_libs/_mlirDialectsSparseTensor.pyd,sha256=Fsg7w2UXmyXY0IkSZWSsp6FMHT4Vb826OufTspu6KzQ,8704 +jaxlib/mlir/_mlir_libs/_mlirGPUPasses.pyd,sha256=DypRTthEcGwh8Zf5uCX-SEisbfSeI4k-MsraOACrAfk,8704 +jaxlib/mlir/_mlir_libs/_mlirHlo.pyd,sha256=etxcXhY7ov83pa9n_PsQDpRShCE5qDV7RXLYCrei7sY,8704 +jaxlib/mlir/_mlir_libs/_mlirSparseTensorPasses.pyd,sha256=ht6D9I3-ulCa7qvt6Zc1MVzvwSiKqa7VyzsyKcJCzYw,8704 +jaxlib/mlir/_mlir_libs/_mosaic_gpu_ext.pyd,sha256=AndIWG5eSU2o1Qgg_jf7YO7sOWn4QwmTnnLDkkH0z_s,8704 +jaxlib/mlir/_mlir_libs/_sdy.pyd,sha256=LMwLqkLZ1CXnG4L5DM4fUznVbhM1yBfiC-eeycvbf-I,8704 +jaxlib/mlir/_mlir_libs/_stablehlo.pyd,sha256=s4QV-RgwZq5bcW2heIx2A4eOU3dKR_OHrvvJM1tiv20,8704 +jaxlib/mlir/_mlir_libs/_tpu_ext.pyd,sha256=-c2tc4UWxSzf2c6fS24NqL66enKj3fEvBkgH1tOSnQE,8704 +jaxlib/mlir/_mlir_libs/register_jax_dialects.pyd,sha256=qjczOrX22NudcXvgk4dCqFgS55J0Xf4HF6E7ksbA9kk,8704 +jaxlib/mlir/dialects/__pycache__/_arith_enum_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_arith_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_builtin_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_cf_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_chlo_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_func_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_gpu_enum_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_gpu_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_llvm_enum_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_llvm_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_math_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_memref_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_mhlo_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_nvgpu_enum_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_nvgpu_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_nvvm_enum_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_nvvm_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_ods_common.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_scf_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_sdy_enums_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_sdy_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_sparse_tensor_enum_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_sparse_tensor_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_stablehlo_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_vector_enum_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/_vector_ops_gen.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/arith.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/builtin.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/cf.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/chlo.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/func.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/llvm.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/math.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/memref.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/mhlo.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/nvgpu.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/nvvm.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/scf.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/sdy.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/sparse_tensor.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/stablehlo.cpython-312.pyc,, +jaxlib/mlir/dialects/__pycache__/vector.cpython-312.pyc,, +jaxlib/mlir/dialects/_arith_enum_gen.py,sha256=k0ig1K5fOGncnTvhfxXfaCW6iRDedPx_a7UOZN6CuT0,7963 +jaxlib/mlir/dialects/_arith_ops_gen.py,sha256=Fsi9PVjfpmb06L4eEZWKgRbEvnf3Ud_pY72l9ruOvWY,67333 +jaxlib/mlir/dialects/_builtin_ops_gen.py,sha256=MmjhGYcjOaaEA33L1xD25uRWM3DpfixJ6hJch9thrwg,4323 +jaxlib/mlir/dialects/_cf_ops_gen.py,sha256=C5z77Xclyx10frxiY2joEWMZ8AIW2RFenH-z7KuHdno,8241 +jaxlib/mlir/dialects/_chlo_ops_gen.py,sha256=gPRvCOEokg-moisc_NwreVNm-v6cxspbtSBjCVu2i-E,70925 +jaxlib/mlir/dialects/_func_ops_gen.py,sha256=XWa43eBYkj6rI--RKqnvu-pjEdI3PnCk5bOsA10NM4g,14692 +jaxlib/mlir/dialects/_gpu_enum_gen.py,sha256=Cbsw4OioBnp65DdGKlXY_i_cKRNTWbK06yHoot6VMko,11698 +jaxlib/mlir/dialects/_gpu_ops_gen.py,sha256=4Ar8ObZa1M88pZbOGU6ZJ58Jq1atrN_5Xj2P_VoB4os,152033 +jaxlib/mlir/dialects/_llvm_enum_gen.py,sha256=MkQpueLP0OrSybRADsVcAA0ELRbXMjbnyElYECLUPf8,29979 +jaxlib/mlir/dialects/_llvm_ops_gen.py,sha256=QXccqVBUr5XfhMi_82_8-4D9cgOWRt-gOuTl2E55YGk,522168 +jaxlib/mlir/dialects/_math_ops_gen.py,sha256=Qp3bDQcgBKDT1qZ9w5ZvNT0QYU2C512-lLdTVQndB6w,65179 +jaxlib/mlir/dialects/_memref_ops_gen.py,sha256=gCIeQi4gsGCZ7K5MDue8lS-V9Rz17_Di2wTI4XiEtuo,54042 +jaxlib/mlir/dialects/_mhlo_ops_gen.py,sha256=wz1SzhTmEoDIx5pviTrby0eyFyVY3TMipDAoXMlgsuU,249851 +jaxlib/mlir/dialects/_nvgpu_enum_gen.py,sha256=AjOSgSefT6MAT3dl5DaOz_tJs0DHfPr7FxAdcloBuP4,4641 +jaxlib/mlir/dialects/_nvgpu_ops_gen.py,sha256=wBSPSrtiCGu19AheAD1sVXd4p6cgVPrQU3tiyIbKr-0,41355 +jaxlib/mlir/dialects/_nvvm_enum_gen.py,sha256=ozS3rA4FQry0AN5i3dzt9AuojLDNx1w-3Mi1lOizUtw,26905 +jaxlib/mlir/dialects/_nvvm_ops_gen.py,sha256=k9WE7sbcKiKYZwL4nMEeOkFlJ7pTLm2jOH6V_iGCwQ8,238306 +jaxlib/mlir/dialects/_ods_common.py,sha256=SLRWUWUEKpOqMfVZ6WfKHYGtuBlZeKJ7OJ5bg7RRsMY,10866 +jaxlib/mlir/dialects/_scf_ops_gen.py,sha256=MWRdW04nUl5jTtlUquuf701_wvzO0Uf8hui1Bwv9yMY,19735 +jaxlib/mlir/dialects/_sdy_enums_gen.py,sha256=5eR2g5GfSQsBzAa8jJpaeVxBSJ7cmoPbU-2bx382r6U,937 +jaxlib/mlir/dialects/_sdy_ops_gen.py,sha256=WSCUOkVoA0XCmXNaXaKqewlp-l0Qe9-Cl4zHIDu4xpg,31447 +jaxlib/mlir/dialects/_sparse_tensor_enum_gen.py,sha256=WDOGE83oEridRekIHuVZdVAqD329ER1pREWAAT8rrCM,3275 +jaxlib/mlir/dialects/_sparse_tensor_ops_gen.py,sha256=Y_uiEQEXjUfDhpeBDFIelDIi9mCvs5K8kNTUjNXyOmE,57496 +jaxlib/mlir/dialects/_stablehlo_ops_gen.py,sha256=bkkngaX3Y_RT0aYi6r0rLcdvCZrdimBy5zp1JXy0Px0,220570 +jaxlib/mlir/dialects/_vector_enum_gen.py,sha256=IdZk0Fn8RrXfTec1cJx-v3NpkP4w6l-TGdzn4dFOoFY,3505 +jaxlib/mlir/dialects/_vector_ops_gen.py,sha256=bkAFX1VFeuC7YTFSP0KQ-UXApMuMzIU48zGaWF2fSrg,73168 +jaxlib/mlir/dialects/arith.py,sha256=zuzjO6R9cGJbeUfwhCmfMp3Q7nAxSohA2lGM-5igvyY,3585 +jaxlib/mlir/dialects/builtin.py,sha256=m_fRViO8UAnS8Y9m0kG17fydx-Q-2p57ujAkNa-OxD0,1280 +jaxlib/mlir/dialects/cf.py,sha256=HQdeGqEsnlBAH0GPO73cuv2ugPWRJlWxzZ68kL3CnQE,229 +jaxlib/mlir/dialects/chlo.py,sha256=qFpdqIlfQB8B-dCBaHPLKPt9hIgy0HoZcE1Lm-RZUHE,1025 +jaxlib/mlir/dialects/func.py,sha256=Zo4R0d9iDxyW8IgUKjVQV7rWVYEKClWP8JkUVo031Es,12900 +jaxlib/mlir/dialects/gpu/__init__.py,sha256=vRpq5LMVUDWQ8NcNabAGvtgvb_1xcHKLPRAWl3Dtd5U,306 +jaxlib/mlir/dialects/gpu/__pycache__/__init__.cpython-312.pyc,, +jaxlib/mlir/dialects/gpu/passes/__init__.py,sha256=s6IJ42EIx__6r6ph-eo0F-FzCu7c1VrAHcFppER-flQ,262 +jaxlib/mlir/dialects/gpu/passes/__pycache__/__init__.cpython-312.pyc,, +jaxlib/mlir/dialects/llvm.py,sha256=mrrz4IzhyTK1waZZDg0w1c5WMnOA1opKUH7k5l56C2U,584 +jaxlib/mlir/dialects/math.py,sha256=UdBTamN3x7tucU7WWcncLCFx_yliMs1_vAM9M5p_AIs,231 +jaxlib/mlir/dialects/memref.py,sha256=WgdlPJo9KgJbdul8WRAJsdBSeyhLnkyMxHBrKb798K8,4286 +jaxlib/mlir/dialects/mhlo.py,sha256=P4w4601rbDLjOYCIMItrhdTmpVkas_RGq4rND2YQghA,852 +jaxlib/mlir/dialects/nvgpu.py,sha256=Hy_O9mKEj-o1hUM4XV9nlQzfH06FnFPHZ3tlhpQ30oE,309 +jaxlib/mlir/dialects/nvvm.py,sha256=Uqbt1cUNSKcyVy4mJZM2QwbY51fIh-_SYfdkR3IX4N4,261 +jaxlib/mlir/dialects/scf.py,sha256=VpFY3DniGDjz8iTqnl3kJFywSjabEsFO5bucUHWsCFk,4186 +jaxlib/mlir/dialects/sdy.py,sha256=opTQzPMomEgpJavDJSOOddGu2bKwJKio0Md7f2pw37w,832 +jaxlib/mlir/dialects/sparse_tensor.py,sha256=obaeQqnv8z1Bm7c_30QM1Syraz68m6L5jUx5mswkuXw,408 +jaxlib/mlir/dialects/stablehlo.py,sha256=cch4nHaJDW3khhjTRnmzzGYF6lsK04rfS4JX0jlLjyM,882 +jaxlib/mlir/dialects/vector.py,sha256=cN63xSlgzyvS06hcXsHnBZFfOp9lwXv0vOTHJyOjTzw,265 +jaxlib/mlir/extras/__pycache__/meta.cpython-312.pyc,, +jaxlib/mlir/extras/meta.py,sha256=g-ZeT8_wbpYpXaTDJiUHwk0KunX9pR3vkwkMPrI3VbE,3271 +jaxlib/mlir/ir.py,sha256=1HYB-t6kgPnnE-VqBCCBzrTX81ObBdBzgKAugh-6Edo,8832 +jaxlib/mlir/ir.pyi,sha256=v1AdIPl2RRtwqolppQ_6dasLq9a6oQgYLbZVy3gUfzo,88380 +jaxlib/mlir/passmanager.py,sha256=11HtTgSs8KHWN8szWqS1Hg80tBugUJ9eUQcYhaWIFxk,246 +jaxlib/mlir/passmanager.pyi,sha256=n_qWvQSqH4XdZ24Lh6Y0oZFBAZSI8tzNNhhViJjFgxE,1135 +jaxlib/mosaic/dialect/gpu/__pycache__/_mosaic_gpu_gen_enums.cpython-312.pyc,, +jaxlib/mosaic/dialect/gpu/__pycache__/_mosaic_gpu_gen_ops.cpython-312.pyc,, +jaxlib/mosaic/dialect/gpu/_mosaic_gpu_gen_enums.py,sha256=VZUhSrFeMBmXcpmGdTQs6R5MHkS18hkYGYRV8B7Yyuw,2198 +jaxlib/mosaic/dialect/gpu/_mosaic_gpu_gen_ops.py,sha256=NGjT1VkUN0zzW-qahr_Pev17Plf0mVZrQ3Hqn-OBdZw,22397 +jaxlib/mosaic/python/__pycache__/_tpu_gen.cpython-312.pyc,, +jaxlib/mosaic/python/__pycache__/layout_defs.cpython-312.pyc,, +jaxlib/mosaic/python/__pycache__/mosaic_gpu.cpython-312.pyc,, +jaxlib/mosaic/python/__pycache__/tpu.cpython-312.pyc,, +jaxlib/mosaic/python/_tpu_gen.py,sha256=3bWp_fRidOajfUFq0ZVfb3K94SXTmS5oWKDpsThWBI4,106145 +jaxlib/mosaic/python/layout_defs.py,sha256=JMz_oarRPkHxcZg-eTxscYZCUq2ErbI-qx1iIJ0ZyAY,1544 +jaxlib/mosaic/python/mosaic_gpu.py,sha256=NzKGM13DmQEchNmiLbBH7wHPDTM5RjrvCaOP8FUR5-Q,1534 +jaxlib/mosaic/python/tpu.py,sha256=2rOSHvFUAtSAFzTK4cjTF3uOmKqKsBC9JMmQ4GcRITQ,1925 +jaxlib/plugin_support.py,sha256=al8fFHtgjgRT3gZnA52uO7ZLG6X4vhnwxVwuiMNse-8,3578 +jaxlib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jaxlib/triton/__init__.py,sha256=N5ZsLqFbXucxFoeajKaRw-i0gz9HuaPTaNSyCcUe5Pw,646 +jaxlib/triton/__pycache__/__init__.cpython-312.pyc,, +jaxlib/triton/__pycache__/_triton_enum_gen.cpython-312.pyc,, +jaxlib/triton/__pycache__/_triton_ops_gen.cpython-312.pyc,, +jaxlib/triton/__pycache__/dialect.cpython-312.pyc,, +jaxlib/triton/_triton_enum_gen.py,sha256=V4ewOvvcRdaY19uvpzKtRq75qpQcFdzMpCZG47gRU_I,9239 +jaxlib/triton/_triton_ops_gen.py,sha256=J8RuHkusp42iHjVoAzn8oWGsTcVYeURkn05uLvWHA2I,96822 +jaxlib/triton/dialect.py,sha256=Gmgb4ju7kN3qya4zOXUDwxq_aqvrPbqdPzQrLOCAF6k,2970 +jaxlib/utils.pyd,sha256=POumBql1nVIHVt91A94xRQtTgPoUF4G0mbSDvdVS818,8704 +jaxlib/version.py,sha256=PJ96ZwrFHDnrRYHirhd4qy7XFlH6qSfd6Xe_HXZx1Ho,6886 +jaxlib/weakref_lru_cache.pyd,sha256=IBXRl213S1DaAhHyK2J5jV6ITmYb_Vk0JNNHKd8FKvE,8704 +jaxlib/weakref_lru_cache.pyi,sha256=hJiX3_z8jM6-96MH56LUwg5v-1SKlTZdBCTBhbGA3-8,1324 +jaxlib/xla_client.py,sha256=ad5dUo8oM6t_rHTLc3D91pHfhUrJ-b1LOeK2OmjtCHY,17456 diff --git a/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/WHEEL b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8f800c2843f2a606f8e8966cf85db911c0aab964 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (76.0.0) +Root-Is-Purelib: false +Tag: cp312-cp312-win_amd64 + diff --git a/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/top_level.txt b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..042f056e96afb730a2c3150dc42a91f8555a0ea0 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib-0.6.2.dist-info/top_level.txt @@ -0,0 +1 @@ +jaxlib diff --git a/python_embeded/Lib/site-packages/jaxlib/__init__.py b/python_embeded/Lib/site-packages/jaxlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1404565419b66aa0fb641f87c6cef84acab4c65 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .version import __version__ # noqa: F401 diff --git a/python_embeded/Lib/site-packages/jaxlib/_jax.pyd b/python_embeded/Lib/site-packages/jaxlib/_jax.pyd new file mode 100644 index 0000000000000000000000000000000000000000..2d887c35871a1e2741ca728e8fd80473c20038e4 Binary files /dev/null and b/python_embeded/Lib/site-packages/jaxlib/_jax.pyd differ diff --git a/python_embeded/Lib/site-packages/jaxlib/_pretty_printer.pyd b/python_embeded/Lib/site-packages/jaxlib/_pretty_printer.pyd new file mode 100644 index 0000000000000000000000000000000000000000..30bf68bf13e3f82718c0a7aa182f8b8519148a8b Binary files /dev/null and b/python_embeded/Lib/site-packages/jaxlib/_pretty_printer.pyd differ diff --git a/python_embeded/Lib/site-packages/jaxlib/_profiler.pyd b/python_embeded/Lib/site-packages/jaxlib/_profiler.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e3e0e0731baabad16674ab92ff6410bef4c2dbf3 Binary files /dev/null and b/python_embeded/Lib/site-packages/jaxlib/_profiler.pyd differ diff --git a/python_embeded/Lib/site-packages/jaxlib/cpu_feature_guard.pyd b/python_embeded/Lib/site-packages/jaxlib/cpu_feature_guard.pyd new file mode 100644 index 0000000000000000000000000000000000000000..bd33729313f38c689463339ff313c6e41c4ed70e Binary files /dev/null and b/python_embeded/Lib/site-packages/jaxlib/cpu_feature_guard.pyd differ diff --git a/python_embeded/Lib/site-packages/jaxlib/cpu_sparse.py b/python_embeded/Lib/site-packages/jaxlib/cpu_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..ed43b3ee0f925e713b8ea6887001726b72561e3b --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/cpu_sparse.py @@ -0,0 +1,27 @@ +# Copyright 2025 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +from .cpu import _sparse + + +def registrations() -> dict[str, list[tuple[str, Any, int]]]: + api_version = 1 + return { + "cpu": [ + (name, value, api_version) + for name, value in _sparse.registrations().items() + ] + } diff --git a/python_embeded/Lib/site-packages/jaxlib/gpu_common_utils.py b/python_embeded/Lib/site-packages/jaxlib/gpu_common_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf6d15448853a986e14cddc40b097141140299a --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/gpu_common_utils.py @@ -0,0 +1,27 @@ +# Copyright 2023 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Those common utility functions for gpu.""" + + +class GpuLibNotLinkedError(Exception): + """Raised when the GPU library is not linked.""" + + error_msg = ( + 'JAX was not built with GPU support. Please use a GPU-enabled JAX to use' + ' this function.' + ) + + def __init__(self): + super().__init__(self.error_msg) diff --git a/python_embeded/Lib/site-packages/jaxlib/gpu_linalg.py b/python_embeded/Lib/site-packages/jaxlib/gpu_linalg.py new file mode 100644 index 0000000000000000000000000000000000000000..967dacdbacffd8d9083ce1d142dc3a7b017e2a99 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/gpu_linalg.py @@ -0,0 +1,42 @@ +# Copyright 2021 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +from .plugin_support import import_from_plugin + +_cuda_linalg = import_from_plugin("cuda", "_linalg") +_hip_linalg = import_from_plugin("rocm", "_linalg") + + +def registrations() -> dict[str, list[tuple[str, Any, int]]]: + registrations: dict[str, list[tuple[str, Any, int]]] = { + "CUDA": [], + "ROCM": [], + } + for platform, module in [("CUDA", _cuda_linalg), ("ROCM", _hip_linalg)]: + if module: + registrations[platform].extend( + (*i, 1) for i in module.registrations().items() + ) + return registrations # pytype: disable=bad-return-type + + +def batch_partitionable_targets() -> list[str]: + targets = [] + if _cuda_linalg: + targets.append("cu_lu_pivots_to_permutation") + if _hip_linalg: + targets.append("hip_lu_pivots_to_permutation") + return targets diff --git a/python_embeded/Lib/site-packages/jaxlib/gpu_prng.py b/python_embeded/Lib/site-packages/jaxlib/gpu_prng.py new file mode 100644 index 0000000000000000000000000000000000000000..17da46de699fd456e62680f3cdaf03679e09f5d0 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/gpu_prng.py @@ -0,0 +1,34 @@ +# Copyright 2019 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +from .plugin_support import import_from_plugin + +_cuda_prng = import_from_plugin("cuda", "_prng") +_hip_prng = import_from_plugin("rocm", "_prng") + + +def registrations() -> dict[str, list[tuple[str, Any, int]]]: + registrations: dict[str, list[tuple[str, Any, int]]] = { + "CUDA": [], + "ROCM": [], + } + for platform, module in [("CUDA", _cuda_prng), ("ROCM", _hip_prng)]: + if module: + registrations[platform].extend( + (name, value, int(name.endswith("_ffi"))) + for name, value in module.registrations().items() + ) + return registrations diff --git a/python_embeded/Lib/site-packages/jaxlib/gpu_rnn.py b/python_embeded/Lib/site-packages/jaxlib/gpu_rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..b63c8991de6dfe123c1e176f1430d3e0bd80bda5 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/gpu_rnn.py @@ -0,0 +1,147 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from functools import partial + +import jaxlib.mlir.ir as ir +import jaxlib.mlir.dialects.stablehlo as hlo + +import numpy as np + +from jaxlib import xla_client +from .gpu_common_utils import GpuLibNotLinkedError +from .plugin_support import import_from_plugin + +_cuda_rnn = import_from_plugin("cuda", "_rnn") +_hip_rnn = import_from_plugin("rocm", "_rnn") + +if _cuda_rnn: + for _name, _value in _cuda_rnn.registrations().items(): + api_version = 1 if _name.endswith("_ffi") else 0 + xla_client.register_custom_call_target(_name, _value, platform='CUDA', + api_version=api_version) + compute_rnn_workspace_reserve_space_sizes = _cuda_rnn.compute_rnn_workspace_reserve_space_sizes + +if _hip_rnn: + for _name, _value in _hip_rnn.registrations().items(): + api_version = 1 if _name.endswith("_ffi") else 0 + xla_client.register_custom_call_target(_name, _value, platform='ROCM', + api_version=api_version) + compute_rnn_workspace_reserve_space_sizes = _hip_rnn.compute_rnn_workspace_reserve_space_sizes + + +def _rnn_fwd_lowering(_rnn, platform, ctx, input, h_0, c_0, weights, seq_lengths, *, + input_size: int, hidden_size: int, num_layers: int, + dropout: bool, bidirectional: bool, + cudnn_allow_tf32: bool): + """CuDnn RNN.""" + out_dtype = ctx.avals_out[0].dtype + if out_dtype == np.float32: + out_type = ir.F32Type.get() + elif out_dtype == np.float64: + out_type = ir.F64Type.get() + elif out_dtype == np.complex64: + out_type = ir.ComplexType.get(ir.F32Type.get()) + elif out_dtype == np.complex128: + out_type = ir.ComplexType.get(ir.F64Type.get()) + else: + raise ValueError(f'Unknown output type {out_dtype}') + + output_type = ir.RankedTensorType.get(ctx.avals_out[0].shape, out_type) + batch_size = ctx.avals_in[0].shape[0] + max_seq_length = ctx.avals_in[0].shape[1] + # workspace_shape = ctx.avals_out[3].shape + workspace_size, _ = compute_rnn_workspace_reserve_space_sizes( + input_size, hidden_size, num_layers, batch_size, max_seq_length, + dropout, bidirectional, cudnn_allow_tf32) + workspace_shape = (workspace_size,) + workspace_type = ir.RankedTensorType.get(workspace_shape, ir.F32Type.get()) + reserve_space_shape = ctx.avals_out[3].shape + reserve_space_type = ir.RankedTensorType.get(reserve_space_shape, + ir.F32Type.get()) + if not _rnn: + raise GpuLibNotLinkedError() + + opaque = _rnn.build_rnn_descriptor(input_size, hidden_size, num_layers, + batch_size, max_seq_length, dropout, + bidirectional, cudnn_allow_tf32, + workspace_shape[0], + reserve_space_shape[0]) + + i32_type = ir.IntegerType.get_signless(32) + out = hlo.CustomCallOp( + [output_type, h_0.type, c_0.type, workspace_type, reserve_space_type], + [input, h_0, c_0, weights, seq_lengths], + call_target_name=ir.StringAttr.get(f"{platform}dnn_rnn_ffi"), + has_side_effect=ir.BoolAttr.get(False), + backend_config=ir.DictAttr.get({"opaque": ir.StringAttr.get(opaque)}), + api_version=ir.IntegerAttr.get(i32_type, 4), + called_computations=ir.ArrayAttr.get([]), + ) + return out.results[:-2] + out.results[-1:] # drop workspace output + +cudnn_rnn_lowering = partial(_rnn_fwd_lowering, _cuda_rnn, "cu") +miopen_rnn_lowering = partial(_rnn_fwd_lowering, _hip_rnn, "hip") + + +def _hlo_zeros_f32(shape): + return hlo.constant( + ir.DenseElementsAttr.get( + np.zeros(shape, dtype=np.float32), type=ir.F32Type.get())) + + +def _rnn_bwd_lowering(_rnn, platform, ctx, dy, dhn, dcn, x, h0, c0, w, y, + reserve_space, seq_lengths, *, input_size: int, + hidden_size: int, num_layers: int, dropout: bool, + bidirectional: bool, cudnn_allow_tf32: bool): + """CuDnn RNN Backward pass.""" + batch_size = ctx.avals_in[3].shape[0] + max_seq_length = ctx.avals_in[3].shape[1] + workspace_size, _ = compute_rnn_workspace_reserve_space_sizes( + input_size, hidden_size, num_layers, batch_size, max_seq_length, + dropout, bidirectional, cudnn_allow_tf32) + workspace_shape = (workspace_size,) + workspace_type = ir.RankedTensorType.get(workspace_shape, ir.F32Type.get()) + reserve_space_shape = ctx.avals_in[8].shape + + if _rnn is None: + raise RuntimeError("cuda couldn't be imported") + opaque = _rnn.build_rnn_descriptor(input_size, hidden_size, num_layers, + batch_size, max_seq_length, dropout, + bidirectional, cudnn_allow_tf32, + workspace_shape[0], + reserve_space_shape[0]) + + i32_type = ir.IntegerType.get_signless(32) + zeroed_dw = _hlo_zeros_f32(ctx.avals_out[3].shape) + out = hlo.CustomCallOp( + [x.type, h0.type, c0.type, w.type, workspace_type], [ + dy, dhn, dcn, x, h0, c0, w, y, reserve_space, zeroed_dw, + seq_lengths + ], + call_target_name=ir.StringAttr.get(f"{platform}dnn_rnn_bwd_ffi"), + has_side_effect=ir.BoolAttr.get(False), + backend_config=ir.DictAttr.get({"opaque": ir.StringAttr.get(opaque)}), + api_version=ir.IntegerAttr.get(i32_type, 4), + called_computations=ir.ArrayAttr.get([]), + output_operand_aliases=ir.ArrayAttr.get([ + hlo.OutputOperandAlias.get( + output_tuple_indices=[3], + operand_index=9, + operand_tuple_indices=[]) + ])) + return out.results[:-1] # drop workspace output + +cudnn_rnn_bwd_lowering = partial(_rnn_bwd_lowering, _cuda_rnn, "cu") +miopen_rnn_bwd_lowering = partial(_rnn_bwd_lowering, _hip_rnn, "hip") diff --git a/python_embeded/Lib/site-packages/jaxlib/gpu_solver.py b/python_embeded/Lib/site-packages/jaxlib/gpu_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..cdcd2b6199f9486b31d2c29acc5c9ee5b1f5816c --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/gpu_solver.py @@ -0,0 +1,70 @@ +# Copyright 2019 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +from .plugin_support import import_from_plugin + +_cusolver = import_from_plugin("cuda", "_solver") +_cuhybrid = import_from_plugin("cuda", "_hybrid") + +_hipsolver = import_from_plugin("rocm", "_solver") +_hiphybrid = import_from_plugin("rocm", "_hybrid") + + +def registrations() -> dict[str, list[tuple[str, Any, int]]]: + registrations: dict[str, list[tuple[str, Any, int]]] = { + "CUDA": [], + "ROCM": [], + } + for platform, module in [("CUDA", _cusolver), ("ROCM", _hipsolver)]: + if module: + registrations[platform].extend( + (name, value, int(name.endswith("_ffi"))) + for name, value in module.registrations().items() + ) + for platform, module in [("CUDA", _cuhybrid), ("ROCM", _hiphybrid)]: + if module: + registrations[platform].extend( + (*i, 1) for i in module.registrations().items() + ) + return registrations # pytype: disable=bad-return-type + + +def batch_partitionable_targets() -> list[str]: + targets: list[str] = [] + for module in [_cusolver, _hipsolver]: + if module: + targets.extend( + name for name in module.registrations() if name.endswith("_ffi") + ) + for module in [_cuhybrid, _hiphybrid]: + if module: + targets.extend(name for name in module.registrations()) + return targets + + +def initialize_hybrid_kernels(): + if _cuhybrid: + _cuhybrid.initialize() + if _hiphybrid: + _hiphybrid.initialize() + + +def has_magma(): + if _cuhybrid: + return _cuhybrid.has_magma() + if _hiphybrid: + return _hiphybrid.has_magma() + return False diff --git a/python_embeded/Lib/site-packages/jaxlib/gpu_sparse.py b/python_embeded/Lib/site-packages/jaxlib/gpu_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1dc6f64ec1b900f61aae3727fe13babdf9fac9 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/gpu_sparse.py @@ -0,0 +1,46 @@ +# Copyright 2019 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +from .plugin_support import import_from_plugin + +_cusparse = import_from_plugin("cuda", "_sparse") +_hipsparse = import_from_plugin("rocm", "_sparse") + +cuda_is_supported = bool(_cusparse and _cusparse.sparse_supported) +rocm_is_supported = bool(_hipsparse and _hipsparse.sparse_supported) + + +def registrations() -> dict[str, list[tuple[str, Any, int]]]: + registrations: dict[str, list[tuple[str, Any, int]]] = { + "CUDA": [], + "ROCM": [], + } + for platform, module in [("CUDA", _cusparse), ("ROCM", _hipsparse)]: + if module: + registrations[platform].extend( + (name, value, int(name.endswith("_ffi"))) + for name, value in module.registrations().items() + ) + return registrations # pytype: disable=bad-return-type + +def batch_partitionable_targets() -> list[str]: + targets: list[str] = [] + for module in [_cusparse, _hipsparse]: + if module: + targets.extend( + name for name in module.registrations() if name.endswith("gtsv2_ffi") + ) + return targets diff --git a/python_embeded/Lib/site-packages/jaxlib/gpu_triton.py b/python_embeded/Lib/site-packages/jaxlib/gpu_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..9411aa6b3beb2f71827609c31d774097f94211c0 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/gpu_triton.py @@ -0,0 +1,48 @@ +# Copyright 2023 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from jaxlib import xla_client + +from .plugin_support import import_from_plugin + +_cuda_triton = import_from_plugin("cuda", "_triton") +_hip_triton = import_from_plugin("rocm", "_triton") + +if _cuda_triton: + xla_client.register_custom_call_target( + "triton_kernel_call", _cuda_triton.get_custom_call(), + platform='CUDA') + TritonKernelCall = _cuda_triton.TritonKernelCall + TritonAutotunedKernelCall = _cuda_triton.TritonAutotunedKernelCall + TritonKernel = _cuda_triton.TritonKernel + create_array_parameter = _cuda_triton.create_array_parameter + create_scalar_parameter = _cuda_triton.create_scalar_parameter + get_compute_capability = _cuda_triton.get_compute_capability + get_arch_details = _cuda_triton.get_arch_details + get_custom_call = _cuda_triton.get_custom_call + get_serialized_metadata = _cuda_triton.get_serialized_metadata + +if _hip_triton: + xla_client.register_custom_call_target( + "triton_kernel_call", _hip_triton.get_custom_call(), + platform='ROCM') + TritonKernelCall = _hip_triton.TritonKernelCall + TritonAutotunedKernelCall = _hip_triton.TritonAutotunedKernelCall + TritonKernel = _hip_triton.TritonKernel + create_array_parameter = _hip_triton.create_array_parameter + create_scalar_parameter = _hip_triton.create_scalar_parameter + get_compute_capability = _hip_triton.get_compute_capability + get_arch_details = _hip_triton.get_arch_details + get_custom_call = _hip_triton.get_custom_call + get_serialized_metadata = _hip_triton.get_serialized_metadata diff --git a/python_embeded/Lib/site-packages/jaxlib/hlo_helpers.py b/python_embeded/Lib/site-packages/jaxlib/hlo_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..11ff844ae53f440ff39649ea9175263bcfd17f43 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/hlo_helpers.py @@ -0,0 +1,259 @@ +# Copyright 2022 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""A small library of helpers for use in jaxlib to build MLIR operations.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from functools import partial +from typing import Union +import warnings + +import jaxlib.mlir.ir as ir +import jaxlib.mlir.dialects.stablehlo as hlo +import numpy as np + +# TODO(danfm): This module isn't covered by JAX's compatibility policy, so no +# formal deprecation period is required, but there are enough users that we +# should keep this warning for at least one full release cycle. +# Deprecation added 2025-03-19 after the release of v0.5.3. Remove this whole +# module after the release of v0.5.4 or later. +warnings.warn( + "The jaxlib.hlo_helpers submodule is deprecated. Instead, use jax.ffi if " + "possible or, for lower-level operations, jax.interpreters.mlir.", + DeprecationWarning, +) + +_dtype_to_ir_type_factory : dict[np.dtype, Callable[[], ir.Type]] = { + np.dtype(np.bool_): partial(ir.IntegerType.get_signless, 1), + np.dtype(np.int8): partial(ir.IntegerType.get_signless, 8), + np.dtype(np.int16): partial(ir.IntegerType.get_signless, 16), + np.dtype(np.int32): partial(ir.IntegerType.get_signless, 32), + np.dtype(np.int64): partial(ir.IntegerType.get_signless, 64), + np.dtype(np.uint8): partial(ir.IntegerType.get_unsigned, 8), + np.dtype(np.uint16): partial(ir.IntegerType.get_unsigned, 16), + np.dtype(np.uint32): partial(ir.IntegerType.get_unsigned, 32), + np.dtype(np.uint64): partial(ir.IntegerType.get_unsigned, 64), + np.dtype(np.float16): ir.F16Type.get, + np.dtype(np.float32): ir.F32Type.get, + np.dtype(np.float64): ir.F64Type.get, + np.dtype(np.complex64): lambda: ir.ComplexType.get(ir.F32Type.get()), + np.dtype(np.complex128): lambda: ir.ComplexType.get(ir.F64Type.get()), +} +def dtype_to_ir_type(dtype) -> ir.Type: + return _dtype_to_ir_type_factory[np.dtype(dtype)]() + + +def shape_dtype_to_ir_type(shape: Sequence[int], dtype) -> ir.Type: + return ir.RankedTensorType.get(shape, dtype_to_ir_type(dtype)) + + +# When we generate custom calls with dynamic shapes we have to pass +# both the result_types, with ir.ShapedType.get_dynamic_size in place of +# the dynamic dimensions, and also result_shapes, which are ir.Value +# representing 1D int32 tensors. If all the shapes are static we can use +# result_shapes=None. We first construct for each result a pair with the shape +# and element type, the shape containing either integer or ir.Value. +DimensionSize = Union[int, ir.Value] # an ir.Value if not static dimension +ShapeTypePair = tuple[Sequence[DimensionSize], ir.Type] + +def mk_result_types_and_shapes( + shape_type_pairs: Sequence[ShapeTypePair] +) -> tuple[list[ir.Type], list[ir.Value] | None]: + result_types: list[ir.Type] = [] + result_shapes: list[ir.Value] = [] + has_dynamic_shapes = any( + any(not isinstance(d, int) for d in rshape) + for rshape, _ in shape_type_pairs) + for (rshape, rtype) in shape_type_pairs: + if has_dynamic_shapes: + result_shapes.append(shape_tensor(rshape)) + result_types.append( + ir.RankedTensorType.get( + [d if isinstance(d, int) else ir.ShapedType.get_dynamic_size() + for d in rshape], + rtype)) + return (result_types, + result_shapes if has_dynamic_shapes else None) + +# TODO(necula): share this with mlir.shape_tensor +def shape_tensor(sizes: Sequence[int | ir.Value]) -> ir.Value: + int1d = shape_dtype_to_ir_type((1,), np.int32) + i32_type = shape_dtype_to_ir_type((), np.int32) + def dim_to_i32x1(d): + if type(d) is int: + return hlo_const(np.array([d], dtype=np.int32)) + else: + if d.type != i32_type: + d = hlo.convert(i32_type, d) + return hlo.reshape(int1d, d) + ds = [dim_to_i32x1(sz) for sz in sizes] + if not ds: + return hlo_const(np.array([], np.int32)) + elif len(ds) == 1: + return ds[0] + else: + return hlo.concatenate( + ds, ir.IntegerAttr.get(ir.IntegerType.get_signless(64), 0)) + +def hlo_const(x: np.ndarray) -> ir.Value: + assert isinstance(x, np.ndarray) + return hlo.constant( + ir.DenseElementsAttr.get(x, type=dtype_to_ir_type(x.dtype))) + +def hlo_u8(x: int): + return hlo_const(np.array(x, dtype=np.uint8)) +def hlo_s32(x: int): + return hlo_const(np.array(x, dtype=np.int32)) + +def ensure_hlo_s32(x: DimensionSize): + return hlo_s32(x) if isinstance(x, int) else x + +def dense_int_array(xs) -> ir.DenseI64ArrayAttr: + return ir.DenseI64ArrayAttr.get(np.asarray(xs, np.int64)) + +def hlo_min(x: DimensionSize, y: DimensionSize) -> DimensionSize: + if type(x) is int: + if type(y) is int: + return min(x, y) + x = hlo_s32(x) + if type(y) is int: + y = hlo_s32(y) + return hlo.minimum(x, y) + + +def hlo_add(x: DimensionSize, y: DimensionSize) -> DimensionSize: + if type(x) is int: + if type(y) is int: + return x + y + x = hlo_s32(x) + if type(y) is int: + y = hlo_s32(y) + return hlo.add(x, y) + + +# TODO(necula): this is identical with mlir.custom_call, but meant for use +# in jaxlib. Find a way to share these implementations. +def custom_call( + call_target_name: str, + *, + result_types: Sequence[ir.Type], + operands: Sequence[ir.Value], + backend_config: str | bytes | dict[str, ir.Attribute] = "", + has_side_effect: bool = False, + result_shapes: Sequence[ir.Value] | None = None, + called_computations: Sequence[str] = (), + api_version: int = 2, + operand_output_aliases: dict[int, int] | None = None, + operand_layouts: Sequence[Sequence[int]] | None = None, + result_layouts: Sequence[Sequence[int]] | None = None, + extra_attributes: dict[str, ir.Attribute] | None = None, +) -> ir.Operation: + """Helper function for building an hlo.CustomCall. + + Args: + call_target_name: the name of the custom call target + result_types: the MLIR types of the results of the custom call + operands: the MLIR IR values that are arguments to the custom call + backend_config: an opaque string passed to the custom call kernel + has_side_effect: if True, marks the custom call as effectful + result_shapes: tensors that represent the result shapes, to be used when + the results have dynamic shapes. If not-None, its length must match the + number of the results. + called_computations: the list of function names called by the custom call. + api_version: the ABI contract version of the custom call + operand_output_aliases: a dict mapping operand numbers to outputs they alias + operand_layouts: a sequence of layouts (dimension orders) for each operand + result_layouts: a sequence of layouts (dimension orders) for each result + extra_attributes: additional IR attributes to apply to the custom_call. + """ + operands = list(operands) + + if backend_config is None: + backend_config_attr = ir.StringAttr.get("") + elif isinstance(backend_config, (str, bytes)): + backend_config_attr = ir.StringAttr.get(backend_config) + elif isinstance(backend_config, dict): + # TODO(necula): it seems that the CustomCallOp constructor requires that + # backend_config_attr be a string attribute, even though in some cases we + # need it to be a DictAttr, e.g., for ApproxTopK on TPU. + # "Verification failed: 'stablehlo.custom_call' op attribute 'backend_config' failed to satisfy constraint: string attribute" + # To workaround this limitation we first set it to the empty string and we + # use an unregistered attribute mhlo.backend_config to hold the DictAttr. + # We must also use api_version=1 to ensure that mhlo.backend_config is + # handled properly. + backend_config_attr = ir.StringAttr.get("") + api_version = 1 + else: + raise ValueError("custom_call backend_config unexpected type: " + str(backend_config)) + attributes = dict( + call_target_name=ir.StringAttr.get(call_target_name), + has_side_effect=ir.BoolAttr.get(has_side_effect), + backend_config=backend_config_attr, + api_version=ir.IntegerAttr.get( + ir.IntegerType.get_signless(32), api_version), + called_computations=ir.ArrayAttr.get( + [ir.FlatSymbolRefAttr.get(name) for name in called_computations] + ), + ) + if operand_output_aliases is not None: + attributes["output_operand_aliases"] = ir.ArrayAttr.get([ + hlo.OutputOperandAlias.get( + # if len(result_types) == 1 then the aliasing refers implicitly to + # the only output. + output_tuple_indices=[output_idx] if len(result_types) > 1 else [], + operand_index=input_idx, + operand_tuple_indices=[], + ) + for input_idx, output_idx in (operand_output_aliases.items() or ()) + ]) + + if extra_attributes is not None: + attributes.update(extra_attributes) + + if result_shapes is not None: + # We add the result_shapes at the end of the operands, and must pass + # the indices_of_output_operands attribute. This attribute is not yet + # accepted by the CustomCall constructor, so we use build_generic + attributes["indices_of_shape_operands"] = ir.DenseIntElementsAttr.get( + np.asarray(list(range(len(operands), len(operands) + len(result_shapes))), + dtype=np.int64)) + if operand_layouts is not None: + assert len(operand_layouts) == len(operands), (operand_layouts, operands) + operand_layouts = list(operand_layouts) + [(0,)] * len(result_shapes) + operands = list(operands) + list(result_shapes) + + if operand_layouts is not None: + attributes["operand_layouts"] = ir.ArrayAttr.get([ + ir.DenseIntElementsAttr.get( + np.atleast_1d(np.asarray(l, dtype=np.int64)), + type=ir.IndexType.get()) for l in operand_layouts + ]) + if result_layouts is not None: + assert result_layouts is not None + assert len(result_layouts) == len(result_types), ( + result_layouts, result_types) + attributes["result_layouts"] = ir.ArrayAttr.get([ + ir.DenseIntElementsAttr.get( + np.atleast_1d(np.asarray(l, dtype=np.int64)), + type=ir.IndexType.get()) for l in result_layouts + ]) + + op = hlo.CustomCallOp.build_generic(results=result_types, operands=operands, + attributes=attributes) + if isinstance(backend_config, dict): + backend_config_attr = ir.DictAttr.get(backend_config) + op.operation.attributes["mhlo.backend_config"] = backend_config_attr + return op diff --git a/python_embeded/Lib/site-packages/jaxlib/lapack.py b/python_embeded/Lib/site-packages/jaxlib/lapack.py new file mode 100644 index 0000000000000000000000000000000000000000..330fcb9926754debf1e384374bcdd42bb8bf7aea --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/lapack.py @@ -0,0 +1,62 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +import numpy as np + +from .cpu import _lapack +from .cpu._lapack import eig +from .cpu._lapack import schur + + +EigComputationMode = eig.ComputationMode +SchurComputationMode = schur.ComputationMode +SchurSort = schur.Sort + + +LAPACK_DTYPE_PREFIX = { + np.float32: "s", + np.float64: "d", + np.complex64: "c", + np.complex128: "z", +} + + +def registrations() -> dict[str, list[tuple[str, Any, int]]]: + return {"cpu": [ + (name, value, int(name.endswith("_ffi"))) + for name, value in _lapack.registrations().items() + ]} + + +def batch_partitionable_targets() -> list[str]: + return [name for name in _lapack.registrations() if name.endswith("_ffi")] + + +def prepare_lapack_call(fn_base, dtype): + """Initializes the LAPACK library and returns the LAPACK target name.""" + _lapack.initialize() + return build_lapack_fn_target(fn_base, dtype) + + +def build_lapack_fn_target(fn_base: str, dtype) -> str: + """Builds the target name for a LAPACK function custom call.""" + try: + prefix = ( + LAPACK_DTYPE_PREFIX.get(dtype, None) or LAPACK_DTYPE_PREFIX[dtype.type] + ) + return f"lapack_{prefix}{fn_base}" + except KeyError as err: + raise NotImplementedError(err, f"Unsupported dtype {dtype}.") from err diff --git a/python_embeded/Lib/site-packages/jaxlib/plugin_support.py b/python_embeded/Lib/site-packages/jaxlib/plugin_support.py new file mode 100644 index 0000000000000000000000000000000000000000..ea24dc181be08d349008e7c51309eeb62878b1cc --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/plugin_support.py @@ -0,0 +1,110 @@ +# Copyright 2025 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +import importlib +import re +from types import ModuleType +import warnings + +from .version import __version__ as jaxlib_version + + +_PLUGIN_MODULE_NAME = { + "cuda": "jax_cuda12_plugin", + "rocm": "jax_rocm60_plugin", +} + + +def import_from_plugin( + plugin_name: str, submodule_name: str, *, check_version: bool = True +) -> ModuleType | None: + """Import a submodule from a known plugin with version checking. + + Args: + plugin_name: The name of the plugin. The supported values are "cuda" or + "rocm". + submodule_name: The name of the submodule to import, e.g. "_triton". + check_version: Whether to check that the plugin version is compatible with + the jaxlib version. If the plugin is installed but the versions are not + compatible, this function produces a warning and returns None. + + Returns: + The imported submodule, or None if the plugin is not installed or if the + versions are incompatible. + """ + if plugin_name not in _PLUGIN_MODULE_NAME: + raise ValueError(f"Unknown plugin: {plugin_name}") + return maybe_import_plugin_submodule( + [f".{plugin_name}", _PLUGIN_MODULE_NAME[plugin_name]], + submodule_name, + check_version=check_version, + ) + + +def check_plugin_version( + plugin_name: str, jaxlib_version: str, plugin_version: str +) -> bool: + # Regex to match a dotted version prefix 0.1.23.456.789 of a PEP440 version. + # PEP440 allows a number of non-numeric suffixes, which we allow also. + # We currently do not allow an epoch. + version_regex = re.compile(r"[0-9]+(?:\.[0-9]+)*") + + def _parse_version(v: str) -> tuple[int, ...]: + m = version_regex.match(v) + if m is None: + raise ValueError(f"Unable to parse version string '{v}'") + return tuple(int(x) for x in m.group(0).split(".")) + + if _parse_version(jaxlib_version) != _parse_version(plugin_version): + warnings.warn( + f"JAX plugin {plugin_name} version {plugin_version} is installed, but " + "it is not compatible with the installed jaxlib version " + f"{jaxlib_version}, so it will not be used.", + RuntimeWarning, + ) + return False + return True + + +def maybe_import_plugin_submodule( + plugin_module_names: Sequence[str], + submodule_name: str, + *, + check_version: bool = True, +) -> ModuleType | None: + for plugin_module_name in plugin_module_names: + try: + module = importlib.import_module( + f"{plugin_module_name}.{submodule_name}", + package="jaxlib", + ) + except ImportError: + continue + else: + if not check_version: + return module + try: + version_module = importlib.import_module( + f"{plugin_module_name}.version", + package="jaxlib", + ) + except ImportError: + return module + plugin_version = getattr(version_module, "__version__", "") + if check_plugin_version( + plugin_module_name, jaxlib_version, plugin_version + ): + return module + return None diff --git a/python_embeded/Lib/site-packages/jaxlib/py.typed b/python_embeded/Lib/site-packages/jaxlib/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/jaxlib/utils.pyd b/python_embeded/Lib/site-packages/jaxlib/utils.pyd new file mode 100644 index 0000000000000000000000000000000000000000..d8ea69d6c4bb6217b0c38d7f440a9033a714d99a Binary files /dev/null and b/python_embeded/Lib/site-packages/jaxlib/utils.pyd differ diff --git a/python_embeded/Lib/site-packages/jaxlib/version.py b/python_embeded/Lib/site-packages/jaxlib/version.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d7fa6eae335aaaa8afde5852a6faf25d47ebd9 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/version.py @@ -0,0 +1,161 @@ +# Copyright 2018 The JAX Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This file is included as part of both jax and jaxlib. It is also +# eval()-ed by setup.py, so it should not have any dependencies. +from __future__ import annotations + +import datetime +import os +import pathlib +import subprocess + +_version = "0.6.2" +# The following line is overwritten by build scripts in distributions & +# releases. Do not modify this manually, or jax/jaxlib build will fail. +_release_version: str = '0.6.2' + +# The following line is overwritten by build scripts in distributions & +# releases. Do not modify this manually, or jax/jaxlib build will fail. +_git_hash: str | None = None + +def _get_version_string() -> str: + # The build/source distribution for jax & jaxlib overwrites _release_version. + # In this case we return it directly. + if _release_version is not None: + return _release_version + if os.getenv("WHEEL_VERSION_SUFFIX"): + return _version + os.getenv("WHEEL_VERSION_SUFFIX", "") + return _version_from_git_tree(_version) or _version_from_todays_date(_version) + + +def _version_from_todays_date(base_version: str) -> str: + datestring = datetime.date.today().strftime("%Y%m%d") + return f"{base_version}.dev{datestring}" + + +def _version_from_git_tree(base_version: str) -> str | None: + try: + root_directory = os.path.dirname(os.path.realpath(__file__)) + + # Get date string from date of most recent git commit, and the abbreviated + # hash of that commit. + p = subprocess.Popen(["git", "show", "-s", "--format=%at-%h", "HEAD"], + cwd=root_directory, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, _ = p.communicate() + timestamp, commit_hash = stdout.decode().strip().split('-', 1) + datestring = datetime.date.fromtimestamp(int(timestamp)).strftime("%Y%m%d") + assert datestring.isnumeric() + assert commit_hash.isalnum() + except: + return None + else: + version = f"{base_version}.dev{datestring}+{commit_hash}" + suffix = os.environ.get("JAX_CUSTOM_VERSION_SUFFIX", None) + if suffix: + return version + "." + suffix + return version + + +def _get_version_for_build() -> str: + """Determine the version at build time. + + The returned version string depends on which environment variables are set: + - if WHEEL_VERSION_SUFFIX is set: version looks like "0.5.1.dev20230906+ge58560fdc" + Here the WHEEL_VERSION_SUFFIX value is ".dev20230906+ge58560fdc". + Please note that the WHEEL_VERSION_SUFFIX value is not the same as the + JAX_CUSTOM_VERSION_SUFFIX value, and WHEEL_VERSION_SUFFIX is set by Bazel + wheel build rule. + - if JAX_RELEASE or JAXLIB_RELEASE are set: version looks like "0.4.16" + - if JAX_NIGHTLY or JAXLIB_NIGHTLY are set: version looks like "0.4.16.dev20230906" + - if none are set: version looks like "0.4.16.dev20230906+ge58560fdc + """ + if _release_version is not None: + return _release_version + if os.getenv("WHEEL_VERSION_SUFFIX"): + return _version + os.getenv("WHEEL_VERSION_SUFFIX", "") + if os.getenv("JAX_RELEASE") or os.getenv("JAXLIB_RELEASE"): + return _version + if os.getenv("JAX_NIGHTLY") or os.getenv("JAXLIB_NIGHTLY"): + return _version_from_todays_date(_version) + return _version_from_git_tree(_version) or _version_from_todays_date(_version) + + +def _is_prerelease() -> bool: + """Determine if this is a pre-release ("rc" wheels) build.""" + rc_version = os.getenv("WHEEL_VERSION_SUFFIX", "") + return True if rc_version.startswith("rc") else False + + +def _write_version(fname: str) -> None: + """Used by setup.py to write the specified version info into the source tree.""" + release_version = _get_version_for_build() + old_version_string = "_release_version: str = '0.6.2'" + new_version_string = f"_release_version: str = {release_version!r}" + fhandle = pathlib.Path(fname) + contents = fhandle.read_text() + # Expect two occurrences: one above, and one here. + if contents.count(old_version_string) != 2: + raise RuntimeError(f"Build: could not find {old_version_string!r} in {fname}") + contents = contents.replace(old_version_string, new_version_string) + + githash = os.environ.get("JAX_GIT_HASH") + if githash: + old_githash_string = "_git_hash: str | None = None" + new_githash_string = f"_git_hash: str = {githash!r}" + if contents.count(old_githash_string) != 2: + raise RuntimeError(f"Build: could not find {old_githash_string!r} in {fname}") + contents = contents.replace(old_githash_string, new_githash_string) + fhandle.write_text(contents) + + +def _get_cmdclass(pkg_source_path): + from setuptools.command.build_py import build_py as build_py_orig # pytype: disable=import-error + from setuptools.command.sdist import sdist as sdist_orig # pytype: disable=import-error + + class _build_py(build_py_orig): + def run(self): + if _release_version is None: + this_file_in_build_dir = os.path.join(self.build_lib, pkg_source_path, + os.path.basename(__file__)) + # super().run() only copies files from source -> build if they are + # missing or outdated. Because _write_version(...) modifies the copy of + # this file in the build tree, re-building from the same JAX directory + # would not automatically re-copy a clean version, and _write_version + # would fail without this deletion. See jax-ml/jax#18252. + if os.path.isfile(this_file_in_build_dir): + os.unlink(this_file_in_build_dir) + super().run() + if _release_version is None: + _write_version(this_file_in_build_dir) + + class _sdist(sdist_orig): + def make_release_tree(self, base_dir, files): + super().make_release_tree(base_dir, files) + if _release_version is None: + _write_version(os.path.join(base_dir, pkg_source_path, + os.path.basename(__file__))) + + return dict(sdist=_sdist, build_py=_build_py) + + +__version__ = _get_version_string() +_minimum_jaxlib_version = "0.6.2" + +def _version_as_tuple(version_str): + return tuple(int(i) for i in version_str.split(".") if i.isdigit()) + +__version_info__ = _version_as_tuple(__version__) +_minimum_jaxlib_version_info = _version_as_tuple(_minimum_jaxlib_version) diff --git a/python_embeded/Lib/site-packages/jaxlib/weakref_lru_cache.pyd b/python_embeded/Lib/site-packages/jaxlib/weakref_lru_cache.pyd new file mode 100644 index 0000000000000000000000000000000000000000..681a3f95fe8aa5a1d19414ac3610200c0d71b6d7 Binary files /dev/null and b/python_embeded/Lib/site-packages/jaxlib/weakref_lru_cache.pyd differ diff --git a/python_embeded/Lib/site-packages/jaxlib/weakref_lru_cache.pyi b/python_embeded/Lib/site-packages/jaxlib/weakref_lru_cache.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ed965d7be81129347ce8e73dff6993a385313ad5 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/weakref_lru_cache.pyi @@ -0,0 +1,38 @@ +# Copyright 2025 The JAX Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +from collections.abc import Callable +from typing import Any + +class WeakrefLRUCache: + def __call__(self, arg0: Any, /, *args, **kwargs) -> Any: ... + def cache_keys(self) -> list[Any]: ... + def cache_info(self) -> WeakrefLRUCache.WeakrefLRUCacheInfo: ... + def cache_clear(self) -> None: ... + + class WeakrefLRUCacheInfo: + @property + def hits(self) -> int: ... + @property + def misses(self) -> int: ... + @property + def maxsize(self) -> int: ... + @property + def currsize(self) -> int: ... + def __repr__(self) -> str: ... + +def weakref_lru_cache( + cache_context_fn: Callable, fn: Callable, maxsize: int = 2048 +) -> WeakrefLRUCache: ... diff --git a/python_embeded/Lib/site-packages/jaxlib/xla_client.py b/python_embeded/Lib/site-packages/jaxlib/xla_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c85276ce2cfad765ac62821ab97f61852eafd9 --- /dev/null +++ b/python_embeded/Lib/site-packages/jaxlib/xla_client.py @@ -0,0 +1,549 @@ +# Copyright 2017 The JAX Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""An XLA client in Python.""" + +from __future__ import annotations + +import atexit +from collections.abc import Mapping +import contextlib +import enum +import logging +import os +import threading +from typing import Any, Protocol, Union + +from jaxlib import _jax as _xla + +# Note this module does *not* depend on any Python protocol buffers. The XLA +# Python bindings are currently packaged both as part of jaxlib and as part +# of TensorFlow. If we use protocol buffers here, then importing both jaxlib +# and TensorFlow may fail with duplicate protocol buffer message definitions. + +# Most functions are snake_case for consistency with other modules, some +# method names are CamelCase for consistency with XLA. +# pylint: disable=invalid-name + +# Pylint has false positives for type annotations. +# pylint: disable=invalid-sequence-index + +ifrt_programs = _xla.ifrt_programs + +# Just an internal arbitrary increasing number to help with backward-compatible +# changes. In JAX, reference this via jax._src.lib.jaxlib_extension_version. +_version = 355 + +# An internal increasing version number for protecting jaxlib code against +# ifrt changes. +# lives in xla/python/version.h. +# In JAX, reference this via jax._src.lib.ifrt_version. +_ifrt_version = _xla.ifrt_version_number + +xla_platform_names = { + 'cpu': 'Host', + 'gpu': 'CUDA', +} + +logger = logging.getLogger(__name__) + +_NameValueMapping = Mapping[str, Union[str, int, list[int], float, bool]] + + +def make_cpu_client( + asynchronous=True, + distributed_client=None, + node_id=0, + num_nodes=1, + collectives=None, + num_devices=None, + get_local_topology_timeout_minutes=None, + get_global_topology_timeout_minutes=None, +) -> Client: + register_custom_call_handler('cpu', _xla.register_custom_call_target) + register_custom_type_id_handler('cpu', _xla.register_custom_type_id) + return _xla.get_tfrt_cpu_client( + asynchronous=asynchronous, + distributed_client=distributed_client, + node_id=node_id, + num_nodes=num_nodes, + collectives=collectives, + num_devices=num_devices, + get_local_topology_timeout_minutes=get_local_topology_timeout_minutes, + get_global_topology_timeout_minutes=get_global_topology_timeout_minutes, + ) + + +DeviceTopology = _xla.DeviceTopology +get_topology_for_devices = _xla.get_topology_for_devices + + +def make_tfrt_tpu_c_api_device_topology( + topology_name: str = '', **kwargs +) -> DeviceTopology: + """Creates a PJRT C API TopologyDescription.""" + return _xla.get_default_c_api_topology('tpu', topology_name, dict(**kwargs)) + + +def make_c_api_device_topology( + c_api: Any, topology_name: str = '', **kwargs +) -> DeviceTopology: + """Creates a PJRT C API TopologyDescription.""" + return _xla.get_c_api_topology(c_api, topology_name, dict(**kwargs)) + + +def pjrt_plugin_loaded(plugin_name: str) -> bool: + return _xla.pjrt_plugin_loaded(plugin_name) + + +def load_pjrt_plugin_dynamically(plugin_name: str, library_path: str) -> Any: + return _xla.load_pjrt_plugin(plugin_name, library_path, c_api=None) + + +def load_pjrt_plugin_with_c_api(plugin_name: str, c_api: Any) -> None: + return _xla.load_pjrt_plugin(plugin_name, None, c_api) + + +def pjrt_plugin_initialized(plugin_name: str) -> bool: + return _xla.pjrt_plugin_initialized(plugin_name) + + +def initialize_pjrt_plugin(plugin_name: str) -> None: + """Initializes a PJRT plugin. + + The plugin needs to be loaded first (through load_pjrt_plugin_dynamically or + static linking) before this method is called. + Args: + plugin_name: the name of the PJRT plugin. + """ + _xla.initialize_pjrt_plugin(plugin_name) + + +def make_c_api_client( + plugin_name: str, + options: _NameValueMapping | None = None, + distributed_client: _xla.DistributedRuntimeClient | None = None, +): + """Creates a PJRT C API client for a PJRT plugin. + + It is required that load_pjrt_plugin_dynamically is called once with the same + plugin_name before this method is called. + + Args: + plugin_name: the name of the PJRT plugin. + options: extra platform-specific options. + distributed_client: distributed client. + + Returns: + A PJRT C API client for plugin_name. + """ + if options is None: + options = {} + return _xla.get_c_api_client(plugin_name, options, distributed_client) + + +def generate_pjrt_gpu_plugin_options() -> _NameValueMapping: + """Generates the PjRt GPU plugin options. + + Returns: + A dictionary of plugin options. + """ + + options = {} + options['platform_name'] = 'cuda' + allocator = os.getenv('XLA_PYTHON_CLIENT_ALLOCATOR', 'default').lower() + memory_fraction = os.getenv('XLA_CLIENT_MEM_FRACTION', '') + deprecated_memory_fraction = os.getenv('XLA_PYTHON_CLIENT_MEM_FRACTION', '') + if deprecated_memory_fraction: + if memory_fraction: + raise ValueError( + 'XLA_CLIENT_MEM_FRACTION is specified together ' + 'with XLA_PYTHON_CLIENT_MEM_FRACTION. ' + 'Remove the latter one, it is deprecated.' + ) + else: + memory_fraction = deprecated_memory_fraction + preallocate = os.getenv('XLA_PYTHON_CLIENT_PREALLOCATE', '') + collective_memory_size = os.getenv( + 'XLA_PYTHON_CLIENT_COLLECTIVE_MEM_SIZE_MB', '' + ) + if allocator not in ('default', 'platform', 'bfc', 'cuda_async'): + raise ValueError( + 'XLA_PYTHON_CLIENT_ALLOCATOR env var must be "default", "platform", ' + '"bfc", or "cuda_async", got "%s"' % allocator + ) + options['allocator'] = allocator + if memory_fraction: + options['memory_fraction'] = float(memory_fraction) + if preallocate: + options['preallocate'] = preallocate not in ('false', 'False', '0') + if collective_memory_size: + options['collective_memory_size'] = int(collective_memory_size) * (1 << 20) + return options + + +PrimitiveType = _xla.PrimitiveType + +Shape = _xla.Shape +Shape.__doc__ = """ +A Shape is an object defined in C++ that duck types like the following class: + +class Shape: + '''Represents an XLA shape. + + A shape is either an array shape, having rank-many integer + dimensions and an element type (represented by a Numpy dtype), or it + is a tuple shape, having a shape for every tuple component: + + type shape = + TupleShape of shape list + | ArrayShape of { dimensions: int list; element_type: dtype } + ''' + + @staticmethod + def tuple_shape(tuple_shapes) -> Shape: + "Construct a tuple shape." + + @staticmethod + def array_shape(element_type, dimensions, minor_to_major=None) -> Shape: + + @staticmethod + def from_pyval(pyval) -> Shape: + "Returns a Shape that describes a tuple-tree of Numpy arrays." + + def __init__(self, str) -> Shape: + "Parses a shape string." + def __eq__(self, other: Shape) -> bool: + def __ne__(self, other: Shape) -> bool: + def __hash__(self): + def __repr__(self): + def is_tuple(self) -> bool: + def is_array(self) -> bool: + def tuple_shapes(self) -> [Shape]: + def numpy_dtype(self) -> np.dtype: + "Like element_type(), but returns dtype('O') for a tuple shape." + def xla_element_type(self) -> PrimitiveType: + def element_type(self) -> np.dtype: + def dimensions(self) -> (int, int, ...): + def rank(self) -> int: + def with_major_to_minor_layout_if_absent(self) -> Shape: + "Returns a copy with missing layouts set to major-to-minor." + + def to_serialized_proto(self) -> bytes: + "Returns 'shape' as a serialized proto." +""" + +ProgramShape = _xla.ProgramShape +ProgramShape.__doc__ = """ +A ProgramShape is a C++ object that duck types like the following class. + +class ProgramShape: + def __init__(self, parameter_shapes, result_shape): + def parameter_shapes(self) -> [Shape]: + def result_shape(self) -> Shape: + def __repr__(self): +""" + +DeviceAssignment = _xla.DeviceAssignment +DeviceAssignment.__doc__ = """ +A DeviceAssignment is a C++ object with the following signature. + +def create(assignment): + '''Builds a device assignment. + + Args: + assignment: a 2D numpy array of device ordinal integers, indexed by + [replica][computation_in_replica]. + Returns: + A device assignment. + ''' + +def replica_count(): + '''Returns the number of replicas.''' +def computation_count(): + '''Returns the number of computations per replica.''' +""" + +Device = _xla.Device +CompileOptions = _xla.CompileOptions + +HostBufferSemantics = _xla.HostBufferSemantics + +# An Executable is a C++ class that duck types with the following API: +# class Executable: +# def local_devices(self) -> [Device]: +# def execute(self, arguments : [Buffer]) -> Buffer: +# """Execute on one replica with Buffer arguments and return value.""" +# +# def size_of_generated_code_in_bytes(self) -> int: +# """Return generated binary size, or -1 if not known.""" +# +# def execute_sharded_on_local_devices(self, arguments: [[Buffer]]) +# -> [Buffer]: +# """Execute on many replicas with Buffer arguments and return value. +# +# Args: +# arguments: A sequence of sequences of Buffers. The i'th element of each +# sequence comprises the arguments for execution on the i'th local +# device. +# +# Returns: +# A list of the computation's outputs as a list of Buffers for each +# device. +# """ +# +# There are different implementations of Executable for different backends. + + +XlaComputation = _xla.XlaComputation +Client = _xla.Client +Memory = _xla.Memory +Array = _xla.Array +ArrayImpl = _xla.ArrayImpl +LoadedExecutable = _xla.LoadedExecutable +Executable = _xla.Executable +DeviceList = _xla.DeviceList +OpSharding = _xla.OpSharding +HloSharding = _xla.HloSharding +Sharding = _xla.Sharding +NamedSharding = _xla.NamedSharding +SingleDeviceSharding = _xla.SingleDeviceSharding +PmapSharding = _xla.PmapSharding +GSPMDSharding = _xla.GSPMDSharding +PjRtLayout = _xla.PjRtLayout +AutotuneCacheMode = _xla.AutotuneCacheMode + + +def LoadedExecutable_execute(self, arguments, device=None): + del device + results = self.execute_sharded(arguments) + return [x[0] for x in results.disassemble_into_single_device_arrays()] + + +def LoadedExecutable_execute_with_token(self, arguments, device=None): + del device + results = self.execute_sharded(arguments, with_tokens=True) + return ( + [x[0] for x in results.disassemble_into_single_device_arrays()], + results.consume_token().get_token(0), + ) + + +LoadedExecutable.execute = LoadedExecutable_execute +LoadedExecutable.execute_with_token = LoadedExecutable_execute_with_token + + +class CustomCallTargetTraits(enum.IntFlag): + DEFAULT = 0 + # Calls to custom call are safe to trace into the command buffer. It means + # that calls to custom call always launch exactly the same device operations + # (can depend on attribute values) that can be captured and then replayed. + # + # Supported only for custom calls implemented with XLA FFI. + COMMAND_BUFFER_COMPATIBLE = 1 + + +class CustomCallHandler(Protocol): + + def __call__( + self, + name: str, + fn: Any, + platform: str, + /, + api_version: int = ..., + traits: CustomCallTargetTraits = ..., + ) -> None: + ... + + +_custom_callback_handler: dict[str, CustomCallHandler] = {} +# Key is xla_platform_name, value is (function_name, function, api_version) +_custom_callback: dict[ + str, list[tuple[str, Any, int, CustomCallTargetTraits]] +] = {} +_custom_callback_lock = threading.Lock() + + +def register_custom_call_target( + name: str, + fn: Any, + platform: str = 'cpu', + api_version: int = 0, + traits: CustomCallTargetTraits = CustomCallTargetTraits.DEFAULT, +) -> None: + """Registers a custom call target. + + Args: + name: bytes containing the name of the function. + fn: a PyCapsule object containing the function pointer. + platform: the target platform. + api_version: the XLA FFI version to use. Supported versions are: 0 for the + untyped FFI and 1 for the typed FFI. + traits: custom call traits corresponding to XLA FFI handler traits. + """ + # To support AMD GPUs, we need to have xla_platform_names["gpu"] == "ROCM" + # Since that is hardcoded to CUDA, we are using the following as workaround. + xla_platform_name = xla_platform_names.get(platform, platform) + with _custom_callback_lock: + if xla_platform_name in _custom_callback_handler: + _custom_callback_handler[xla_platform_name]( + name, fn, xla_platform_name, api_version, traits + ) + else: + _custom_callback.setdefault(xla_platform_name, []).append( + (name, fn, api_version, traits) + ) + + +def register_custom_call_handler( + platform: str, handler: CustomCallHandler +) -> None: + """Registers a custom handler and use it to register existing custom calls. + + If a custom call handler for the platform already exist, calling this method + is a no-op and it will not register a new handler. + + Args: + platform: the target platform. + handler: the function to register a custom call. + """ + xla_platform_name = xla_platform_names.get(platform, platform) + with _custom_callback_lock: + if xla_platform_name in _custom_callback_handler: + logger.debug( + 'Custom call handler for %s is already register. Will not register a' + ' new one', + xla_platform_name, + ) + return + _custom_callback_handler[xla_platform_name] = handler + if xla_platform_name in _custom_callback: + for name, fn, api_version, traits in _custom_callback[xla_platform_name]: + handler(name, fn, xla_platform_name, api_version, traits) + del _custom_callback[xla_platform_name] + + +class CustomTypeIdHandler(Protocol): + + def __call__(self, name: str, capsule: Any) -> None: + ... + + +_custom_type_id_handler: dict[str, CustomTypeIdHandler] = {} +_custom_type_id: dict[str, Any] = {} +_custom_type_id_lock = threading.Lock() + + +def register_custom_type_id( + type_name: str, + type_id: Any, + platform: str = 'cpu', +) -> None: + """Register a custom type id for use with the FFI. + + Args: + type_name: a unique name for the type. + type_id: a PyCapsule object containing a pointer to the ``ffi::TypeId``. + platform: the target platform. + """ + xla_platform_name = xla_platform_names.get(platform, platform) + with _custom_type_id_lock: + if xla_platform_name in _custom_type_id_handler: + _custom_type_id_handler[xla_platform_name](type_name, type_id) + else: + _custom_type_id.setdefault(xla_platform_name, []).append( + (type_name, type_id) + ) + + +def register_custom_type_id_handler( + platform: str, handler: CustomTypeIdHandler +) -> None: + """Register a custom type id handler and use it to register existing type ids. + + If a custom type id handler for the platform already exist, calling this + method is a no-op and it will not register a new handler. + + Args: + platform: the target platform. + handler: the function to register a custom type id. + """ + xla_platform_name = xla_platform_names.get(platform, platform) + with _custom_callback_lock: + if xla_platform_name in _custom_type_id_handler: + logger.debug( + 'Custom type id handler for %s is already register. Will not ' + 'register a new one', + xla_platform_name, + ) + return + _custom_type_id_handler[xla_platform_name] = handler + if xla_platform_name in _custom_type_id: + for name, capsule in _custom_type_id[xla_platform_name]: + handler(name, capsule) + del _custom_type_id[xla_platform_name] + + +register_custom_call_partitioner = _xla.register_custom_call_partitioner +encode_inspect_sharding_callback = _xla.encode_inspect_sharding_callback +hlo_sharding_util = _xla.hlo_sharding_util +register_custom_call_as_batch_partitionable = ( + _xla.register_custom_call_as_batch_partitionable +) + + +Traceback = _xla.Traceback +Frame = _xla.Frame + + +@contextlib.contextmanager +def tracebacks(enabled=True): + """Context manager that enables or disables traceback collection.""" + saved = _xla.tracebacks_enabled() + _xla.set_tracebacks_enabled(enabled) + try: + yield + finally: + _xla.set_tracebacks_enabled(saved) + + +@contextlib.contextmanager +def execution_stream_id(new_id: int): + """Context manager that overwrites and restores the current thread's execution_stream_id.""" + saved = _xla.get_execution_stream_id() + _xla.set_execution_stream_id(new_id) + try: + yield + finally: + _xla.set_execution_stream_id(saved) + + +XlaRuntimeError = _xla.XlaRuntimeError + +# Perform one last garbage collection of deferred Python references. This is +# mostly to keep ASAN happy. +atexit.register(_xla.collect_garbage) + +array_result_handler = _xla.array_result_handler +batched_copy_array_to_devices_with_sharding = ( + _xla.batched_copy_array_to_devices_with_sharding +) +batched_device_put = _xla.batched_device_put +reorder_shards = _xla.reorder_shards +batched_block_until_ready = _xla.batched_block_until_ready +check_and_canonicalize_memory_kind = _xla.check_and_canonicalize_memory_kind +Layout = _xla.Layout +custom_call_targets = _xla.custom_call_targets +ArrayCopySemantics = _xla.ArrayCopySemantics diff --git a/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/INSTALLER b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/METADATA b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ffef2ff3bfa0c42b6e6e3eefda700391d181c9a0 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/METADATA @@ -0,0 +1,84 @@ +Metadata-Version: 2.4 +Name: Jinja2 +Version: 3.1.6 +Summary: A very fast and expressive template engine. +Maintainer-email: Pallets +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: MarkupSafe>=2.0 +Requires-Dist: Babel>=2.7 ; extra == "i18n" +Project-URL: Changes, https://jinja.palletsprojects.com/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://jinja.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/jinja/ +Provides-Extra: i18n + +# Jinja + +Jinja is a fast, expressive, extensible templating engine. Special +placeholders in the template allow writing code similar to Python +syntax. Then the template is passed data to render the final document. + +It includes: + +- Template inheritance and inclusion. +- Define and import macros within templates. +- HTML templates can use autoescaping to prevent XSS from untrusted + user input. +- A sandboxed environment can safely render untrusted templates. +- AsyncIO support for generating templates and calling async + functions. +- I18N support with Babel. +- Templates are compiled to optimized Python code just-in-time and + cached, or can be compiled ahead-of-time. +- Exceptions point to the correct line in templates to make debugging + easier. +- Extensible filters, tests, functions, and even syntax. + +Jinja's philosophy is that while application logic belongs in Python if +possible, it shouldn't make the template designer's job difficult by +restricting functionality too much. + + +## In A Nutshell + +```jinja +{% extends "base.html" %} +{% block title %}Members{% endblock %} +{% block content %} + +{% endblock %} +``` + +## Donate + +The Pallets organization develops and supports Jinja and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/RECORD b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..14ea9ec78c8b960de3cafcc4d9af4cce3f60a790 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/RECORD @@ -0,0 +1,59 @@ +jinja2-3.1.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jinja2-3.1.6.dist-info/METADATA,sha256=aMVUj7Z8QTKhOJjZsx7FDGvqKr3ZFdkh8hQ1XDpkmcg,2871 +jinja2-3.1.6.dist-info/RECORD,, +jinja2-3.1.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jinja2-3.1.6.dist-info/WHEEL,sha256=_2ozNFCLWc93bK4WKHCO-eDUENDlo-dgc9cU3qokYO4,82 +jinja2-3.1.6.dist-info/direct_url.json,sha256=e8JNrFqsgNHo6Q5nme3BP_bus7ZS1NVB87-IzIKTPNE,270 +jinja2-3.1.6.dist-info/entry_points.txt,sha256=OL85gYU1eD8cuPlikifFngXpeBjaxl6rIJ8KkC_3r-I,58 +jinja2-3.1.6.dist-info/licenses/LICENSE.txt,sha256=O0nc7kEF6ze6wQ-vG-JgQI_oXSUrjp3y4JefweCUQ3s,1475 +jinja2/__init__.py,sha256=xxepO9i7DHsqkQrgBEduLtfoz2QCuT6_gbL4XSN1hbU,1928 +jinja2/__pycache__/__init__.cpython-312.pyc,, +jinja2/__pycache__/_identifier.cpython-312.pyc,, +jinja2/__pycache__/async_utils.cpython-312.pyc,, +jinja2/__pycache__/bccache.cpython-312.pyc,, +jinja2/__pycache__/compiler.cpython-312.pyc,, +jinja2/__pycache__/constants.cpython-312.pyc,, +jinja2/__pycache__/debug.cpython-312.pyc,, +jinja2/__pycache__/defaults.cpython-312.pyc,, +jinja2/__pycache__/environment.cpython-312.pyc,, +jinja2/__pycache__/exceptions.cpython-312.pyc,, +jinja2/__pycache__/ext.cpython-312.pyc,, +jinja2/__pycache__/filters.cpython-312.pyc,, +jinja2/__pycache__/idtracking.cpython-312.pyc,, +jinja2/__pycache__/lexer.cpython-312.pyc,, +jinja2/__pycache__/loaders.cpython-312.pyc,, +jinja2/__pycache__/meta.cpython-312.pyc,, +jinja2/__pycache__/nativetypes.cpython-312.pyc,, +jinja2/__pycache__/nodes.cpython-312.pyc,, +jinja2/__pycache__/optimizer.cpython-312.pyc,, +jinja2/__pycache__/parser.cpython-312.pyc,, +jinja2/__pycache__/runtime.cpython-312.pyc,, +jinja2/__pycache__/sandbox.cpython-312.pyc,, +jinja2/__pycache__/tests.cpython-312.pyc,, +jinja2/__pycache__/utils.cpython-312.pyc,, +jinja2/__pycache__/visitor.cpython-312.pyc,, +jinja2/_identifier.py,sha256=_zYctNKzRqlk_murTNlzrju1FFJL7Va_Ijqqd7ii2lU,1958 +jinja2/async_utils.py,sha256=vK-PdsuorOMnWSnEkT3iUJRIkTnYgO2T6MnGxDgHI5o,2834 +jinja2/bccache.py,sha256=gh0qs9rulnXo0PhX5jTJy2UHzI8wFnQ63o_vw7nhzRg,14061 +jinja2/compiler.py,sha256=9RpCQl5X88BHllJiPsHPh295Hh0uApvwFJNQuutULeM,74131 +jinja2/constants.py,sha256=GMoFydBF_kdpaRKPoM5cl5MviquVRLVyZtfp5-16jg0,1433 +jinja2/debug.py,sha256=CnHqCDHd-BVGvti_8ZsTolnXNhA3ECsY-6n_2pwU8Hw,6297 +jinja2/defaults.py,sha256=boBcSw78h-lp20YbaXSJsqkAI2uN_mD_TtCydpeq5wU,1267 +jinja2/environment.py,sha256=9nhrP7Ch-NbGX00wvyr4yy-uhNHq2OCc60ggGrni_fk,61513 +jinja2/exceptions.py,sha256=ioHeHrWwCWNaXX1inHmHVblvc4haO7AXsjCp3GfWvx0,5071 +jinja2/ext.py,sha256=5PF5eHfh8mXAIxXHHRB2xXbXohi8pE3nHSOxa66uS7E,31875 +jinja2/filters.py,sha256=PQ_Egd9n9jSgtnGQYyF4K5j2nYwhUIulhPnyimkdr-k,55212 +jinja2/idtracking.py,sha256=-ll5lIp73pML3ErUYiIJj7tdmWxcH_IlDv3yA_hiZYo,10555 +jinja2/lexer.py,sha256=LYiYio6br-Tep9nPcupWXsPEtjluw3p1mU-lNBVRUfk,29786 +jinja2/loaders.py,sha256=wIrnxjvcbqh5VwW28NSkfotiDq8qNCxIOSFbGUiSLB4,24055 +jinja2/meta.py,sha256=OTDPkaFvU2Hgvx-6akz7154F8BIWaRmvJcBFvwopHww,4397 +jinja2/nativetypes.py,sha256=7GIGALVJgdyL80oZJdQUaUfwSt5q2lSSZbXt0dNf_M4,4210 +jinja2/nodes.py,sha256=m1Duzcr6qhZI8JQ6VyJgUNinjAf5bQzijSmDnMsvUx8,34579 +jinja2/optimizer.py,sha256=rJnCRlQ7pZsEEmMhsQDgC_pKyDHxP5TPS6zVPGsgcu8,1651 +jinja2/parser.py,sha256=lLOFy3sEmHc5IaEHRiH1sQVnId2moUQzhyeJZTtdY30,40383 +jinja2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jinja2/runtime.py,sha256=gDk-GvdriJXqgsGbHgrcKTP0Yp6zPXzhzrIpCFH3jAU,34249 +jinja2/sandbox.py,sha256=Mw2aitlY2I8la7FYhcX2YG9BtUYcLnD0Gh3d29cDWrY,15009 +jinja2/tests.py,sha256=VLsBhVFnWg-PxSBz1MhRnNWgP1ovXk3neO1FLQMeC9Q,5926 +jinja2/utils.py,sha256=rRp3o9e7ZKS4fyrWRbELyLcpuGVTFcnooaOa1qx_FIk,24129 +jinja2/visitor.py,sha256=EcnL1PIwf_4RVCOMxsRNuR8AXHbS1qfAdMOE2ngKJz4,3557 diff --git a/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/REQUESTED b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/WHEEL b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..23d2d7e9a5d381ef8a375db09f82052144d1fd96 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.11.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/direct_url.json b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..6b0c133dd631c81eef3fc42ca0997b6895f42e29 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/direct_url.json @@ -0,0 +1 @@ +{"archive_info": {"hash": "sha256=85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", "hashes": {"sha256": "85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67"}}, "url": "file:///C:/a/ComfyUI/cu128_python_deps/jinja2-3.1.6-py3-none-any.whl"} \ No newline at end of file diff --git a/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/entry_points.txt b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..abc3eae3b3bc573957cf7401711948799b3465c0 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2-3.1.6.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[babel.extractors] +jinja2=jinja2.ext:babel_extract[i18n] + diff --git a/python_embeded/Lib/site-packages/jinja2/__init__.py b/python_embeded/Lib/site-packages/jinja2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a423a3eac16ac550e8e4008d7f5d79401b50e0f --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/__init__.py @@ -0,0 +1,38 @@ +"""Jinja is a template engine written in pure Python. It provides a +non-XML syntax that supports inline expressions and an optional +sandboxed environment. +""" + +from .bccache import BytecodeCache as BytecodeCache +from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache +from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache +from .environment import Environment as Environment +from .environment import Template as Template +from .exceptions import TemplateAssertionError as TemplateAssertionError +from .exceptions import TemplateError as TemplateError +from .exceptions import TemplateNotFound as TemplateNotFound +from .exceptions import TemplateRuntimeError as TemplateRuntimeError +from .exceptions import TemplatesNotFound as TemplatesNotFound +from .exceptions import TemplateSyntaxError as TemplateSyntaxError +from .exceptions import UndefinedError as UndefinedError +from .loaders import BaseLoader as BaseLoader +from .loaders import ChoiceLoader as ChoiceLoader +from .loaders import DictLoader as DictLoader +from .loaders import FileSystemLoader as FileSystemLoader +from .loaders import FunctionLoader as FunctionLoader +from .loaders import ModuleLoader as ModuleLoader +from .loaders import PackageLoader as PackageLoader +from .loaders import PrefixLoader as PrefixLoader +from .runtime import ChainableUndefined as ChainableUndefined +from .runtime import DebugUndefined as DebugUndefined +from .runtime import make_logging_undefined as make_logging_undefined +from .runtime import StrictUndefined as StrictUndefined +from .runtime import Undefined as Undefined +from .utils import clear_caches as clear_caches +from .utils import is_undefined as is_undefined +from .utils import pass_context as pass_context +from .utils import pass_environment as pass_environment +from .utils import pass_eval_context as pass_eval_context +from .utils import select_autoescape as select_autoescape + +__version__ = "3.1.6" diff --git a/python_embeded/Lib/site-packages/jinja2/_identifier.py b/python_embeded/Lib/site-packages/jinja2/_identifier.py new file mode 100644 index 0000000000000000000000000000000000000000..928c1503c7d414a8a86bbf5a82c68d42cb089bd2 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/_identifier.py @@ -0,0 +1,6 @@ +import re + +# generated by scripts/generate_identifier_pattern.py +pattern = re.compile( + r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𐴤-𐽆𐴧-𐽐𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑄴𑅅𑅆𑅳𑆀-𑆂𑆳-𑇀𑇉-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌻𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑑞𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑠬-𑠺𑨁-𑨊𑨳-𑨹𑨻-𑨾𑩇𑩑-𑩛𑪊-𑪙𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𑴱-𑴶𑴺𑴼𑴽𑴿-𑵅𑵇𑶊-𑶎𑶐𑶑𑶓-𑶗𑻳-𑻶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B950 +) diff --git a/python_embeded/Lib/site-packages/jinja2/async_utils.py b/python_embeded/Lib/site-packages/jinja2/async_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c140205c50a3df9863ce1ab610b0c62a483f1b --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/async_utils.py @@ -0,0 +1,99 @@ +import inspect +import typing as t +from functools import WRAPPER_ASSIGNMENTS +from functools import wraps + +from .utils import _PassArg +from .utils import pass_eval_context + +if t.TYPE_CHECKING: + import typing_extensions as te + +V = t.TypeVar("V") + + +def async_variant(normal_func): # type: ignore + def decorator(async_func): # type: ignore + pass_arg = _PassArg.from_obj(normal_func) + need_eval_context = pass_arg is None + + if pass_arg is _PassArg.environment: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].is_async) + + else: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].environment.is_async) + + # Take the doc and annotations from the sync function, but the + # name from the async function. Pallets-Sphinx-Themes + # build_function_directive expects __wrapped__ to point to the + # sync function. + async_func_attrs = ("__module__", "__name__", "__qualname__") + normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs)) + + @wraps(normal_func, assigned=normal_func_attrs) + @wraps(async_func, assigned=async_func_attrs, updated=()) + def wrapper(*args, **kwargs): # type: ignore + b = is_async(args) + + if need_eval_context: + args = args[1:] + + if b: + return async_func(*args, **kwargs) + + return normal_func(*args, **kwargs) + + if need_eval_context: + wrapper = pass_eval_context(wrapper) + + wrapper.jinja_async_variant = True # type: ignore[attr-defined] + return wrapper + + return decorator + + +_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)} + + +async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V": + # Avoid a costly call to isawaitable + if type(value) in _common_primitives: + return t.cast("V", value) + + if inspect.isawaitable(value): + return await t.cast("t.Awaitable[V]", value) + + return value + + +class _IteratorToAsyncIterator(t.Generic[V]): + def __init__(self, iterator: "t.Iterator[V]"): + self._iterator = iterator + + def __aiter__(self) -> "te.Self": + return self + + async def __anext__(self) -> V: + try: + return next(self._iterator) + except StopIteration as e: + raise StopAsyncIteration(e.value) from e + + +def auto_aiter( + iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> "t.AsyncIterator[V]": + if hasattr(iterable, "__aiter__"): + return iterable.__aiter__() + else: + return _IteratorToAsyncIterator(iter(iterable)) + + +async def auto_to_list( + value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> t.List["V"]: + return [x async for x in auto_aiter(value)] diff --git a/python_embeded/Lib/site-packages/jinja2/bccache.py b/python_embeded/Lib/site-packages/jinja2/bccache.py new file mode 100644 index 0000000000000000000000000000000000000000..ada8b099ff251ea9c6da4c42e1383f37e359f06a --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/bccache.py @@ -0,0 +1,408 @@ +"""The optional bytecode cache system. This is useful if you have very +complex template situations and the compilation of all those templates +slows down your application too much. + +Situations where this is useful are often forking web applications that +are initialized on the first request. +""" + +import errno +import fnmatch +import marshal +import os +import pickle +import stat +import sys +import tempfile +import typing as t +from hashlib import sha1 +from io import BytesIO +from types import CodeType + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + + class _MemcachedClient(te.Protocol): + def get(self, key: str) -> bytes: ... + + def set( + self, key: str, value: bytes, timeout: t.Optional[int] = None + ) -> None: ... + + +bc_version = 5 +# Magic bytes to identify Jinja bytecode cache files. Contains the +# Python major and minor version to avoid loading incompatible bytecode +# if a project upgrades its Python version. +bc_magic = ( + b"j2" + + pickle.dumps(bc_version, 2) + + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2) +) + + +class Bucket: + """Buckets are used to store the bytecode for one template. It's created + and initialized by the bytecode cache and passed to the loading functions. + + The buckets get an internal checksum from the cache assigned and use this + to automatically reject outdated cache material. Individual bytecode + cache subclasses don't have to care about cache invalidation. + """ + + def __init__(self, environment: "Environment", key: str, checksum: str) -> None: + self.environment = environment + self.key = key + self.checksum = checksum + self.reset() + + def reset(self) -> None: + """Resets the bucket (unloads the bytecode).""" + self.code: t.Optional[CodeType] = None + + def load_bytecode(self, f: t.BinaryIO) -> None: + """Loads bytecode from a file or file like object.""" + # make sure the magic header is correct + magic = f.read(len(bc_magic)) + if magic != bc_magic: + self.reset() + return + # the source code of the file changed, we need to reload + checksum = pickle.load(f) + if self.checksum != checksum: + self.reset() + return + # if marshal_load fails then we need to reload + try: + self.code = marshal.load(f) + except (EOFError, ValueError, TypeError): + self.reset() + return + + def write_bytecode(self, f: t.IO[bytes]) -> None: + """Dump the bytecode into the file or file like object passed.""" + if self.code is None: + raise TypeError("can't write empty bucket") + f.write(bc_magic) + pickle.dump(self.checksum, f, 2) + marshal.dump(self.code, f) + + def bytecode_from_string(self, string: bytes) -> None: + """Load bytecode from bytes.""" + self.load_bytecode(BytesIO(string)) + + def bytecode_to_string(self) -> bytes: + """Return the bytecode as bytes.""" + out = BytesIO() + self.write_bytecode(out) + return out.getvalue() + + +class BytecodeCache: + """To implement your own bytecode cache you have to subclass this class + and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of + these methods are passed a :class:`~jinja2.bccache.Bucket`. + + A very basic bytecode cache that saves the bytecode on the file system:: + + from os import path + + class MyCache(BytecodeCache): + + def __init__(self, directory): + self.directory = directory + + def load_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + if path.exists(filename): + with open(filename, 'rb') as f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + with open(filename, 'wb') as f: + bucket.write_bytecode(f) + + A more advanced version of a filesystem based bytecode cache is part of + Jinja. + """ + + def load_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to load bytecode into a + bucket. If they are not able to find code in the cache for the + bucket, it must not do anything. + """ + raise NotImplementedError() + + def dump_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to write the bytecode + from a bucket back to the cache. If it unable to do so it must not + fail silently but raise an exception. + """ + raise NotImplementedError() + + def clear(self) -> None: + """Clears the cache. This method is not used by Jinja but should be + implemented to allow applications to clear the bytecode cache used + by a particular environment. + """ + + def get_cache_key( + self, name: str, filename: t.Optional[t.Union[str]] = None + ) -> str: + """Returns the unique hash key for this template name.""" + hash = sha1(name.encode("utf-8")) + + if filename is not None: + hash.update(f"|{filename}".encode()) + + return hash.hexdigest() + + def get_source_checksum(self, source: str) -> str: + """Returns a checksum for the source.""" + return sha1(source.encode("utf-8")).hexdigest() + + def get_bucket( + self, + environment: "Environment", + name: str, + filename: t.Optional[str], + source: str, + ) -> Bucket: + """Return a cache bucket for the given template. All arguments are + mandatory but filename may be `None`. + """ + key = self.get_cache_key(name, filename) + checksum = self.get_source_checksum(source) + bucket = Bucket(environment, key, checksum) + self.load_bytecode(bucket) + return bucket + + def set_bucket(self, bucket: Bucket) -> None: + """Put the bucket into the cache.""" + self.dump_bytecode(bucket) + + +class FileSystemBytecodeCache(BytecodeCache): + """A bytecode cache that stores bytecode on the filesystem. It accepts + two arguments: The directory where the cache items are stored and a + pattern string that is used to build the filename. + + If no directory is specified a default cache directory is selected. On + Windows the user's temp directory is used, on UNIX systems a directory + is created for the user in the system temp directory. + + The pattern can be used to have multiple separate caches operate on the + same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s`` + is replaced with the cache key. + + >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache') + + This bytecode cache supports clearing of the cache using the clear method. + """ + + def __init__( + self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache" + ) -> None: + if directory is None: + directory = self._get_default_cache_dir() + self.directory = directory + self.pattern = pattern + + def _get_default_cache_dir(self) -> str: + def _unsafe_dir() -> "te.NoReturn": + raise RuntimeError( + "Cannot determine safe temp directory. You " + "need to explicitly provide one." + ) + + tmpdir = tempfile.gettempdir() + + # On windows the temporary directory is used specific unless + # explicitly forced otherwise. We can just use that. + if os.name == "nt": + return tmpdir + if not hasattr(os, "getuid"): + _unsafe_dir() + + dirname = f"_jinja2-cache-{os.getuid()}" + actual_dir = os.path.join(tmpdir, dirname) + + try: + os.mkdir(actual_dir, stat.S_IRWXU) + except OSError as e: + if e.errno != errno.EEXIST: + raise + try: + os.chmod(actual_dir, stat.S_IRWXU) + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + except OSError as e: + if e.errno != errno.EEXIST: + raise + + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + + return actual_dir + + def _get_cache_filename(self, bucket: Bucket) -> str: + return os.path.join(self.directory, self.pattern % (bucket.key,)) + + def load_bytecode(self, bucket: Bucket) -> None: + filename = self._get_cache_filename(bucket) + + # Don't test for existence before opening the file, since the + # file could disappear after the test before the open. + try: + f = open(filename, "rb") + except (FileNotFoundError, IsADirectoryError, PermissionError): + # PermissionError can occur on Windows when an operation is + # in progress, such as calling clear(). + return + + with f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket: Bucket) -> None: + # Write to a temporary file, then rename to the real name after + # writing. This avoids another process reading the file before + # it is fully written. + name = self._get_cache_filename(bucket) + f = tempfile.NamedTemporaryFile( + mode="wb", + dir=os.path.dirname(name), + prefix=os.path.basename(name), + suffix=".tmp", + delete=False, + ) + + def remove_silent() -> None: + try: + os.remove(f.name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + pass + + try: + with f: + bucket.write_bytecode(f) + except BaseException: + remove_silent() + raise + + try: + os.replace(f.name, name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + remove_silent() + except BaseException: + remove_silent() + raise + + def clear(self) -> None: + # imported lazily here because google app-engine doesn't support + # write access on the file system and the function does not exist + # normally. + from os import remove + + files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",)) + for filename in files: + try: + remove(os.path.join(self.directory, filename)) + except OSError: + pass + + +class MemcachedBytecodeCache(BytecodeCache): + """This class implements a bytecode cache that uses a memcache cache for + storing the information. It does not enforce a specific memcache library + (tummy's memcache or cmemcache) but will accept any class that provides + the minimal interface required. + + Libraries compatible with this class: + + - `cachelib `_ + - `python-memcached `_ + + (Unfortunately the django cache interface is not compatible because it + does not support storing binary data, only text. You can however pass + the underlying cache client to the bytecode cache which is available + as `django.core.cache.cache._client`.) + + The minimal interface for the client passed to the constructor is this: + + .. class:: MinimalClientInterface + + .. method:: set(key, value[, timeout]) + + Stores the bytecode in the cache. `value` is a string and + `timeout` the timeout of the key. If timeout is not provided + a default timeout or no timeout should be assumed, if it's + provided it's an integer with the number of seconds the cache + item should exist. + + .. method:: get(key) + + Returns the value for the cache key. If the item does not + exist in the cache the return value must be `None`. + + The other arguments to the constructor are the prefix for all keys that + is added before the actual cache key and the timeout for the bytecode in + the cache system. We recommend a high (or no) timeout. + + This bytecode cache does not support clearing of used items in the cache. + The clear method is a no-operation function. + + .. versionadded:: 2.7 + Added support for ignoring memcache errors through the + `ignore_memcache_errors` parameter. + """ + + def __init__( + self, + client: "_MemcachedClient", + prefix: str = "jinja2/bytecode/", + timeout: t.Optional[int] = None, + ignore_memcache_errors: bool = True, + ): + self.client = client + self.prefix = prefix + self.timeout = timeout + self.ignore_memcache_errors = ignore_memcache_errors + + def load_bytecode(self, bucket: Bucket) -> None: + try: + code = self.client.get(self.prefix + bucket.key) + except Exception: + if not self.ignore_memcache_errors: + raise + else: + bucket.bytecode_from_string(code) + + def dump_bytecode(self, bucket: Bucket) -> None: + key = self.prefix + bucket.key + value = bucket.bytecode_to_string() + + try: + if self.timeout is not None: + self.client.set(key, value, self.timeout) + else: + self.client.set(key, value) + except Exception: + if not self.ignore_memcache_errors: + raise diff --git a/python_embeded/Lib/site-packages/jinja2/compiler.py b/python_embeded/Lib/site-packages/jinja2/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ff6a1b11af3e1a868d1a74c48d842390259b43 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/compiler.py @@ -0,0 +1,1998 @@ +"""Compiles nodes from the parser into Python code.""" + +import typing as t +from contextlib import contextmanager +from functools import update_wrapper +from io import StringIO +from itertools import chain +from keyword import iskeyword as is_python_keyword + +from markupsafe import escape +from markupsafe import Markup + +from . import nodes +from .exceptions import TemplateAssertionError +from .idtracking import Symbols +from .idtracking import VAR_LOAD_ALIAS +from .idtracking import VAR_LOAD_PARAMETER +from .idtracking import VAR_LOAD_RESOLVE +from .idtracking import VAR_LOAD_UNDEFINED +from .nodes import EvalContext +from .optimizer import Optimizer +from .utils import _PassArg +from .utils import concat +from .visitor import NodeVisitor + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + +operators = { + "eq": "==", + "ne": "!=", + "gt": ">", + "gteq": ">=", + "lt": "<", + "lteq": "<=", + "in": "in", + "notin": "not in", +} + + +def optimizeconst(f: F) -> F: + def new_func( + self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any + ) -> t.Any: + # Only optimize if the frame is not volatile + if self.optimizer is not None and not frame.eval_ctx.volatile: + new_node = self.optimizer.visit(node, frame.eval_ctx) + + if new_node != node: + return self.visit(new_node, frame) + + return f(self, node, frame, **kwargs) + + return update_wrapper(new_func, f) # type: ignore[return-value] + + +def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore + ): + self.write(f"environment.call_binop(context, {op!r}, ") + self.visit(node.left, frame) + self.write(", ") + self.visit(node.right, frame) + else: + self.write("(") + self.visit(node.left, frame) + self.write(f" {op} ") + self.visit(node.right, frame) + + self.write(")") + + return visitor + + +def _make_unop( + op: str, +) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore + ): + self.write(f"environment.call_unop(context, {op!r}, ") + self.visit(node.node, frame) + else: + self.write("(" + op) + self.visit(node.node, frame) + + self.write(")") + + return visitor + + +def generate( + node: nodes.Template, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, +) -> t.Optional[str]: + """Generate the python source for a node tree.""" + if not isinstance(node, nodes.Template): + raise TypeError("Can't compile non template nodes") + + generator = environment.code_generator_class( + environment, name, filename, stream, defer_init, optimized + ) + generator.visit(node) + + if stream is None: + return generator.stream.getvalue() # type: ignore + + return None + + +def has_safe_repr(value: t.Any) -> bool: + """Does the node have a safe representation?""" + if value is None or value is NotImplemented or value is Ellipsis: + return True + + if type(value) in {bool, int, float, complex, range, str, Markup}: + return True + + if type(value) in {tuple, list, set, frozenset}: + return all(has_safe_repr(v) for v in value) + + if type(value) is dict: # noqa E721 + return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items()) + + return False + + +def find_undeclared( + nodes: t.Iterable[nodes.Node], names: t.Iterable[str] +) -> t.Set[str]: + """Check if the names passed are accessed undeclared. The return value + is a set of all the undeclared names from the sequence of names found. + """ + visitor = UndeclaredNameVisitor(names) + try: + for node in nodes: + visitor.visit(node) + except VisitorExit: + pass + return visitor.undeclared + + +class MacroRef: + def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: + self.node = node + self.accesses_caller = False + self.accesses_kwargs = False + self.accesses_varargs = False + + +class Frame: + """Holds compile time information for us.""" + + def __init__( + self, + eval_ctx: EvalContext, + parent: t.Optional["Frame"] = None, + level: t.Optional[int] = None, + ) -> None: + self.eval_ctx = eval_ctx + + # the parent of this frame + self.parent = parent + + if parent is None: + self.symbols = Symbols(level=level) + + # in some dynamic inheritance situations the compiler needs to add + # write tests around output statements. + self.require_output_check = False + + # inside some tags we are using a buffer rather than yield statements. + # this for example affects {% filter %} or {% macro %}. If a frame + # is buffered this variable points to the name of the list used as + # buffer. + self.buffer: t.Optional[str] = None + + # the name of the block we're in, otherwise None. + self.block: t.Optional[str] = None + + else: + self.symbols = Symbols(parent.symbols, level=level) + self.require_output_check = parent.require_output_check + self.buffer = parent.buffer + self.block = parent.block + + # a toplevel frame is the root + soft frames such as if conditions. + self.toplevel = False + + # the root frame is basically just the outermost frame, so no if + # conditions. This information is used to optimize inheritance + # situations. + self.rootlevel = False + + # variables set inside of loops and blocks should not affect outer frames, + # but they still needs to be kept track of as part of the active context. + self.loop_frame = False + self.block_frame = False + + # track whether the frame is being used in an if-statement or conditional + # expression as it determines which errors should be raised during runtime + # or compile time. + self.soft_frame = False + + def copy(self) -> "te.Self": + """Create a copy of the current one.""" + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.symbols = self.symbols.copy() + return rv + + def inner(self, isolated: bool = False) -> "Frame": + """Return an inner frame.""" + if isolated: + return Frame(self.eval_ctx, level=self.symbols.level + 1) + return Frame(self.eval_ctx, self) + + def soft(self) -> "te.Self": + """Return a soft frame. A soft frame may not be modified as + standalone thing as it shares the resources with the frame it + was created of, but it's not a rootlevel frame any longer. + + This is only used to implement if-statements and conditional + expressions. + """ + rv = self.copy() + rv.rootlevel = False + rv.soft_frame = True + return rv + + __copy__ = copy + + +class VisitorExit(RuntimeError): + """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" + + +class DependencyFinderVisitor(NodeVisitor): + """A visitor that collects filter and test calls.""" + + def __init__(self) -> None: + self.filters: t.Set[str] = set() + self.tests: t.Set[str] = set() + + def visit_Filter(self, node: nodes.Filter) -> None: + self.generic_visit(node) + self.filters.add(node.name) + + def visit_Test(self, node: nodes.Test) -> None: + self.generic_visit(node) + self.tests.add(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting at blocks.""" + + +class UndeclaredNameVisitor(NodeVisitor): + """A visitor that checks if a name is accessed without being + declared. This is different from the frame visitor as it will + not stop at closure frames. + """ + + def __init__(self, names: t.Iterable[str]) -> None: + self.names = set(names) + self.undeclared: t.Set[str] = set() + + def visit_Name(self, node: nodes.Name) -> None: + if node.ctx == "load" and node.name in self.names: + self.undeclared.add(node.name) + if self.undeclared == self.names: + raise VisitorExit() + else: + self.names.discard(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting a blocks.""" + + +class CompilerExit(Exception): + """Raised if the compiler encountered a situation where it just + doesn't make sense to further process the code. Any block that + raises such an exception is not further processed. + """ + + +class CodeGenerator(NodeVisitor): + def __init__( + self, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, + ) -> None: + if stream is None: + stream = StringIO() + self.environment = environment + self.name = name + self.filename = filename + self.stream = stream + self.created_block_context = False + self.defer_init = defer_init + self.optimizer: t.Optional[Optimizer] = None + + if optimized: + self.optimizer = Optimizer(environment) + + # aliases for imports + self.import_aliases: t.Dict[str, str] = {} + + # a registry for all blocks. Because blocks are moved out + # into the global python scope they are registered here + self.blocks: t.Dict[str, nodes.Block] = {} + + # the number of extends statements so far + self.extends_so_far = 0 + + # some templates have a rootlevel extends. In this case we + # can safely assume that we're a child template and do some + # more optimizations. + self.has_known_extends = False + + # the current line number + self.code_lineno = 1 + + # registry of all filters and tests (global, not block local) + self.tests: t.Dict[str, str] = {} + self.filters: t.Dict[str, str] = {} + + # the debug information + self.debug_info: t.List[t.Tuple[int, int]] = [] + self._write_debug_info: t.Optional[int] = None + + # the number of new lines before the next write() + self._new_lines = 0 + + # the line number of the last written statement + self._last_line = 0 + + # true if nothing was written so far. + self._first_write = True + + # used by the `temporary_identifier` method to get new + # unique, temporary identifier + self._last_identifier = 0 + + # the current indentation + self._indentation = 0 + + # Tracks toplevel assignments + self._assign_stack: t.List[t.Set[str]] = [] + + # Tracks parameter definition blocks + self._param_def_block: t.List[t.Set[str]] = [] + + # Tracks the current context. + self._context_reference_stack = ["context"] + + @property + def optimized(self) -> bool: + return self.optimizer is not None + + # -- Various compilation helpers + + def fail(self, msg: str, lineno: int) -> "te.NoReturn": + """Fail with a :exc:`TemplateAssertionError`.""" + raise TemplateAssertionError(msg, lineno, self.name, self.filename) + + def temporary_identifier(self) -> str: + """Get a new unique identifier.""" + self._last_identifier += 1 + return f"t_{self._last_identifier}" + + def buffer(self, frame: Frame) -> None: + """Enable buffering for the frame from that point onwards.""" + frame.buffer = self.temporary_identifier() + self.writeline(f"{frame.buffer} = []") + + def return_buffer_contents( + self, frame: Frame, force_unescaped: bool = False + ) -> None: + """Return the buffer contents of the frame.""" + if not force_unescaped: + if frame.eval_ctx.volatile: + self.writeline("if context.eval_ctx.autoescape:") + self.indent() + self.writeline(f"return Markup(concat({frame.buffer}))") + self.outdent() + self.writeline("else:") + self.indent() + self.writeline(f"return concat({frame.buffer})") + self.outdent() + return + elif frame.eval_ctx.autoescape: + self.writeline(f"return Markup(concat({frame.buffer}))") + return + self.writeline(f"return concat({frame.buffer})") + + def indent(self) -> None: + """Indent by one.""" + self._indentation += 1 + + def outdent(self, step: int = 1) -> None: + """Outdent by step.""" + self._indentation -= step + + def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None: + """Yield or write into the frame buffer.""" + if frame.buffer is None: + self.writeline("yield ", node) + else: + self.writeline(f"{frame.buffer}.append(", node) + + def end_write(self, frame: Frame) -> None: + """End the writing process started by `start_write`.""" + if frame.buffer is not None: + self.write(")") + + def simple_write( + self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None + ) -> None: + """Simple shortcut for start_write + write + end_write.""" + self.start_write(frame, node) + self.write(s) + self.end_write(frame) + + def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None: + """Visit a list of nodes as block in a frame. If the current frame + is no buffer a dummy ``if 0: yield None`` is written automatically. + """ + try: + self.writeline("pass") + for node in nodes: + self.visit(node, frame) + except CompilerExit: + pass + + def write(self, x: str) -> None: + """Write a string into the output stream.""" + if self._new_lines: + if not self._first_write: + self.stream.write("\n" * self._new_lines) + self.code_lineno += self._new_lines + if self._write_debug_info is not None: + self.debug_info.append((self._write_debug_info, self.code_lineno)) + self._write_debug_info = None + self._first_write = False + self.stream.write(" " * self._indentation) + self._new_lines = 0 + self.stream.write(x) + + def writeline( + self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 + ) -> None: + """Combination of newline and write.""" + self.newline(node, extra) + self.write(x) + + def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None: + """Add one or more newlines before the next write.""" + self._new_lines = max(self._new_lines, 1 + extra) + if node is not None and node.lineno != self._last_line: + self._write_debug_info = node.lineno + self._last_line = node.lineno + + def signature( + self, + node: t.Union[nodes.Call, nodes.Filter, nodes.Test], + frame: Frame, + extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + ) -> None: + """Writes a function call to the stream for the current node. + A leading comma is added automatically. The extra keyword + arguments may not include python keywords otherwise a syntax + error could occur. The extra keyword arguments should be given + as python dict. + """ + # if any of the given keyword arguments is a python keyword + # we have to make sure that no invalid call is created. + kwarg_workaround = any( + is_python_keyword(t.cast(str, k)) + for k in chain((x.key for x in node.kwargs), extra_kwargs or ()) + ) + + for arg in node.args: + self.write(", ") + self.visit(arg, frame) + + if not kwarg_workaround: + for kwarg in node.kwargs: + self.write(", ") + self.visit(kwarg, frame) + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f", {key}={value}") + if node.dyn_args: + self.write(", *") + self.visit(node.dyn_args, frame) + + if kwarg_workaround: + if node.dyn_kwargs is not None: + self.write(", **dict({") + else: + self.write(", **{") + for kwarg in node.kwargs: + self.write(f"{kwarg.key!r}: ") + self.visit(kwarg.value, frame) + self.write(", ") + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f"{key!r}: {value}, ") + if node.dyn_kwargs is not None: + self.write("}, **") + self.visit(node.dyn_kwargs, frame) + self.write(")") + else: + self.write("}") + + elif node.dyn_kwargs is not None: + self.write(", **") + self.visit(node.dyn_kwargs, frame) + + def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None: + """Find all filter and test names used in the template and + assign them to variables in the compiled namespace. Checking + that the names are registered with the environment is done when + compiling the Filter and Test nodes. If the node is in an If or + CondExpr node, the check is done at runtime instead. + + .. versionchanged:: 3.0 + Filters and tests in If and CondExpr nodes are checked at + runtime instead of compile time. + """ + visitor = DependencyFinderVisitor() + + for node in nodes: + visitor.visit(node) + + for id_map, names, dependency in ( + (self.filters, visitor.filters, "filters"), + ( + self.tests, + visitor.tests, + "tests", + ), + ): + for name in sorted(names): + if name not in id_map: + id_map[name] = self.temporary_identifier() + + # add check during runtime that dependencies used inside of executed + # blocks are defined, as this step may be skipped during compile time + self.writeline("try:") + self.indent() + self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]") + self.outdent() + self.writeline("except KeyError:") + self.indent() + self.writeline("@internalcode") + self.writeline(f"def {id_map[name]}(*unused):") + self.indent() + self.writeline( + f'raise TemplateRuntimeError("No {dependency[:-1]}' + f' named {name!r} found.")' + ) + self.outdent() + self.outdent() + + def enter_frame(self, frame: Frame) -> None: + undefs = [] + for target, (action, param) in frame.symbols.loads.items(): + if action == VAR_LOAD_PARAMETER: + pass + elif action == VAR_LOAD_RESOLVE: + self.writeline(f"{target} = {self.get_resolve_func()}({param!r})") + elif action == VAR_LOAD_ALIAS: + self.writeline(f"{target} = {param}") + elif action == VAR_LOAD_UNDEFINED: + undefs.append(target) + else: + raise NotImplementedError("unknown load instruction") + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None: + if not with_python_scope: + undefs = [] + for target in frame.symbols.loads: + undefs.append(target) + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str: + return async_value if self.environment.is_async else sync_value + + def func(self, name: str) -> str: + return f"{self.choose_async()}def {name}" + + def macro_body( + self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame + ) -> t.Tuple[Frame, MacroRef]: + """Dump the function def of a macro or call block.""" + frame = frame.inner() + frame.symbols.analyze_node(node) + macro_ref = MacroRef(node) + + explicit_caller = None + skip_special_params = set() + args = [] + + for idx, arg in enumerate(node.args): + if arg.name == "caller": + explicit_caller = idx + if arg.name in ("kwargs", "varargs"): + skip_special_params.add(arg.name) + args.append(frame.symbols.ref(arg.name)) + + undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs")) + + if "caller" in undeclared: + # In older Jinja versions there was a bug that allowed caller + # to retain the special behavior even if it was mentioned in + # the argument list. However thankfully this was only really + # working if it was the last argument. So we are explicitly + # checking this now and error out if it is anywhere else in + # the argument list. + if explicit_caller is not None: + try: + node.defaults[explicit_caller - len(node.args)] + except IndexError: + self.fail( + "When defining macros or call blocks the " + 'special "caller" argument must be omitted ' + "or be given a default.", + node.lineno, + ) + else: + args.append(frame.symbols.declare_parameter("caller")) + macro_ref.accesses_caller = True + if "kwargs" in undeclared and "kwargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("kwargs")) + macro_ref.accesses_kwargs = True + if "varargs" in undeclared and "varargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("varargs")) + macro_ref.accesses_varargs = True + + # macros are delayed, they never require output checks + frame.require_output_check = False + frame.symbols.analyze_node(node) + self.writeline(f"{self.func('macro')}({', '.join(args)}):", node) + self.indent() + + self.buffer(frame) + self.enter_frame(frame) + + self.push_parameter_definitions(frame) + for idx, arg in enumerate(node.args): + ref = frame.symbols.ref(arg.name) + self.writeline(f"if {ref} is missing:") + self.indent() + try: + default = node.defaults[idx - len(node.args)] + except IndexError: + self.writeline( + f'{ref} = undefined("parameter {arg.name!r} was not provided",' + f" name={arg.name!r})" + ) + else: + self.writeline(f"{ref} = ") + self.visit(default, frame) + self.mark_parameter_stored(ref) + self.outdent() + self.pop_parameter_definitions() + + self.blockvisit(node.body, frame) + self.return_buffer_contents(frame, force_unescaped=True) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + return frame, macro_ref + + def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None: + """Dump the macro definition for the def created by macro_body.""" + arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args) + name = getattr(macro_ref.node, "name", None) + if len(macro_ref.node.args) == 1: + arg_tuple += "," + self.write( + f"Macro(environment, macro, {name!r}, ({arg_tuple})," + f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r}," + f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)" + ) + + def position(self, node: nodes.Node) -> str: + """Return a human readable position for the node.""" + rv = f"line {node.lineno}" + if self.name is not None: + rv = f"{rv} in {self.name!r}" + return rv + + def dump_local_context(self, frame: Frame) -> str: + items_kv = ", ".join( + f"{name!r}: {target}" + for name, target in frame.symbols.dump_stores().items() + ) + return f"{{{items_kv}}}" + + def write_commons(self) -> None: + """Writes a common preamble that is used by root and block functions. + Primarily this sets up common local helpers and enforces a generator + through a dead branch. + """ + self.writeline("resolve = context.resolve_or_missing") + self.writeline("undefined = environment.undefined") + self.writeline("concat = environment.concat") + # always use the standard Undefined class for the implicit else of + # conditional expressions + self.writeline("cond_expr_undefined = Undefined") + self.writeline("if 0: yield None") + + def push_parameter_definitions(self, frame: Frame) -> None: + """Pushes all parameter targets from the given frame into a local + stack that permits tracking of yet to be assigned parameters. In + particular this enables the optimization from `visit_Name` to skip + undefined expressions for parameters in macros as macros can reference + otherwise unbound parameters. + """ + self._param_def_block.append(frame.symbols.dump_param_targets()) + + def pop_parameter_definitions(self) -> None: + """Pops the current parameter definitions set.""" + self._param_def_block.pop() + + def mark_parameter_stored(self, target: str) -> None: + """Marks a parameter in the current parameter definitions as stored. + This will skip the enforced undefined checks. + """ + if self._param_def_block: + self._param_def_block[-1].discard(target) + + def push_context_reference(self, target: str) -> None: + self._context_reference_stack.append(target) + + def pop_context_reference(self) -> None: + self._context_reference_stack.pop() + + def get_context_ref(self) -> str: + return self._context_reference_stack[-1] + + def get_resolve_func(self) -> str: + target = self._context_reference_stack[-1] + if target == "context": + return "resolve" + return f"{target}.resolve" + + def derive_context(self, frame: Frame) -> str: + return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})" + + def parameter_is_undeclared(self, target: str) -> bool: + """Checks if a given target is an undeclared parameter.""" + if not self._param_def_block: + return False + return target in self._param_def_block[-1] + + def push_assign_tracking(self) -> None: + """Pushes a new layer for assignment tracking.""" + self._assign_stack.append(set()) + + def pop_assign_tracking(self, frame: Frame) -> None: + """Pops the topmost level for assignment tracking and updates the + context variables if necessary. + """ + vars = self._assign_stack.pop() + if ( + not frame.block_frame + and not frame.loop_frame + and not frame.toplevel + or not vars + ): + return + public_names = [x for x in vars if x[:1] != "_"] + if len(vars) == 1: + name = next(iter(vars)) + ref = frame.symbols.ref(name) + if frame.loop_frame: + self.writeline(f"_loop_vars[{name!r}] = {ref}") + return + if frame.block_frame: + self.writeline(f"_block_vars[{name!r}] = {ref}") + return + self.writeline(f"context.vars[{name!r}] = {ref}") + else: + if frame.loop_frame: + self.writeline("_loop_vars.update({") + elif frame.block_frame: + self.writeline("_block_vars.update({") + else: + self.writeline("context.vars.update({") + for idx, name in enumerate(sorted(vars)): + if idx: + self.write(", ") + ref = frame.symbols.ref(name) + self.write(f"{name!r}: {ref}") + self.write("})") + if not frame.block_frame and not frame.loop_frame and public_names: + if len(public_names) == 1: + self.writeline(f"context.exported_vars.add({public_names[0]!r})") + else: + names_str = ", ".join(map(repr, sorted(public_names))) + self.writeline(f"context.exported_vars.update(({names_str}))") + + # -- Statement Visitors + + def visit_Template( + self, node: nodes.Template, frame: t.Optional[Frame] = None + ) -> None: + assert frame is None, "no root frame allowed" + eval_ctx = EvalContext(self.environment, self.name) + + from .runtime import async_exported + from .runtime import exported + + if self.environment.is_async: + exported_names = sorted(exported + async_exported) + else: + exported_names = sorted(exported) + + self.writeline("from jinja2.runtime import " + ", ".join(exported_names)) + + # if we want a deferred initialization we cannot move the + # environment into a local name + envenv = "" if self.defer_init else ", environment=environment" + + # do we have an extends tag at all? If not, we can save some + # overhead by just not processing any inheritance code. + have_extends = node.find(nodes.Extends) is not None + + # find all blocks + for block in node.find_all(nodes.Block): + if block.name in self.blocks: + self.fail(f"block {block.name!r} defined twice", block.lineno) + self.blocks[block.name] = block + + # find all imports and import them + for import_ in node.find_all(nodes.ImportedName): + if import_.importname not in self.import_aliases: + imp = import_.importname + self.import_aliases[imp] = alias = self.temporary_identifier() + if "." in imp: + module, obj = imp.rsplit(".", 1) + self.writeline(f"from {module} import {obj} as {alias}") + else: + self.writeline(f"import {imp} as {alias}") + + # add the load name + self.writeline(f"name = {self.name!r}") + + # generate the root render function. + self.writeline( + f"{self.func('root')}(context, missing=missing{envenv}):", extra=1 + ) + self.indent() + self.write_commons() + + # process the root + frame = Frame(eval_ctx) + if "self" in find_undeclared(node.body, ("self",)): + ref = frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + frame.symbols.analyze_node(node) + frame.toplevel = frame.rootlevel = True + frame.require_output_check = have_extends and not self.has_known_extends + if have_extends: + self.writeline("parent_template = None") + self.enter_frame(frame) + self.pull_dependencies(node.body) + self.blockvisit(node.body, frame) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + # make sure that the parent root is called. + if have_extends: + if not self.has_known_extends: + self.indent() + self.writeline("if parent_template is not None:") + self.indent() + if not self.environment.is_async: + self.writeline("yield from parent_template.root_render_func(context)") + else: + self.writeline("agen = parent_template.root_render_func(context)") + self.writeline("try:") + self.indent() + self.writeline("async for event in agen:") + self.indent() + self.writeline("yield event") + self.outdent() + self.outdent() + self.writeline("finally: await agen.aclose()") + self.outdent(1 + (not self.has_known_extends)) + + # at this point we now have the blocks collected and can visit them too. + for name, block in self.blocks.items(): + self.writeline( + f"{self.func('block_' + name)}(context, missing=missing{envenv}):", + block, + 1, + ) + self.indent() + self.write_commons() + # It's important that we do not make this frame a child of the + # toplevel template. This would cause a variety of + # interesting issues with identifier tracking. + block_frame = Frame(eval_ctx) + block_frame.block_frame = True + undeclared = find_undeclared(block.body, ("self", "super")) + if "self" in undeclared: + ref = block_frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + if "super" in undeclared: + ref = block_frame.symbols.declare_parameter("super") + self.writeline(f"{ref} = context.super({name!r}, block_{name})") + block_frame.symbols.analyze_node(block) + block_frame.block = name + self.writeline("_block_vars = {}") + self.enter_frame(block_frame) + self.pull_dependencies(block.body) + self.blockvisit(block.body, block_frame) + self.leave_frame(block_frame, with_python_scope=True) + self.outdent() + + blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks) + self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1) + debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info) + self.writeline(f"debug_info = {debug_kv_str!r}") + + def visit_Block(self, node: nodes.Block, frame: Frame) -> None: + """Call a block and register it for the template.""" + level = 0 + if frame.toplevel: + # if we know that we are a child template, there is no need to + # check if we are one + if self.has_known_extends: + return + if self.extends_so_far > 0: + self.writeline("if parent_template is None:") + self.indent() + level += 1 + + if node.scoped: + context = self.derive_context(frame) + else: + context = self.get_context_ref() + + if node.required: + self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node) + self.indent() + self.writeline( + f'raise TemplateRuntimeError("Required block {node.name!r} not found")', + node, + ) + self.outdent() + + if not self.environment.is_async and frame.buffer is None: + self.writeline( + f"yield from context.blocks[{node.name!r}][0]({context})", node + ) + else: + self.writeline(f"gen = context.blocks[{node.name!r}][0]({context})") + self.writeline("try:") + self.indent() + self.writeline( + f"{self.choose_async()}for event in gen:", + node, + ) + self.indent() + self.simple_write("event", frame) + self.outdent() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + + self.outdent(level) + + def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None: + """Calls the extender.""" + if not frame.toplevel: + self.fail("cannot use extend from a non top-level scope", node.lineno) + + # if the number of extends statements in general is zero so + # far, we don't have to add a check if something extended + # the template before this one. + if self.extends_so_far > 0: + # if we have a known extends we just add a template runtime + # error into the generated code. We could catch that at compile + # time too, but i welcome it not to confuse users by throwing the + # same error at different times just "because we can". + if not self.has_known_extends: + self.writeline("if parent_template is not None:") + self.indent() + self.writeline('raise TemplateRuntimeError("extended multiple times")') + + # if we have a known extends already we don't need that code here + # as we know that the template execution will end here. + if self.has_known_extends: + raise CompilerExit() + else: + self.outdent() + + self.writeline("parent_template = environment.get_template(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + self.writeline("for name, parent_block in parent_template.blocks.items():") + self.indent() + self.writeline("context.blocks.setdefault(name, []).append(parent_block)") + self.outdent() + + # if this extends statement was in the root level we can take + # advantage of that information and simplify the generated code + # in the top level from this point onwards + if frame.rootlevel: + self.has_known_extends = True + + # and now we have one more + self.extends_so_far += 1 + + def visit_Include(self, node: nodes.Include, frame: Frame) -> None: + """Handles includes.""" + if node.ignore_missing: + self.writeline("try:") + self.indent() + + func_name = "get_or_select_template" + if isinstance(node.template, nodes.Const): + if isinstance(node.template.value, str): + func_name = "get_template" + elif isinstance(node.template.value, (tuple, list)): + func_name = "select_template" + elif isinstance(node.template, (nodes.Tuple, nodes.List)): + func_name = "select_template" + + self.writeline(f"template = environment.{func_name}(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + if node.ignore_missing: + self.outdent() + self.writeline("except TemplateNotFound:") + self.indent() + self.writeline("pass") + self.outdent() + self.writeline("else:") + self.indent() + + def loop_body() -> None: + self.indent() + self.simple_write("event", frame) + self.outdent() + + if node.with_context: + self.writeline( + f"gen = template.root_render_func(" + "template.new_context(context.get_all(), True," + f" {self.dump_local_context(frame)}))" + ) + self.writeline("try:") + self.indent() + self.writeline(f"{self.choose_async()}for event in gen:") + loop_body() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + elif self.environment.is_async: + self.writeline( + "for event in (await template._get_default_module_async())" + "._body_stream:" + ) + loop_body() + else: + self.writeline("yield from template._get_default_module()._body_stream") + + if node.ignore_missing: + self.outdent() + + def _import_common( + self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame + ) -> None: + self.write(f"{self.choose_async('await ')}environment.get_template(") + self.visit(node.template, frame) + self.write(f", {self.name!r}).") + + if node.with_context: + f_name = f"make_module{self.choose_async('_async')}" + self.write( + f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" + ) + else: + self.write(f"_get_default_module{self.choose_async('_async')}(context)") + + def visit_Import(self, node: nodes.Import, frame: Frame) -> None: + """Visit regular imports.""" + self.writeline(f"{frame.symbols.ref(node.target)} = ", node) + if frame.toplevel: + self.write(f"context.vars[{node.target!r}] = ") + + self._import_common(node, frame) + + if frame.toplevel and not node.target.startswith("_"): + self.writeline(f"context.exported_vars.discard({node.target!r})") + + def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None: + """Visit named imports.""" + self.newline(node) + self.write("included_template = ") + self._import_common(node, frame) + var_names = [] + discarded_names = [] + for name in node.names: + if isinstance(name, tuple): + name, alias = name + else: + alias = name + self.writeline( + f"{frame.symbols.ref(alias)} =" + f" getattr(included_template, {name!r}, missing)" + ) + self.writeline(f"if {frame.symbols.ref(alias)} is missing:") + self.indent() + # The position will contain the template name, and will be formatted + # into a string that will be compiled into an f-string. Curly braces + # in the name must be replaced with escapes so that they will not be + # executed as part of the f-string. + position = self.position(node).replace("{", "{{").replace("}", "}}") + message = ( + "the template {included_template.__name__!r}" + f" (imported on {position})" + f" does not export the requested name {name!r}" + ) + self.writeline( + f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})" + ) + self.outdent() + if frame.toplevel: + var_names.append(alias) + if not alias.startswith("_"): + discarded_names.append(alias) + + if var_names: + if len(var_names) == 1: + name = var_names[0] + self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}") + else: + names_kv = ", ".join( + f"{name!r}: {frame.symbols.ref(name)}" for name in var_names + ) + self.writeline(f"context.vars.update({{{names_kv}}})") + if discarded_names: + if len(discarded_names) == 1: + self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})") + else: + names_str = ", ".join(map(repr, discarded_names)) + self.writeline( + f"context.exported_vars.difference_update(({names_str}))" + ) + + def visit_For(self, node: nodes.For, frame: Frame) -> None: + loop_frame = frame.inner() + loop_frame.loop_frame = True + test_frame = frame.inner() + else_frame = frame.inner() + + # try to figure out if we have an extended loop. An extended loop + # is necessary if the loop is in recursive mode if the special loop + # variable is accessed in the body if the body is a scoped block. + extended_loop = ( + node.recursive + or "loop" + in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",)) + or any(block.scoped for block in node.find_all(nodes.Block)) + ) + + loop_ref = None + if extended_loop: + loop_ref = loop_frame.symbols.declare_parameter("loop") + + loop_frame.symbols.analyze_node(node, for_branch="body") + if node.else_: + else_frame.symbols.analyze_node(node, for_branch="else") + + if node.test: + loop_filter_func = self.temporary_identifier() + test_frame.symbols.analyze_node(node, for_branch="test") + self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test) + self.indent() + self.enter_frame(test_frame) + self.writeline(self.choose_async("async for ", "for ")) + self.visit(node.target, loop_frame) + self.write(" in ") + self.write(self.choose_async("auto_aiter(fiter)", "fiter")) + self.write(":") + self.indent() + self.writeline("if ", node.test) + self.visit(node.test, test_frame) + self.write(":") + self.indent() + self.writeline("yield ") + self.visit(node.target, loop_frame) + self.outdent(3) + self.leave_frame(test_frame, with_python_scope=True) + + # if we don't have an recursive loop we have to find the shadowed + # variables at that point. Because loops can be nested but the loop + # variable is a special one we have to enforce aliasing for it. + if node.recursive: + self.writeline( + f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node + ) + self.indent() + self.buffer(loop_frame) + + # Use the same buffer for the else frame + else_frame.buffer = loop_frame.buffer + + # make sure the loop variable is a special one and raise a template + # assertion error if a loop tries to write to loop + if extended_loop: + self.writeline(f"{loop_ref} = missing") + + for name in node.find_all(nodes.Name): + if name.ctx == "store" and name.name == "loop": + self.fail( + "Can't assign to special loop variable in for-loop target", + name.lineno, + ) + + if node.else_: + iteration_indicator = self.temporary_identifier() + self.writeline(f"{iteration_indicator} = 1") + + self.writeline(self.choose_async("async for ", "for "), node) + self.visit(node.target, loop_frame) + if extended_loop: + self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(") + else: + self.write(" in ") + + if node.test: + self.write(f"{loop_filter_func}(") + if node.recursive: + self.write("reciter") + else: + if self.environment.is_async and not extended_loop: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async and not extended_loop: + self.write(")") + if node.test: + self.write(")") + + if node.recursive: + self.write(", undefined, loop_render_func, depth):") + else: + self.write(", undefined):" if extended_loop else ":") + + self.indent() + self.enter_frame(loop_frame) + + self.writeline("_loop_vars = {}") + self.blockvisit(node.body, loop_frame) + if node.else_: + self.writeline(f"{iteration_indicator} = 0") + self.outdent() + self.leave_frame( + loop_frame, with_python_scope=node.recursive and not node.else_ + ) + + if node.else_: + self.writeline(f"if {iteration_indicator}:") + self.indent() + self.enter_frame(else_frame) + self.blockvisit(node.else_, else_frame) + self.leave_frame(else_frame) + self.outdent() + + # if the node was recursive we have to return the buffer contents + # and start the iteration code + if node.recursive: + self.return_buffer_contents(loop_frame) + self.outdent() + self.start_write(frame, node) + self.write(f"{self.choose_async('await ')}loop(") + if self.environment.is_async: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async: + self.write(")") + self.write(", loop)") + self.end_write(frame) + + # at the end of the iteration, clear any assignments made in the + # loop from the top level + if self._assign_stack: + self._assign_stack[-1].difference_update(loop_frame.symbols.stores) + + def visit_If(self, node: nodes.If, frame: Frame) -> None: + if_frame = frame.soft() + self.writeline("if ", node) + self.visit(node.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(node.body, if_frame) + self.outdent() + for elif_ in node.elif_: + self.writeline("elif ", elif_) + self.visit(elif_.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(elif_.body, if_frame) + self.outdent() + if node.else_: + self.writeline("else:") + self.indent() + self.blockvisit(node.else_, if_frame) + self.outdent() + + def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None: + macro_frame, macro_ref = self.macro_body(node, frame) + self.newline() + if frame.toplevel: + if not node.name.startswith("_"): + self.write(f"context.exported_vars.add({node.name!r})") + self.writeline(f"context.vars[{node.name!r}] = ") + self.write(f"{frame.symbols.ref(node.name)} = ") + self.macro_def(macro_ref, macro_frame) + + def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None: + call_frame, macro_ref = self.macro_body(node, frame) + self.writeline("caller = ") + self.macro_def(macro_ref, call_frame) + self.start_write(frame, node) + self.visit_Call(node.call, frame, forward_caller=True) + self.end_write(frame) + + def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None: + filter_frame = frame.inner() + filter_frame.symbols.analyze_node(node) + self.enter_frame(filter_frame) + self.buffer(filter_frame) + self.blockvisit(node.body, filter_frame) + self.start_write(frame, node) + self.visit_Filter(node.filter, filter_frame) + self.end_write(frame) + self.leave_frame(filter_frame) + + def visit_With(self, node: nodes.With, frame: Frame) -> None: + with_frame = frame.inner() + with_frame.symbols.analyze_node(node) + self.enter_frame(with_frame) + for target, expr in zip(node.targets, node.values): + self.newline() + self.visit(target, with_frame) + self.write(" = ") + self.visit(expr, frame) + self.blockvisit(node.body, with_frame) + self.leave_frame(with_frame) + + def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None: + self.newline(node) + self.visit(node.node, frame) + + class _FinalizeInfo(t.NamedTuple): + const: t.Optional[t.Callable[..., str]] + src: t.Optional[str] + + @staticmethod + def _default_finalize(value: t.Any) -> t.Any: + """The default finalize function if the environment isn't + configured with one. Or, if the environment has one, this is + called on that function's output for constants. + """ + return str(value) + + _finalize: t.Optional[_FinalizeInfo] = None + + def _make_finalize(self) -> _FinalizeInfo: + """Build the finalize function to be used on constants and at + runtime. Cached so it's only created once for all output nodes. + + Returns a ``namedtuple`` with the following attributes: + + ``const`` + A function to finalize constant data at compile time. + + ``src`` + Source code to output around nodes to be evaluated at + runtime. + """ + if self._finalize is not None: + return self._finalize + + finalize: t.Optional[t.Callable[..., t.Any]] + finalize = default = self._default_finalize + src = None + + if self.environment.finalize: + src = "environment.finalize(" + env_finalize = self.environment.finalize + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(env_finalize) # type: ignore + ) + finalize = None + + if pass_arg is None: + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(value)) + + else: + src = f"{src}{pass_arg}, " + + if pass_arg == "environment": + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(self.environment, value)) + + self._finalize = self._FinalizeInfo(finalize, src) + return self._finalize + + def _output_const_repr(self, group: t.Iterable[t.Any]) -> str: + """Given a group of constant values converted from ``Output`` + child nodes, produce a string to write to the template module + source. + """ + return repr(concat(group)) + + def _output_child_to_const( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> str: + """Try to optimize a child of an ``Output`` node by trying to + convert it to constant, finalized data at compile time. + + If :exc:`Impossible` is raised, the node is not constant and + will be evaluated at runtime. Any other exception will also be + evaluated at runtime for easier debugging. + """ + const = node.as_const(frame.eval_ctx) + + if frame.eval_ctx.autoescape: + const = escape(const) + + # Template data doesn't go through finalize. + if isinstance(node, nodes.TemplateData): + return str(const) + + return finalize.const(const) # type: ignore + + def _output_child_pre( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code before visiting a child of an + ``Output`` node. + """ + if frame.eval_ctx.volatile: + self.write("(escape if context.eval_ctx.autoescape else str)(") + elif frame.eval_ctx.autoescape: + self.write("escape(") + else: + self.write("str(") + + if finalize.src is not None: + self.write(finalize.src) + + def _output_child_post( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code after visiting a child of an + ``Output`` node. + """ + self.write(")") + + if finalize.src is not None: + self.write(")") + + def visit_Output(self, node: nodes.Output, frame: Frame) -> None: + # If an extends is active, don't render outside a block. + if frame.require_output_check: + # A top-level extends is known to exist at compile time. + if self.has_known_extends: + return + + self.writeline("if parent_template is None:") + self.indent() + + finalize = self._make_finalize() + body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = [] + + # Evaluate constants at compile time if possible. Each item in + # body will be either a list of static data or a node to be + # evaluated at runtime. + for child in node.nodes: + try: + if not ( + # If the finalize function requires runtime context, + # constants can't be evaluated at compile time. + finalize.const + # Unless it's basic template data that won't be + # finalized anyway. + or isinstance(child, nodes.TemplateData) + ): + raise nodes.Impossible() + + const = self._output_child_to_const(child, frame, finalize) + except (nodes.Impossible, Exception): + # The node was not constant and needs to be evaluated at + # runtime. Or another error was raised, which is easier + # to debug at runtime. + body.append(child) + continue + + if body and isinstance(body[-1], list): + body[-1].append(const) + else: + body.append([const]) + + if frame.buffer is not None: + if len(body) == 1: + self.writeline(f"{frame.buffer}.append(") + else: + self.writeline(f"{frame.buffer}.extend((") + + self.indent() + + for item in body: + if isinstance(item, list): + # A group of constant data to join and output. + val = self._output_const_repr(item) + + if frame.buffer is None: + self.writeline("yield " + val) + else: + self.writeline(val + ",") + else: + if frame.buffer is None: + self.writeline("yield ", item) + else: + self.newline(item) + + # A node to be evaluated at runtime. + self._output_child_pre(item, frame, finalize) + self.visit(item, frame) + self._output_child_post(item, frame, finalize) + + if frame.buffer is not None: + self.write(",") + + if frame.buffer is not None: + self.outdent() + self.writeline(")" if len(body) == 1 else "))") + + if frame.require_output_check: + self.outdent() + + def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None: + self.push_assign_tracking() + + # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However, + # it is only valid if it references a Namespace object. Emit a check for + # that for each ref here, before assignment code is emitted. This can't + # be done in visit_NSRef as the ref could be in the middle of a tuple. + seen_refs: t.Set[str] = set() + + for nsref in node.find_all(nodes.NSRef): + if nsref.name in seen_refs: + # Only emit the check for each reference once, in case the same + # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`. + continue + + seen_refs.add(nsref.name) + ref = frame.symbols.ref(nsref.name) + self.writeline(f"if not isinstance({ref}, Namespace):") + self.indent() + self.writeline( + "raise TemplateRuntimeError" + '("cannot assign attribute on non-namespace object")' + ) + self.outdent() + + self.newline(node) + self.visit(node.target, frame) + self.write(" = ") + self.visit(node.node, frame) + self.pop_assign_tracking(frame) + + def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None: + self.push_assign_tracking() + block_frame = frame.inner() + # This is a special case. Since a set block always captures we + # will disable output checks. This way one can use set blocks + # toplevel even in extended templates. + block_frame.require_output_check = False + block_frame.symbols.analyze_node(node) + self.enter_frame(block_frame) + self.buffer(block_frame) + self.blockvisit(node.body, block_frame) + self.newline(node) + self.visit(node.target, frame) + self.write(" = (Markup if context.eval_ctx.autoescape else identity)(") + if node.filter is not None: + self.visit_Filter(node.filter, block_frame) + else: + self.write(f"concat({block_frame.buffer})") + self.write(")") + self.pop_assign_tracking(frame) + self.leave_frame(block_frame) + + # -- Expression Visitors + + def visit_Name(self, node: nodes.Name, frame: Frame) -> None: + if node.ctx == "store" and ( + frame.toplevel or frame.loop_frame or frame.block_frame + ): + if self._assign_stack: + self._assign_stack[-1].add(node.name) + ref = frame.symbols.ref(node.name) + + # If we are looking up a variable we might have to deal with the + # case where it's undefined. We can skip that case if the load + # instruction indicates a parameter which are always defined. + if node.ctx == "load": + load = frame.symbols.find_load(ref) + if not ( + load is not None + and load[0] == VAR_LOAD_PARAMETER + and not self.parameter_is_undeclared(ref) + ): + self.write( + f"(undefined(name={node.name!r}) if {ref} is missing else {ref})" + ) + return + + self.write(ref) + + def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None: + # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally. + # visit_Assign emits code to validate that each ref is to a Namespace + # object only. That can't be emitted here as the ref could be in the + # middle of a tuple assignment. + ref = frame.symbols.ref(node.name) + self.writeline(f"{ref}[{node.attr!r}]") + + def visit_Const(self, node: nodes.Const, frame: Frame) -> None: + val = node.as_const(frame.eval_ctx) + if isinstance(val, float): + self.write(str(val)) + else: + self.write(repr(val)) + + def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None: + try: + self.write(repr(node.as_const(frame.eval_ctx))) + except nodes.Impossible: + self.write( + f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})" + ) + + def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None: + self.write("(") + idx = -1 + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write(",)" if idx == 0 else ")") + + def visit_List(self, node: nodes.List, frame: Frame) -> None: + self.write("[") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write("]") + + def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None: + self.write("{") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item.key, frame) + self.write(": ") + self.visit(item.value, frame) + self.write("}") + + visit_Add = _make_binop("+") + visit_Sub = _make_binop("-") + visit_Mul = _make_binop("*") + visit_Div = _make_binop("/") + visit_FloorDiv = _make_binop("//") + visit_Pow = _make_binop("**") + visit_Mod = _make_binop("%") + visit_And = _make_binop("and") + visit_Or = _make_binop("or") + visit_Pos = _make_unop("+") + visit_Neg = _make_unop("-") + visit_Not = _make_unop("not ") + + @optimizeconst + def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None: + if frame.eval_ctx.volatile: + func_name = "(markup_join if context.eval_ctx.volatile else str_join)" + elif frame.eval_ctx.autoescape: + func_name = "markup_join" + else: + func_name = "str_join" + self.write(f"{func_name}((") + for arg in node.nodes: + self.visit(arg, frame) + self.write(", ") + self.write("))") + + @optimizeconst + def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None: + self.write("(") + self.visit(node.expr, frame) + for op in node.ops: + self.visit(op, frame) + self.write(")") + + def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None: + self.write(f" {operators[node.op]} ") + self.visit(node.expr, frame) + + @optimizeconst + def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getattr(") + self.visit(node.node, frame) + self.write(f", {node.attr!r})") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None: + # slices bypass the environment getitem method. + if isinstance(node.arg, nodes.Slice): + self.visit(node.node, frame) + self.write("[") + self.visit(node.arg, frame) + self.write("]") + else: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getitem(") + self.visit(node.node, frame) + self.write(", ") + self.visit(node.arg, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None: + if node.start is not None: + self.visit(node.start, frame) + self.write(":") + if node.stop is not None: + self.visit(node.stop, frame) + if node.step is not None: + self.write(":") + self.visit(node.step, frame) + + @contextmanager + def _filter_test_common( + self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool + ) -> t.Iterator[None]: + if self.environment.is_async: + self.write("(await auto_await(") + + if is_filter: + self.write(f"{self.filters[node.name]}(") + func = self.environment.filters.get(node.name) + else: + self.write(f"{self.tests[node.name]}(") + func = self.environment.tests.get(node.name) + + # When inside an If or CondExpr frame, allow the filter to be + # undefined at compile time and only raise an error if it's + # actually called at runtime. See pull_dependencies. + if func is None and not frame.soft_frame: + type_name = "filter" if is_filter else "test" + self.fail(f"No {type_name} named {node.name!r}.", node.lineno) + + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(func) # type: ignore + ) + + if pass_arg is not None: + self.write(f"{pass_arg}, ") + + # Back to the visitor function to handle visiting the target of + # the filter or test. + yield + + self.signature(node, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None: + with self._filter_test_common(node, frame, True): + # if the filter node is None we are inside a filter block + # and want to write to the current buffer + if node.node is not None: + self.visit(node.node, frame) + elif frame.eval_ctx.volatile: + self.write( + f"(Markup(concat({frame.buffer}))" + f" if context.eval_ctx.autoescape else concat({frame.buffer}))" + ) + elif frame.eval_ctx.autoescape: + self.write(f"Markup(concat({frame.buffer}))") + else: + self.write(f"concat({frame.buffer})") + + @optimizeconst + def visit_Test(self, node: nodes.Test, frame: Frame) -> None: + with self._filter_test_common(node, frame, False): + self.visit(node.node, frame) + + @optimizeconst + def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None: + frame = frame.soft() + + def write_expr2() -> None: + if node.expr2 is not None: + self.visit(node.expr2, frame) + return + + self.write( + f'cond_expr_undefined("the inline if-expression on' + f" {self.position(node)} evaluated to false and no else" + f' section was defined.")' + ) + + self.write("(") + self.visit(node.expr1, frame) + self.write(" if ") + self.visit(node.test, frame) + self.write(" else ") + write_expr2() + self.write(")") + + @optimizeconst + def visit_Call( + self, node: nodes.Call, frame: Frame, forward_caller: bool = False + ) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + if self.environment.sandboxed: + self.write("environment.call(context, ") + else: + self.write("context.call(") + self.visit(node.node, frame) + extra_kwargs = {"caller": "caller"} if forward_caller else None + loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {} + block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {} + if extra_kwargs: + extra_kwargs.update(loop_kwargs, **block_kwargs) + elif loop_kwargs or block_kwargs: + extra_kwargs = dict(loop_kwargs, **block_kwargs) + self.signature(node, frame, extra_kwargs) + self.write(")") + if self.environment.is_async: + self.write("))") + + def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None: + self.write(node.key + "=") + self.visit(node.value, frame) + + # -- Unused nodes for extensions + + def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None: + self.write("Markup(") + self.visit(node.expr, frame) + self.write(")") + + def visit_MarkSafeIfAutoescape( + self, node: nodes.MarkSafeIfAutoescape, frame: Frame + ) -> None: + self.write("(Markup if context.eval_ctx.autoescape else identity)(") + self.visit(node.expr, frame) + self.write(")") + + def visit_EnvironmentAttribute( + self, node: nodes.EnvironmentAttribute, frame: Frame + ) -> None: + self.write("environment." + node.name) + + def visit_ExtensionAttribute( + self, node: nodes.ExtensionAttribute, frame: Frame + ) -> None: + self.write(f"environment.extensions[{node.identifier!r}].{node.name}") + + def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None: + self.write(self.import_aliases[node.importname]) + + def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None: + self.write(node.name) + + def visit_ContextReference( + self, node: nodes.ContextReference, frame: Frame + ) -> None: + self.write("context") + + def visit_DerivedContextReference( + self, node: nodes.DerivedContextReference, frame: Frame + ) -> None: + self.write(self.derive_context(frame)) + + def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None: + self.writeline("continue", node) + + def visit_Break(self, node: nodes.Break, frame: Frame) -> None: + self.writeline("break", node) + + def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None: + scope_frame = frame.inner() + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + + def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None: + ctx = self.temporary_identifier() + self.writeline(f"{ctx} = {self.derive_context(frame)}") + self.writeline(f"{ctx}.vars = ") + self.visit(node.context, frame) + self.push_context_reference(ctx) + + scope_frame = frame.inner(isolated=True) + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + self.pop_context_reference() + + def visit_EvalContextModifier( + self, node: nodes.EvalContextModifier, frame: Frame + ) -> None: + for keyword in node.options: + self.writeline(f"context.eval_ctx.{keyword.key} = ") + self.visit(keyword.value, frame) + try: + val = keyword.value.as_const(frame.eval_ctx) + except nodes.Impossible: + frame.eval_ctx.volatile = True + else: + setattr(frame.eval_ctx, keyword.key, val) + + def visit_ScopedEvalContextModifier( + self, node: nodes.ScopedEvalContextModifier, frame: Frame + ) -> None: + old_ctx_name = self.temporary_identifier() + saved_ctx = frame.eval_ctx.save() + self.writeline(f"{old_ctx_name} = context.eval_ctx.save()") + self.visit_EvalContextModifier(node, frame) + for child in node.body: + self.visit(child, frame) + frame.eval_ctx.revert(saved_ctx) + self.writeline(f"context.eval_ctx.revert({old_ctx_name})") diff --git a/python_embeded/Lib/site-packages/jinja2/constants.py b/python_embeded/Lib/site-packages/jinja2/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..41a1c23b0a7fe134b1f662545876eb65b31b071e --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/constants.py @@ -0,0 +1,20 @@ +#: list of lorem ipsum words used by the lipsum() helper function +LOREM_IPSUM_WORDS = """\ +a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at +auctor augue bibendum blandit class commodo condimentum congue consectetuer +consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus +diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend +elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames +faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac +hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum +justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem +luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie +mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non +nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque +penatibus per pharetra phasellus placerat platea porta porttitor posuere +potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus +ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit +sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor +tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices +ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus +viverra volutpat vulputate""" diff --git a/python_embeded/Lib/site-packages/jinja2/debug.py b/python_embeded/Lib/site-packages/jinja2/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..eeeeee78b620f5d0745133b4629647973cd7af87 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/debug.py @@ -0,0 +1,191 @@ +import sys +import typing as t +from types import CodeType +from types import TracebackType + +from .exceptions import TemplateSyntaxError +from .utils import internal_code +from .utils import missing + +if t.TYPE_CHECKING: + from .runtime import Context + + +def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException: + """Rewrite the current exception to replace any tracebacks from + within compiled template code with tracebacks that look like they + came from the template source. + + This must be called within an ``except`` block. + + :param source: For ``TemplateSyntaxError``, the original source if + known. + :return: The original exception with the rewritten traceback. + """ + _, exc_value, tb = sys.exc_info() + exc_value = t.cast(BaseException, exc_value) + tb = t.cast(TracebackType, tb) + + if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated: + exc_value.translated = True + exc_value.source = source + # Remove the old traceback, otherwise the frames from the + # compiler still show up. + exc_value.with_traceback(None) + # Outside of runtime, so the frame isn't executing template + # code, but it still needs to point at the template. + tb = fake_traceback( + exc_value, None, exc_value.filename or "", exc_value.lineno + ) + else: + # Skip the frame for the render function. + tb = tb.tb_next + + stack = [] + + # Build the stack of traceback object, replacing any in template + # code with the source file and line information. + while tb is not None: + # Skip frames decorated with @internalcode. These are internal + # calls that aren't useful in template debugging output. + if tb.tb_frame.f_code in internal_code: + tb = tb.tb_next + continue + + template = tb.tb_frame.f_globals.get("__jinja_template__") + + if template is not None: + lineno = template.get_corresponding_lineno(tb.tb_lineno) + fake_tb = fake_traceback(exc_value, tb, template.filename, lineno) + stack.append(fake_tb) + else: + stack.append(tb) + + tb = tb.tb_next + + tb_next = None + + # Assign tb_next in reverse to avoid circular references. + for tb in reversed(stack): + tb.tb_next = tb_next + tb_next = tb + + return exc_value.with_traceback(tb_next) + + +def fake_traceback( # type: ignore + exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int +) -> TracebackType: + """Produce a new traceback object that looks like it came from the + template source instead of the compiled code. The filename, line + number, and location name will point to the template, and the local + variables will be the current template context. + + :param exc_value: The original exception to be re-raised to create + the new traceback. + :param tb: The original traceback to get the local variables and + code info from. + :param filename: The template filename. + :param lineno: The line number in the template source. + """ + if tb is not None: + # Replace the real locals with the context that would be + # available at that point in the template. + locals = get_template_locals(tb.tb_frame.f_locals) + locals.pop("__jinja_exception__", None) + else: + locals = {} + + globals = { + "__name__": filename, + "__file__": filename, + "__jinja_exception__": exc_value, + } + # Raise an exception at the correct line number. + code: CodeType = compile( + "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec" + ) + + # Build a new code object that points to the template file and + # replaces the location with a block name. + location = "template" + + if tb is not None: + function = tb.tb_frame.f_code.co_name + + if function == "root": + location = "top-level template code" + elif function.startswith("block_"): + location = f"block {function[6:]!r}" + + if sys.version_info >= (3, 8): + code = code.replace(co_name=location) + else: + code = CodeType( + code.co_argcount, + code.co_kwonlyargcount, + code.co_nlocals, + code.co_stacksize, + code.co_flags, + code.co_code, + code.co_consts, + code.co_names, + code.co_varnames, + code.co_filename, + location, + code.co_firstlineno, + code.co_lnotab, + code.co_freevars, + code.co_cellvars, + ) + + # Execute the new code, which is guaranteed to raise, and return + # the new traceback without this frame. + try: + exec(code, globals, locals) + except BaseException: + return sys.exc_info()[2].tb_next # type: ignore + + +def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]: + """Based on the runtime locals, get the context that would be + available at that point in the template. + """ + # Start with the current template context. + ctx: t.Optional[Context] = real_locals.get("context") + + if ctx is not None: + data: t.Dict[str, t.Any] = ctx.get_all().copy() + else: + data = {} + + # Might be in a derived context that only sets local variables + # rather than pushing a context. Local variables follow the scheme + # l_depth_name. Find the highest-depth local that has a value for + # each name. + local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {} + + for name, value in real_locals.items(): + if not name.startswith("l_") or value is missing: + # Not a template variable, or no longer relevant. + continue + + try: + _, depth_str, name = name.split("_", 2) + depth = int(depth_str) + except ValueError: + continue + + cur_depth = local_overrides.get(name, (-1,))[0] + + if cur_depth < depth: + local_overrides[name] = (depth, value) + + # Modify the context with any derived context. + for name, (_, value) in local_overrides.items(): + if value is missing: + data.pop(name, None) + else: + data[name] = value + + return data diff --git a/python_embeded/Lib/site-packages/jinja2/defaults.py b/python_embeded/Lib/site-packages/jinja2/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..638cad3d2d8907330bde56e2b76c9b185c523b45 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/defaults.py @@ -0,0 +1,48 @@ +import typing as t + +from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401 +from .tests import TESTS as DEFAULT_TESTS # noqa: F401 +from .utils import Cycler +from .utils import generate_lorem_ipsum +from .utils import Joiner +from .utils import Namespace + +if t.TYPE_CHECKING: + import typing_extensions as te + +# defaults for the parser / lexer +BLOCK_START_STRING = "{%" +BLOCK_END_STRING = "%}" +VARIABLE_START_STRING = "{{" +VARIABLE_END_STRING = "}}" +COMMENT_START_STRING = "{#" +COMMENT_END_STRING = "#}" +LINE_STATEMENT_PREFIX: t.Optional[str] = None +LINE_COMMENT_PREFIX: t.Optional[str] = None +TRIM_BLOCKS = False +LSTRIP_BLOCKS = False +NEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n" +KEEP_TRAILING_NEWLINE = False + +# default filters, tests and namespace + +DEFAULT_NAMESPACE = { + "range": range, + "dict": dict, + "lipsum": generate_lorem_ipsum, + "cycler": Cycler, + "joiner": Joiner, + "namespace": Namespace, +} + +# default policies +DEFAULT_POLICIES: t.Dict[str, t.Any] = { + "compiler.ascii_str": True, + "urlize.rel": "noopener", + "urlize.target": None, + "urlize.extra_schemes": None, + "truncate.leeway": 5, + "json.dumps_function": None, + "json.dumps_kwargs": {"sort_keys": True}, + "ext.i18n.trimmed": False, +} diff --git a/python_embeded/Lib/site-packages/jinja2/environment.py b/python_embeded/Lib/site-packages/jinja2/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc6e5be87ab8273f6056ddfede07e1be28f1495 --- /dev/null +++ b/python_embeded/Lib/site-packages/jinja2/environment.py @@ -0,0 +1,1672 @@ +"""Classes for managing templates and their runtime and compile time +options. +""" + +import os +import typing +import typing as t +import weakref +from collections import ChainMap +from functools import lru_cache +from functools import partial +from functools import reduce +from types import CodeType + +from markupsafe import Markup + +from . import nodes +from .compiler import CodeGenerator +from .compiler import generate +from .defaults import BLOCK_END_STRING +from .defaults import BLOCK_START_STRING +from .defaults import COMMENT_END_STRING +from .defaults import COMMENT_START_STRING +from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined] +from .defaults import DEFAULT_NAMESPACE +from .defaults import DEFAULT_POLICIES +from .defaults import DEFAULT_TESTS # type: ignore[attr-defined] +from .defaults import KEEP_TRAILING_NEWLINE +from .defaults import LINE_COMMENT_PREFIX +from .defaults import LINE_STATEMENT_PREFIX +from .defaults import LSTRIP_BLOCKS +from .defaults import NEWLINE_SEQUENCE +from .defaults import TRIM_BLOCKS +from .defaults import VARIABLE_END_STRING +from .defaults import VARIABLE_START_STRING +from .exceptions import TemplateNotFound +from .exceptions import TemplateRuntimeError +from .exceptions import TemplatesNotFound +from .exceptions import TemplateSyntaxError +from .exceptions import UndefinedError +from .lexer import get_lexer +from .lexer import Lexer +from .lexer import TokenStream +from .nodes import EvalContext +from .parser import Parser +from .runtime import Context +from .runtime import new_context +from .runtime import Undefined +from .utils import _PassArg +from .utils import concat +from .utils import consume +from .utils import import_string +from .utils import internalcode +from .utils import LRUCache +from .utils import missing + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .bccache import BytecodeCache + from .ext import Extension + from .loaders import BaseLoader + +_env_bound = t.TypeVar("_env_bound", bound="Environment") + + +# for direct template usage we have up to ten living environments +@lru_cache(maxsize=10) +def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound: + """Return a new spontaneous environment. A spontaneous environment + is used for templates created directly rather than through an + existing environment. + + :param cls: Environment class to create. + :param args: Positional arguments passed to environment. + """ + env = cls(*args) + env.shared = True + return env + + +def create_cache( + size: int, +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Return the cache class for the given size.""" + if size == 0: + return None + + if size < 0: + return {} + + return LRUCache(size) # type: ignore + + +def copy_cache( + cache: t.Optional[t.MutableMapping[t.Any, t.Any]], +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Create an empty copy of the given cache.""" + if cache is None: + return None + + if type(cache) is dict: # noqa E721 + return {} + + return LRUCache(cache.capacity) # type: ignore + + +def load_extensions( + environment: "Environment", + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]], +) -> t.Dict[str, "Extension"]: + """Load the extensions from the list and bind it to the environment. + Returns a dict of instantiated extensions. + """ + result = {} + + for extension in extensions: + if isinstance(extension, str): + extension = t.cast(t.Type["Extension"], import_string(extension)) + + result[extension.identifier] = extension(environment) + + return result + + +def _environment_config_check(environment: _env_bound) -> _env_bound: + """Perform a sanity check on the environment.""" + assert issubclass( + environment.undefined, Undefined + ), "'undefined' must be a subclass of 'jinja2.Undefined'." + assert ( + environment.block_start_string + != environment.variable_start_string + != environment.comment_start_string + ), "block, variable and comment start strings must be different." + assert environment.newline_sequence in { + "\r", + "\r\n", + "\n", + }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'." + return environment + + +class Environment: + r"""The core component of Jinja is the `Environment`. It contains + important shared variables like configuration, filters, tests, + globals and others. Instances of this class may be modified if + they are not shared and if no template was loaded so far. + Modifications on environments after the first template was loaded + will lead to surprising effects and undefined behavior. + + Here are the possible initialization parameters: + + `block_start_string` + The string marking the beginning of a block. Defaults to ``'{%'``. + + `block_end_string` + The string marking the end of a block. Defaults to ``'%}'``. + + `variable_start_string` + The string marking the beginning of a print statement. + Defaults to ``'{{'``. + + `variable_end_string` + The string marking the end of a print statement. Defaults to + ``'}}'``. + + `comment_start_string` + The string marking the beginning of a comment. Defaults to ``'{#'``. + + `comment_end_string` + The string marking the end of a comment. Defaults to ``'#}'``. + + `line_statement_prefix` + If given and a string, this will be used as prefix for line based + statements. See also :ref:`line-statements`. + + `line_comment_prefix` + If given and a string, this will be used as prefix for line based + comments. See also :ref:`line-statements`. + + .. versionadded:: 2.2 + + `trim_blocks` + If this is set to ``True`` the first newline after a block is + removed (block, not variable tag!). Defaults to `False`. + + `lstrip_blocks` + If this is set to ``True`` leading spaces and tabs are stripped + from the start of a line to a block. Defaults to `False`. + + `newline_sequence` + The sequence that starts a newline. Must be one of ``'\r'``, + ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a + useful default for Linux and OS X systems as well as web + applications. + + `keep_trailing_newline` + Preserve the trailing newline when rendering templates. + The default is ``False``, which causes a single newline, + if present, to be stripped from the end of the template. + + .. versionadded:: 2.7 + + `extensions` + List of Jinja extensions to use. This can either be import paths + as strings or extension classes. For more information have a + look at :ref:`the extensions documentation `. + + `optimized` + should the optimizer be enabled? Default is ``True``. + + `undefined` + :class:`Undefined` or a subclass of it that is used to represent + undefined values in the template. + + `finalize` + A callable that can be used to process the result of a variable + expression before it is output. For example one can convert + ``None`` implicitly into an empty string here. + + `autoescape` + If set to ``True`` the XML/HTML autoescaping feature is enabled by + default. For more details about autoescaping see + :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also + be a callable that is passed the template name and has to + return ``True`` or ``False`` depending on autoescape should be + enabled by default. + + .. versionchanged:: 2.4 + `autoescape` can now be a function + + `loader` + The template loader for this environment. + + `cache_size` + The size of the cache. Per default this is ``400`` which means + that if more than 400 templates are loaded the loader will clean + out the least recently used template. If the cache size is set to + ``0`` templates are recompiled all the time, if the cache size is + ``-1`` the cache will not be cleaned. + + .. versionchanged:: 2.8 + The cache size was increased to 400 from a low 50. + + `auto_reload` + Some loaders load templates from locations where the template + sources may change (ie: file system or database). If + ``auto_reload`` is set to ``True`` (default) every time a template is + requested the loader checks if the source changed and if yes, it + will reload the template. For higher performance it's possible to + disable that. + + `bytecode_cache` + If set to a bytecode cache object, this object will provide a + cache for the internal Jinja bytecode so that templates don't + have to be parsed if they were not changed. + + See :ref:`bytecode-cache` for more information. + + `enable_async` + If set to true this enables async template execution which + allows using async functions and generators. + """ + + #: if this environment is sandboxed. Modifying this variable won't make + #: the environment sandboxed though. For a real sandboxed environment + #: have a look at jinja2.sandbox. This flag alone controls the code + #: generation by the compiler. + sandboxed = False + + #: True if the environment is just an overlay + overlayed = False + + #: the environment this environment is linked to if it is an overlay + linked_to: t.Optional["Environment"] = None + + #: shared environments have this set to `True`. A shared environment + #: must not be modified + shared = False + + #: the class that is used for code generation. See + #: :class:`~jinja2.compiler.CodeGenerator` for more information. + code_generator_class: t.Type["CodeGenerator"] = CodeGenerator + + concat = "".join + + #: the context class that is used for templates. See + #: :class:`~jinja2.runtime.Context` for more information. + context_class: t.Type[Context] = Context + + template_class: t.Type["Template"] + + def __init__( + self, + block_start_string: str = BLOCK_START_STRING, + block_end_string: str = BLOCK_END_STRING, + variable_start_string: str = VARIABLE_START_STRING, + variable_end_string: str = VARIABLE_END_STRING, + comment_start_string: str = COMMENT_START_STRING, + comment_end_string: str = COMMENT_END_STRING, + line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, + line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, + trim_blocks: bool = TRIM_BLOCKS, + lstrip_blocks: bool = LSTRIP_BLOCKS, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, + keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), + optimized: bool = True, + undefined: t.Type[Undefined] = Undefined, + finalize: t.Optional[t.Callable[..., t.Any]] = None, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, + loader: t.Optional["BaseLoader"] = None, + cache_size: int = 400, + auto_reload: bool = True, + bytecode_cache: t.Optional["BytecodeCache"] = None, + enable_async: bool = False, + ): + # !!Important notice!! + # The constructor accepts quite a few arguments that should be + # passed by keyword rather than position. However it's important to + # not change the order of arguments because it's used at least + # internally in those cases: + # - spontaneous environments (i18n extension and Template) + # - unittests + # If parameter changes are required only add parameters at the end + # and don't change the arguments (or the defaults!) of the arguments + # existing already. + + # lexer / parser information + self.block_start_string = block_start_string + self.block_end_string = block_end_string + self.variable_start_string = variable_start_string + self.variable_end_string = variable_end_string + self.comment_start_string = comment_start_string + self.comment_end_string = comment_end_string + self.line_statement_prefix = line_statement_prefix + self.line_comment_prefix = line_comment_prefix + self.trim_blocks = trim_blocks + self.lstrip_blocks = lstrip_blocks + self.newline_sequence = newline_sequence + self.keep_trailing_newline = keep_trailing_newline + + # runtime information + self.undefined: t.Type[Undefined] = undefined + self.optimized = optimized + self.finalize = finalize + self.autoescape = autoescape + + # defaults + self.filters = DEFAULT_FILTERS.copy() + self.tests = DEFAULT_TESTS.copy() + self.globals = DEFAULT_NAMESPACE.copy() + + # set the loader provided + self.loader = loader + self.cache = create_cache(cache_size) + self.bytecode_cache = bytecode_cache + self.auto_reload = auto_reload + + # configurable policies + self.policies = DEFAULT_POLICIES.copy() + + # load extensions + self.extensions = load_extensions(self, extensions) + + self.is_async = enable_async + _environment_config_check(self) + + def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None: + """Adds an extension after the environment was created. + + .. versionadded:: 2.5 + """ + self.extensions.update(load_extensions(self, [extension])) + + def extend(self, **attributes: t.Any) -> None: + """Add the items to the instance of the environment if they do not exist + yet. This is used by :ref:`extensions ` to register + callbacks and configuration values without breaking inheritance. + """ + for key, value in attributes.items(): + if not hasattr(self, key): + setattr(self, key, value) + + def overlay( + self, + block_start_string: str = missing, + block_end_string: str = missing, + variable_start_string: str = missing, + variable_end_string: str = missing, + comment_start_string: str = missing, + comment_end_string: str = missing, + line_statement_prefix: t.Optional[str] = missing, + line_comment_prefix: t.Optional[str] = missing, + trim_blocks: bool = missing, + lstrip_blocks: bool = missing, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing, + keep_trailing_newline: bool = missing, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing, + optimized: bool = missing, + undefined: t.Type[Undefined] = missing, + finalize: t.Optional[t.Callable[..., t.Any]] = missing, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing, + loader: t.Optional["BaseLoader"] = missing, + cache_size: int = missing, + auto_reload: bool = missing, + bytecode_cache: t.Optional["BytecodeCache"] = missing, + enable_async: bool = missing, + ) -> "te.Self": + """Create a new overlay environment that shares all the data with the + current environment except for cache and the overridden attributes. + Extensions cannot be removed for an overlayed environment. An overlayed + environment automatically gets all the extensions of the environment it + is linked to plus optional extra extensions. + + Creating overlays should happen after the initial environment was set + up completely. Not all attributes are truly linked, some are just + copied over so modifications on the original environment may not shine + through. + + .. versionchanged:: 3.1.5 + ``enable_async`` is applied correctly. + + .. versionchanged:: 3.1.2 + Added the ``newline_sequence``, ``keep_trailing_newline``, + and ``enable_async`` parameters to match ``__init__``. + """ + args = dict(locals()) + del args["self"], args["cache_size"], args["extensions"], args["enable_async"] + + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.overlayed = True + rv.linked_to = self + + for key, value in args.items(): + if value is not missing: + setattr(rv, key, value) + + if cache_size is not missing: + rv.cache = create_cache(cache_size) + else: + rv.cache = copy_cache(self.cache) + + rv.extensions = {} + for key, value in self.extensions.items(): + rv.extensions[key] = value.bind(rv) + if extensions is not missing: + rv.extensions.update(load_extensions(rv, extensions)) + + if enable_async is not missing: + rv.is_async = enable_async + + return _environment_config_check(rv) + + @property + def lexer(self) -> Lexer: + """The lexer for this environment.""" + return get_lexer(self) + + def iter_extensions(self) -> t.Iterator["Extension"]: + """Iterates over the extensions by priority.""" + return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) + + def getitem( + self, obj: t.Any, argument: t.Union[str, t.Any] + ) -> t.Union[t.Any, Undefined]: + """Get an item or attribute of an object but prefer the item.""" + try: + return obj[argument] + except (AttributeError, TypeError, LookupError): + if isinstance(argument, str): + try: + attr = str(argument) + except Exception: + pass + else: + try: + return getattr(obj, attr) + except AttributeError: + pass + return self.undefined(obj=obj, name=argument) + + def getattr(self, obj: t.Any, attribute: str) -> t.Any: + """Get an item or attribute of an object but prefer the attribute. + Unlike :meth:`getitem` the attribute *must* be a string. + """ + try: + return getattr(obj, attribute) + except AttributeError: + pass + try: + return obj[attribute] + except (TypeError, LookupError, AttributeError): + return self.undefined(obj=obj, name=attribute) + + def _filter_test_common( + self, + name: t.Union[str, Undefined], + value: t.Any, + args: t.Optional[t.Sequence[t.Any]], + kwargs: t.Optional[t.Mapping[str, t.Any]], + context: t.Optional[Context], + eval_ctx: t.Optional[EvalContext], + is_filter: bool, + ) -> t.Any: + if is_filter: + env_map = self.filters + type_name = "filter" + else: + env_map = self.tests + type_name = "test" + + func = env_map.get(name) # type: ignore + + if func is None: + msg = f"No {type_name} named {name!r}." + + if isinstance(name, Undefined): + try: + name._fail_with_undefined_error() + except Exception as e: + msg = f"{msg} ({e}; did you forget to quote the callable name?)" + + raise TemplateRuntimeError(msg) + + args = [value, *(args if args is not None else ())] + kwargs = kwargs if kwargs is not None else {} + pass_arg = _PassArg.from_obj(func) + + if pass_arg is _PassArg.context: + if context is None: + raise TemplateRuntimeError( + f"Attempted to invoke a context {type_name} without context." + ) + + args.insert(0, context) + elif pass_arg is _PassArg.eval_context: + if eval_ctx is None: + if context is not None: + eval_ctx = context.eval_ctx + else: + eval_ctx = EvalContext(self) + + args.insert(0, eval_ctx) + elif pass_arg is _PassArg.environment: + args.insert(0, self) + + return func(*args, **kwargs) + + def call_filter( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a filter on a value the same way the compiler does. + + This might return a coroutine if the filter is running from an + environment in async mode and the filter supports async + execution. It's your responsibility to await this if needed. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, True + ) + + def call_test( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a test on a value the same way the compiler does. + + This might return a coroutine if the test is running from an + environment in async mode and the test supports async execution. + It's your responsibility to await this if needed. + + .. versionchanged:: 3.0 + Tests support ``@pass_context``, etc. decorators. Added + the ``context`` and ``eval_ctx`` parameters. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, False + ) + + @internalcode + def parse( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> nodes.Template: + """Parse the sourcecode and return the abstract syntax tree. This + tree of nodes is used by the compiler to convert the template into + executable source- or bytecode. This is useful for debugging or to + extract information from templates. + + If you are :ref:`developing Jinja extensions ` + this gives you a good overview of the node tree generated. + """ + try: + return self._parse(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def _parse( + self, source: str, name: t.Optional[str], filename: t.Optional[str] + ) -> nodes.Template: + """Internal parsing function used by `parse` and `compile`.""" + return Parser(self, source, name, filename).parse() + + def lex( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> t.Iterator[t.Tuple[int, str, str]]: + """Lex the given sourcecode and return a generator that yields + tokens as tuples in the form ``(lineno, token_type, value)``. + This can be useful for :ref:`extension development ` + and debugging templates. + + This does not perform preprocessing. If you want the preprocessing + of the extensions to be applied you have to filter source through + the :meth:`preprocess` method. + """ + source = str(source) + try: + return self.lexer.tokeniter(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def preprocess( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> str: + """Preprocesses the source with all extensions. This is automatically + called for all parsing and compiling methods but *not* for :meth:`lex` + because there you usually only want the actual source tokenized. + """ + return reduce( + lambda s, e: e.preprocess(s, name, filename), + self.iter_extensions(), + str(source), + ) + + def _tokenize( + self, + source: str, + name: t.Optional[str], + filename: t.Optional[str] = None, + state: t.Optional[str] = None, + ) -> TokenStream: + """Called by the parser to do the preprocessing and filtering + for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. + """ + source = self.preprocess(source, name, filename) + stream = self.lexer.tokenize(source, name, filename, state) + + for ext in self.iter_extensions(): + stream = ext.filter_stream(stream) # type: ignore + + if not isinstance(stream, TokenStream): + stream = TokenStream(stream, name, filename) + + return stream + + def _generate( + self, + source: nodes.Template, + name: t.Optional[str], + filename: t.Optional[str], + defer_init: bool = False, + ) -> str: + """Internal hook that can be overridden to hook a different generate + method in. + + .. versionadded:: 2.5 + """ + return generate( # type: ignore + source, + self, + name, + filename, + defer_init=defer_init, + optimized=self.optimized, + ) + + def _compile(self, source: str, filename: str) -> CodeType: + """Internal hook that can be overridden to hook a different compile + method in. + + .. versionadded:: 2.5 + """ + return compile(source, filename, "exec") + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[False]" = False, + defer_init: bool = False, + ) -> CodeType: ... + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[True]" = ..., + defer_init: bool = False, + ) -> str: ... + + @internalcode + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: bool = False, + defer_init: bool = False, + ) -> t.Union[str, CodeType]: + """Compile a node or template source code. The `name` parameter is + the load name of the template after it was joined using + :meth:`join_path` if necessary, not the filename on the file system. + the `filename` parameter is the estimated filename of the template on + the file system. If the template came from a database or memory this + can be omitted. + + The return value of this method is a python code object. If the `raw` + parameter is `True` the return value will be a string with python + code equivalent to the bytecode returned otherwise. This method is + mainly used internally. + + `defer_init` is use internally to aid the module code generator. This + causes the generated code to be able to import without the global + environment variable to be set. + + .. versionadded:: 2.4 + `defer_init` parameter added. + """ + source_hint = None + try: + if isinstance(source, str): + source_hint = source + source = self._parse(source, name, filename) + source = self._generate(source, name, filename, defer_init=defer_init) + if raw: + return source + if filename is None: + filename = "