Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+4
- .venv-deploy/lib/python3.14/site-packages/idna-3.18.dist-info/WHEELAdded+4
- .venv-deploy/lib/python3.14/site-packages/idna-3.18.dist-info/entry_points.txtAdded+3
- .venv-deploy/lib/python3.14/site-packages/idna-3.18.dist-info/licenses/LICENSE.mdAdded+31
- .venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/INSTALLERAdded+1
- .venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/METADATAAdded+112
- .venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/RECORDAdded+52
- .venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/WHEELAdded+4
- .venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/licenses/LICENSEAdded+3
- .venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/licenses/LICENSE.APACHEAdded+177
- .venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/licenses/LICENSE.BSDAdded+23
- .venv-deploy/lib/python3.14/site-packages/packaging/__init__.pyAdded+15
- .venv-deploy/lib/python3.14/site-packages/packaging/_elffile.pyAdded+108
- .venv-deploy/lib/python3.14/site-packages/packaging/_manylinux.pyAdded+278
- .venv-deploy/lib/python3.14/site-packages/packaging/_musllinux.pyAdded+88
- .venv-deploy/lib/python3.14/site-packages/packaging/_parser.pyAdded+418
- .venv-deploy/lib/python3.14/site-packages/packaging/_ranges.pyAdded+836
- .venv-deploy/lib/python3.14/site-packages/packaging/_structures.pyAdded+33
- .venv-deploy/lib/python3.14/site-packages/packaging/_tokenizer.pyAdded+200
- .venv-deploy/lib/python3.14/site-packages/packaging/dependency_groups.pyAdded+335
- .venv-deploy/lib/python3.14/site-packages/packaging/direct_url.pyAdded+349
- .venv-deploy/lib/python3.14/site-packages/packaging/errors.pyAdded+94
- .venv-deploy/lib/python3.14/site-packages/packaging/licenses/__init__.pyAdded+198
- .venv-deploy/lib/python3.14/site-packages/packaging/licenses/_spdx.pyAdded+799
- .venv-deploy/lib/python3.14/site-packages/packaging/markers.pyAdded+576
- .venv-deploy/lib/python3.14/site-packages/packaging/metadata.pyAdded+1054
- .venv-deploy/lib/python3.14/site-packages/packaging/py.typedAdded
- .venv-deploy/lib/python3.14/site-packages/packaging/pylock.pyAdded+943
- .venv-deploy/lib/python3.14/site-packages/packaging/ranges.pyAdded+2067
- .venv-deploy/lib/python3.14/site-packages/packaging/requirements.pyAdded+192
- .venv-deploy/lib/python3.14/site-packages/packaging/specifiers.pyAdded+1457
- .venv-deploy/lib/python3.14/site-packages/packaging/tags.pyAdded+1053
- .venv-deploy/lib/python3.14/site-packages/packaging/utils.pyAdded+370
- .venv-deploy/lib/python3.14/site-packages/packaging/version.pyAdded+1252
- .venv-deploy/lib/python3.14/site-packages/pip/__init__.pyAdded+13
- .venv-deploy/lib/python3.14/site-packages/pip/__main__.pyAdded+24
- .venv-deploy/lib/python3.14/site-packages/pip/__pip-runner__.pyAdded+50
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/__init__.pyAdded+18
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/build_env.pyAdded+606
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cache.pyAdded+291
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/__init__.pyAdded+3
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/autocompletion.pyAdded+184
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/base_command.pyAdded+264
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/cmdoptions.pyAdded+1298
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/command_context.pyAdded+28
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/index_command.pyAdded+212
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/main.pyAdded+85
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/main_parser.pyAdded+136
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/parser.pyAdded+358
- .venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/progress_bars.pyAdded+153
38 unmodified lines3940414243444538 unmodified linesdocs/retro/screenshots/04-scorecard.png filter=lfs diff=lfs merge=lfs -textdocs/retro/screenshots/05-retrieved-standards.png filter=lfs diff=lfs merge=lfs -textdocs/retro/screenshots/06-audit-trail.png filter=lfs diff=lfs merge=lfs -text.venv-deploy/lib/python3.14/site-packages/pip/_vendor/distlib/t64-arm.exe filter=lfs diff=lfs merge=lfs -text.venv-deploy/lib/python3.14/site-packages/pip/_vendor/distlib/t64.exe filter=lfs diff=lfs merge=lfs -text.venv-deploy/lib/python3.14/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text.venv-deploy/lib/python3.14/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs merge=lfs -text1234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any123[console_scripts]idna=idna.cli:main
12345678910111213141516171819202122232425262728293031BSD 3-Clause License
Copyright (c) 2013-2026, Kim Davies and contributors.All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:
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 NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITEDTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112Metadata-Version: 2.4Name: packagingVersion: 26.3Summary: Core utilities for Python packagesAuthor-email: Donald Stufft <donald@stufft.io>Requires-Python: >=3.9Description-Content-Type: text/x-rstLicense-Expression: Apache-2.0 OR BSD-2-ClauseClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: 3.15Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Python :: Free Threading :: 4 - ResilientClassifier: Typing :: TypedLicense-File: LICENSELicense-File: LICENSE.APACHELicense-File: LICENSE.BSDProject-URL: Documentation, https://packaging.pypa.io/Project-URL: Source, https://github.com/pypa/packaging
packaging=========
.. start-intro
Reusable core utilities for various Python Packaging`interoperability specifications <https://packaging.python.org/specifications/>`_.
This library provides utilities that implement the interoperabilityspecifications which have clearly one correct behaviour (eg: :pep:`440`)or benefit greatly from having a single shared implementation (eg: :pep:`425`).
.. end-intro
The ``packaging`` project includes the following: version handling, specifiers,markers, requirements, tags, metadata, lockfiles, utilities.
Documentation-------------
The `documentation`_ provides information and the API for the following:
- Version Handling- Specifiers- Markers- Licenses- Requirements- Metadata- Tags- Lockfiles (pylock)- Direct URL helpers- Dependency groups- Errors- Utilities
Installation------------
Use ``pip`` to install these utilities::
pip install packaging
The ``packaging`` library uses calendar-based versioning (``YY.N``).
Discussion----------
If you run into bugs, you can file them in our `issue tracker`_.
You can also join discussions on `GitHub Discussions`_ to ask questions or get involved.
.. _`documentation`: https://packaging.pypa.io/.. _`issue tracker`: https://github.com/pypa/packaging/issues.. _`GitHub Discussions`: https://github.com/pypa/packaging/discussions
Code of Conduct---------------
Everyone interacting in the packaging project's codebases, issue trackers, chatrooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
Contributing------------
The ``CONTRIBUTING.rst`` file outlines how to contribute to this project aswell as how to report a potential security issue. The documentation for thisproject also covers information about `project development`_ and `security`_.
.. _`project development`: https://packaging.pypa.io/en/latest/development/.. _`security`: https://packaging.pypa.io/en/latest/security/
Project History---------------
Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ forrecent changes and project history.
.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152packaging-26.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
packaging-26.3.dist-info/METADATA,sha256=cP24n8TUqaBDv3NyuJcrzIg_3f80q1Xpz4DXOHU4R2M,3544
packaging-26.3.dist-info/RECORD,,
packaging-26.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
packaging-26.3.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
packaging-26.3.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
packaging-26.3.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
packaging/__init__.py,sha256=bnWM3QAossrXTHObmtycnwbwVJMjBigLh4v-WdOSGbU,494
packaging/__pycache__/__init__.cpython-314.pyc,,
packaging/__pycache__/_elffile.cpython-314.pyc,,
packaging/__pycache__/_manylinux.cpython-314.pyc,,
packaging/__pycache__/_musllinux.cpython-314.pyc,,
packaging/__pycache__/_parser.cpython-314.pyc,,
packaging/__pycache__/_ranges.cpython-314.pyc,,
packaging/__pycache__/_structures.cpython-314.pyc,,
packaging/__pycache__/_tokenizer.cpython-314.pyc,,
packaging/__pycache__/dependency_groups.cpython-314.pyc,,
packaging/__pycache__/direct_url.cpython-314.pyc,,
packaging/__pycache__/errors.cpython-314.pyc,,
packaging/__pycache__/markers.cpython-314.pyc,,
packaging/__pycache__/metadata.cpython-314.pyc,,
packaging/__pycache__/pylock.cpython-314.pyc,,
packaging/__pycache__/ranges.cpython-314.pyc,,
packaging/__pycache__/requirements.cpython-314.pyc,,
packaging/__pycache__/specifiers.cpython-314.pyc,,
packaging/__pycache__/tags.cpython-314.pyc,,
packaging/__pycache__/utils.cpython-314.pyc,,
packaging/__pycache__/version.cpython-314.pyc,,
packaging/_elffile.py,sha256=HwJfVMVz8ahXQMT72QjMHR-wwXfBQ3fr9fCdbNU2h4A,3236
packaging/_manylinux.py,sha256=W26EMkxCU4q0zbFI4kMP26NvBEJ7Dv2lW-oIOjX6YTY,10000
packaging/_musllinux.py,sha256=Ayj7gnsRcMd99MEH1Jvo3403JiEDSQph6Kytii-crf8,2774
packaging/_parser.py,sha256=iKNIEVIJMnSX5FO2NeXbCZ_VkvkzXXEMcxOynNswxQw,12639
packaging/_ranges.py,sha256=t7WV8uaSrrNpfFRbhcJMu8tFUvKtxtkFmqgtCHfoFrc,30850
packaging/_structures.py,sha256=60jRbF78p8z5MKnNd6cAprgOadCJHV0DlmUmRBqFZcs,1109
packaging/_tokenizer.py,sha256=zCXlfA1WTInhUHNHHW4cJkKZypRvsXwOHkr1TvdxPuY,5573
packaging/dependency_groups.py,sha256=UwnMVkyjAi37WUgW6dWTuwnN80IIwfuMXsmvtsZwJ4w,11224
packaging/direct_url.py,sha256=hDuqldBMu0kojenZ_XfulG6GLLYDEj5-RqaeFx-n0Gs,11645
packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680
packaging/licenses/__init__.py,sha256=WQ0S7uc92-xTtOnuW_xk2cs6rLSUDo68uiYHV85WdAs,7859
packaging/licenses/__pycache__/__init__.cpython-314.pyc,,
packaging/licenses/__pycache__/_spdx.cpython-314.pyc,,
packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
packaging/markers.py,sha256=bL6GDTXZjStZnn8Oxz_qsSTgFXEbML6QReZ4ySlA2cw,20554
packaging/metadata.py,sha256=k0FJ9CClRJ5vN2qmHW8moII-uCzHxqHIzeWqe-Q9D2M,42059
packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
packaging/pylock.py,sha256=G84Kn-Y-Qrh-jO0F2icrrxamiqcEs3GEBeJzWmESRnw,35232
packaging/ranges.py,sha256=tHgc6RPl3_ngeQbyBYXFTDAo4ff_VjQYKOedUi3b-rY,83054
packaging/requirements.py,sha256=RZR26yEH_jDmsTEAUaW9tEx9O3944Oh7raJoKCy6YvU,7040
packaging/specifiers.py,sha256=ZhrTHd9F_7hh0mJnNPTj1mlmApuP23lYa7EFgl2NnVk,52798
packaging/tags.py,sha256=DnF6CCp5Yg15zwMhtCDfFVk8SRb82gPCfLnYLgfvXW4,38302
packaging/utils.py,sha256=oTdCzZmU7spa37AknRJkCMR4Am6x9Iy5evvy_p8o7MY,12215
packaging/version.py,sha256=VYsvtQ_RmMZgpMCC-WuJGcVlkRtrS24H80trYMB0vpc,390401234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any123This software is made available under the terms of *either* of the licensesfound in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is madeunder the terms of *both* these licenses.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
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 CONDITIONS1234567891011121314151617181920212223Copyright (c) Donald Stufft and individual contributors.All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, 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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
__title__ = "packaging"__summary__ = "Core utilities for Python packages"__uri__ = "https://github.com/pypa/packaging"
__version__ = "26.3"
__author__ = "Donald Stufft and individual contributors"__email__ = "donald@stufft.io"
__license__ = "BSD-2-Clause or Apache-2.0"__copyright__ = f"2014 {__author__}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""ELF file parser.
This provides a class ``ELFFile`` that parses an ELF executable in a similarinterface to ``ZipFile``. Only the read interface is implemented.
ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html"""
from __future__ import annotations
import enumimport osimport structfrom typing import IO
class ELFInvalid(ValueError): pass
class EIClass(enum.IntEnum): C32 = 1 C64 = 2
class EIData(enum.IntEnum): Lsb = 1 Msb = 2
class EMachine(enum.IntEnum): I386 = 3 S390 = 22 Arm = 40 X8664 = 62 AArch64 = 183
class ELFFile: """ Representation of an ELF executable. """
def __init__(self, f: IO[bytes]) -> None: self._f = f
try: ident = self._read("16B") except struct.error as e: raise ELFInvalid("unable to parse identification") from e magic = bytes(ident[:4]) if magic != b"\x7fELF": raise ELFInvalid(f"invalid magic: {magic!r}")
self.capacity = ident[4] # Format for program header (bitness). self.encoding = ident[5] # Data structure encoding (endianness).
try: # e_fmt: Format for the ELF header. # p_fmt: Format for a program header. # p_idx: Indexes to find p_type, p_offset, and p_filesz. e_fmt, self._p_fmt, self._p_idx = { (1, 1): ("<HHIIIIIHHH", "<IIIIIIII", (0, 1, 4)), # 32-bit LSB. (1, 2): (">HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. (2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB. (2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. }[(self.capacity, self.encoding)] except KeyError as e: raise ELFInvalid( f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})" ) from e
try: ( _, self.machine, # Architecture type. _, _, self._e_phoff, # Offset of program header. _, self.flags, # Processor-specific flags. _, self._e_phentsize, # Size of a program header entry. self._e_phnum, # Number of program headers. ) = self._read(e_fmt) except struct.error as e: raise ELFInvalid("unable to parse machine and section information") from e
def _read(self, fmt: str) -> tuple[int, ...]: return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
@property def interpreter(self) -> str | None: """ The path recorded in the ``PT_INTERP`` section header. """ for index in range(self._e_phnum): self._f.seek(self._e_phoff + self._e_phentsize * index) try: data = self._read(self._p_fmt) except struct.error: continue if data[self._p_idx[0]] != 3: # Not PT_INTERP. continue self._f.seek(data[self._p_idx[1]]) return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278from __future__ import annotations
import collectionsimport contextlibimport functoolsimport osimport reimport sysimport warningsfrom typing import TYPE_CHECKING, NamedTuple
from ._elffile import EIClass, EIData, ELFFile, EMachine
if TYPE_CHECKING: import types from collections.abc import Generator, Iterator, Sequence
EF_ARM_ABIMASK = 0xFF000000EF_ARM_ABI_VER5 = 0x05000000EF_ARM_ABI_FLOAT_HARD = 0x00000400
_ALLOWED_ARCHS = { "x86_64", "aarch64", "ppc64", "ppc64le", "s390x", "loongarch64", "riscv64",}
@contextlib.contextmanagerdef _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: try: with open(path, "rb") as f: yield ELFFile(f) except (OSError, TypeError, ValueError): yield None
def _is_linux_armhf(executable: str) -> bool: # hard-float ABI can be detected from the ELF header of the running # process # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf with _parse_elf(executable) as f: return ( f is not None and f.capacity == EIClass.C32 and f.encoding == EIData.Lsb and f.machine == EMachine.Arm and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD )
def _is_linux_i686(executable: str) -> bool: with _parse_elf(executable) as f: return ( f is not None and f.capacity == EIClass.C32 and f.encoding == EIData.Lsb and f.machine == EMachine.I386 )
def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: if "armv7l" in archs: return _is_linux_armhf(executable) if "i686" in archs: return _is_linux_i686(executable) return any(arch in _ALLOWED_ARCHS for arch in archs)
# If glibc ever changes its major version, we need to know what the last# minor version was, so we can build the complete list of all versions.# For now, guess what the highest minor version might be, assume it will# be 50 for testing. Once this actually happens, update the dictionary# with the actual value._LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
class _GLibCVersion(NamedTuple): major: int minor: int
def _glibc_version_string_confstr() -> str | None: """ Primary implementation of glibc_version_string using os.confstr. """ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platform module. # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 try: # Should be a string like "glibc 2.17". version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") assert version_string is not None _, version = version_string.rsplit() except (AssertionError, AttributeError, OSError, ValueError): # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... return None return version
def _glibc_version_string_ctypes() -> str | None: """ Fallback implementation of glibc_version_string using ctypes. """ try: import ctypes # noqa: PLC0415 except ImportError: return None
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure out # which libc our process is actually using. # # We must also handle the special case where the executable is not a # dynamically linked executable. This can occur when using musl libc, # for example. In this situation, dlopen() will error, leading to an # OSError. Interestingly, at least in the case of musl, there is no # errno set on the OSError. The single string argument used to construct # OSError comes from libc itself and is therefore not portable to # hard code here. In any case, failure to call dlopen() means we # can proceed, so we bail on our attempt. try: process_namespace = ctypes.CDLL(None) except OSError: return None
try: gnu_get_libc_version = process_namespace.gnu_get_libc_version except AttributeError: # Symbol doesn't exist -> therefore, we are not linked to # glibc. return None
# Call gnu_get_libc_version, which returns a string like "2.5". gnu_get_libc_version.restype = ctypes.c_char_p # A c_char_p restype comes back as bytes, so decode to text. version_str: str | bytes = gnu_get_libc_version() if isinstance(version_str, bytes): version_str = version_str.decode("ascii")
return version_str
def _glibc_version_string() -> str | None: """Returns glibc version string, or None if not using glibc.""" return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
def _parse_glibc_version(version_str: str) -> _GLibCVersion: """Parse glibc version.
We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked versions of glibc (e.g. Linaro's version of glibc uses version strings like "2.20-2014.11"). See gh-3588. """ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str) if not m: warnings.warn( f"Expected glibc version with 2 components major.minor, got: {version_str}", RuntimeWarning, stacklevel=2, ) return _GLibCVersion(-1, -1) return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
@functools.lru_cachedef _get_glibc_version() -> _GLibCVersion: version_str = _glibc_version_string() if version_str is None: return _GLibCVersion(-1, -1) return _parse_glibc_version(version_str)
# From PEP 513, PEP 600@functools.lru_cache(maxsize=1)def _get_manylinux_module() -> types.ModuleType | None: """Return the ``_manylinux`` C extension module, or None if unavailable.
The result is cached for the lifetime of the process, since the presence of the module does not change while running. """ try: return __import__("_manylinux") except ImportError: return None
def _is_compatible(arch: str, version: _GLibCVersion) -> bool: sys_glibc = _get_glibc_version() if sys_glibc < version: return False # Check for presence of _manylinux module. manylinux_mod = _get_manylinux_module() if manylinux_mod is None: return True if hasattr(manylinux_mod, "manylinux_compatible"): result = manylinux_mod.manylinux_compatible(version[0], version[1], arch) if result is not None: return bool(result) return True if version == _GLibCVersion(2, 5) and hasattr( manylinux_mod, "manylinux1_compatible" ): return bool(manylinux_mod.manylinux1_compatible) if version == _GLibCVersion(2, 12) and hasattr( manylinux_mod, "manylinux2010_compatible" ): return bool(manylinux_mod.manylinux2010_compatible) if version == _GLibCVersion(2, 17) and hasattr( manylinux_mod, "manylinux2014_compatible" ): return bool(manylinux_mod.manylinux2014_compatible) return True
_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { # CentOS 7 w/ glibc 2.17 (PEP 599) _GLibCVersion(2, 17): "manylinux2014", # CentOS 6 w/ glibc 2.12 (PEP 571) _GLibCVersion(2, 12): "manylinux2010", # CentOS 5 w/ glibc 2.5 (PEP 513) _GLibCVersion(2, 5): "manylinux1",}
def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate manylinux tags compatible to the current platform.
:param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be manylinux-compatible.
:returns: An iterator of compatible manylinux tags. """ if not _have_compatible_abi(sys.executable, archs): return # Oldest glibc to be supported regardless of architecture is (2, 17). too_old_glibc2 = _GLibCVersion(2, 16) if set(archs) & {"x86_64", "i686"}: # On x86/i686 also oldest glibc to be supported is (2, 5). too_old_glibc2 = _GLibCVersion(2, 4) current_glibc = _GLibCVersion(*_get_glibc_version()) glibc_max_list = [current_glibc] # We can assume compatibility across glibc major versions. # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 # # Build a list of maximum glibc versions so that we can # output the canonical list of all glibc from current_glibc # down to too_old_glibc2, including all intermediary versions. for glibc_major in range(current_glibc.major - 1, 1, -1): glibc_minor = _LAST_GLIBC_MINOR[glibc_major] glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) for arch in archs: for glibc_max in glibc_max_list: if glibc_max.major == too_old_glibc2.major: min_minor = too_old_glibc2.minor else: # For other glibc major versions oldest supported is (x, 0). min_minor = -1 for glibc_minor in range(glibc_max.minor, min_minor, -1): glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) if _is_compatible(arch, glibc_version): yield "manylinux_{}_{}_{}".format(*glibc_version, arch)
# Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version): yield f"{legacy_tag}_{arch}"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""PEP 656 support.
This module implements logic to detect if the currently running Python islinked against musl, and what musl version is used."""
from __future__ import annotations
import functoolsimport reimport subprocessimport sysfrom typing import TYPE_CHECKING, NamedTuple
from ._elffile import ELFFile
if TYPE_CHECKING: from collections.abc import Iterator, Sequence
class _MuslVersion(NamedTuple): major: int minor: int
def _parse_musl_version(output: str) -> _MuslVersion | None: lines = [n for n in (n.strip() for n in output.splitlines()) if n] if len(lines) < 2 or lines[0][:4] != "musl": return None m = re.match(r"Version (\d+)\.(\d+)", lines[1]) if not m: return None return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))
@functools.lru_cachedef _get_musl_version(executable: str) -> _MuslVersion | None: """Detect currently-running musl runtime version.
This is done by checking the specified executable's dynamic linking information, and invoking the loader to parse its output for a version string. If the loader is musl, the output would be something like::
musl libc (x86_64) Version 1.2.2 Dynamic Program Loader """ try: with open(executable, "rb") as f: ld = ELFFile(f).interpreter except (OSError, TypeError, ValueError): return None if ld is None or "musl" not in ld: return None proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True) return _parse_musl_version(proc.stderr)
def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate musllinux tags compatible to the current platform.
:param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be musllinux-compatible.
:returns: An iterator of compatible musllinux tags. """ sys_musl = _get_musl_version(sys.executable) if sys_musl is None: # Python not dynamically linked against musl. return for arch in archs: for minor in range(sys_musl.minor, -1, -1): yield f"musllinux_{sys_musl.major}_{minor}_{arch}"
if __name__ == "__main__": # pragma: no cover import sysconfig
plat = sysconfig.get_platform() assert plat.startswith("linux-"), "not linux"
print("plat:", plat) print("musl:", _get_musl_version(sys.executable)) print("tags:", end=" ") for t in platform_tags([re.sub(r"[.-]", "_", plat.split("-", 1)[-1])]): print(t, end="\n ")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418"""Handwritten parser of dependency specifiers.
The docstring for each __parse_* function contains EBNF-inspired grammar representingthe implementation."""
from __future__ import annotations
import astfrom collections.abc import Sequencefrom typing import Literal, NamedTuple, Union
from ._tokenizer import DEFAULT_RULES, ParserSyntaxError, Tokenizer
class Node: __slots__ = ("value",)
def __init__(self, value: str) -> None: self.value = value
def __str__(self) -> str: return self.value
def __repr__(self) -> str: return f"<{self.__class__.__name__}({self.value!r})>"
def serialize(self) -> str: raise NotImplementedError
def __getstate__(self) -> str: # Return just the value string for compactness and stability. return self.value
def _restore_value(self, value: object) -> None: if not isinstance(value, str): raise TypeError( f"Cannot restore {self.__class__.__name__} value from {value!r}" ) self.value = value
def __setstate__(self, state: object) -> None: if isinstance(state, str): # New format (26.2+): just the value string. self._restore_value(state) return if isinstance(state, tuple) and len(state) == 2: # Old format (packaging <= 26.0, __slots__): (None, {slot: value}). _, slot_dict = state if isinstance(slot_dict, dict) and "value" in slot_dict: self._restore_value(slot_dict["value"]) return if isinstance(state, dict) and "value" in state: # Old format (packaging <= 25.0, no __slots__): plain __dict__. self._restore_value(state["value"]) return raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}")
class Variable(Node): __slots__ = ()
def serialize(self) -> str: return str(self)
class Value(Node): __slots__ = ()
def serialize(self) -> str: value = str(self) if '"' not in value: return f'"{value}"' if "'" not in value: return f"'{value}'" raise ValueError( "Cannot serialize marker value containing both quote characters" )
class Op(Node): __slots__ = ()
def serialize(self) -> str: return str(self)
MarkerLogical = Literal["and", "or"]MarkerVar = Union[Variable, Value]MarkerItem = tuple[MarkerVar, Op, MarkerVar]MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]MarkerList = list[Union["MarkerList", MarkerAtom, MarkerLogical]]
class ParsedRequirement(NamedTuple): name: str url: str extras: list[str] specifier: str marker: MarkerList | None
# --------------------------------------------------------------------------------------# Recursive descent parser for dependency specifier# --------------------------------------------------------------------------------------def parse_requirement(source: str) -> ParsedRequirement: return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: """ requirement = WS? IDENTIFIER WS? extras WS? requirement_details """ tokenizer.consume("WS")
name_token = tokenizer.expect( "IDENTIFIER", expected="package name at the start of dependency specifier" ) name = name_token.text tokenizer.consume("WS")
extras = _parse_extras(tokenizer) tokenizer.consume("WS")
url, specifier, marker = _parse_requirement_details(tokenizer) tokenizer.expect("END", expected="end of dependency specifier")
return ParsedRequirement(name, url, extras, specifier, marker)
def _parse_requirement_details( tokenizer: Tokenizer,) -> tuple[str, str, MarkerList | None]: """ requirement_details = AT URL (WS requirement_marker?)? | specifier WS? (requirement_marker)? """
specifier = "" url = "" marker = None
if tokenizer.check("AT"): tokenizer.read() tokenizer.consume("WS")
url_start = tokenizer.position url = tokenizer.expect("URL", expected="URL after @").text if tokenizer.check("END", peek=True): return (url, specifier, marker)
tokenizer.expect("WS", expected="whitespace after URL")
# The input might end after whitespace. if tokenizer.check("END", peek=True): return (url, specifier, marker)
marker = _parse_requirement_marker( tokenizer, span_start=url_start, expected="semicolon (after URL and whitespace)", ) else: specifier_start = tokenizer.position specifier = _parse_specifier(tokenizer) tokenizer.consume("WS")
if tokenizer.check("END", peek=True): return (url, specifier, marker)
marker = _parse_requirement_marker( tokenizer, span_start=specifier_start, expected=( "comma (within version specifier), semicolon (after version specifier)" if specifier else "semicolon (after name with no version specifier)" ), )
return (url, specifier, marker)
def _parse_requirement_marker( tokenizer: Tokenizer, *, span_start: int, expected: str) -> MarkerList: """ requirement_marker = SEMICOLON marker WS? """
if not tokenizer.check("SEMICOLON"): tokenizer.raise_syntax_error( f"Expected {expected} or end", span_start=span_start, span_end=None, ) tokenizer.read()
marker = _parse_marker(tokenizer) tokenizer.consume("WS")
return marker
def _parse_extras(tokenizer: Tokenizer) -> list[str]: """ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? """ if not tokenizer.check("LEFT_BRACKET", peek=True): return []
with tokenizer.enclosing_tokens( "LEFT_BRACKET", "RIGHT_BRACKET", around="extras", ): tokenizer.consume("WS") extras = _parse_extras_list(tokenizer) tokenizer.consume("WS")
return extras
def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: """ extras_list = identifier (wsp* ',' wsp* identifier)* """ extras: list[str] = []
if not tokenizer.check("IDENTIFIER"): return extras
extras.append(tokenizer.read().text)
while True: tokenizer.consume("WS") if tokenizer.check("IDENTIFIER", peek=True): tokenizer.raise_syntax_error("Expected comma between extra names") elif not tokenizer.check("COMMA"): break
tokenizer.read() tokenizer.consume("WS")
extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") extras.append(extra_token.text)
return extras
def _parse_specifier(tokenizer: Tokenizer) -> str: """ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS | WS? version_many WS? """ with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="version specifier", ): tokenizer.consume("WS") parsed_specifiers = _parse_version_many(tokenizer) tokenizer.consume("WS")
return parsed_specifiers
def _parse_version_many(tokenizer: Tokenizer) -> str: """ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? """ parsed_specifiers = "" while tokenizer.check("SPECIFIER"): span_start = tokenizer.position specifier = tokenizer.read().text parsed_specifiers += specifier if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): message = ".* suffix can only be used with `==` or `!=` operators" if specifier.startswith("!=") or ( specifier.startswith("==") and not specifier.startswith("===") ): message = ( ".* suffix cannot be used with pre-release, post-release, " "dev or local versions" ) tokenizer.raise_syntax_error( message, span_start=span_start, span_end=tokenizer.position + 1, ) if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): tokenizer.raise_syntax_error( "Local version label can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position, ) tokenizer.consume("WS") if not tokenizer.check("COMMA"): break parsed_specifiers += tokenizer.read().text tokenizer.consume("WS")
return parsed_specifiers
# --------------------------------------------------------------------------------------# Recursive descent parser for marker expression# --------------------------------------------------------------------------------------def parse_marker(source: str) -> MarkerList: return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: retval = _parse_marker(tokenizer) tokenizer.expect("END", expected="end of marker expression") return retval
def _parse_marker(tokenizer: Tokenizer) -> MarkerList: """ marker = marker_atom (BOOLOP marker_atom)+ """ expression = [_parse_marker_atom(tokenizer)] while tokenizer.check("BOOLOP"): token = tokenizer.read() expr_right = _parse_marker_atom(tokenizer) expression.extend((token.text, expr_right)) return expression
def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: """ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? | WS? marker_item WS? """
tokenizer.consume("WS") if tokenizer.check("LEFT_PARENTHESIS", peek=True): with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="marker expression", ): tokenizer.consume("WS") marker: MarkerAtom = _parse_marker(tokenizer) tokenizer.consume("WS") else: marker = _parse_marker_item(tokenizer) tokenizer.consume("WS") return marker
def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: """ marker_item = WS? marker_var WS? marker_op WS? marker_var WS? """ tokenizer.consume("WS") marker_var_left = _parse_marker_var(tokenizer) tokenizer.consume("WS") marker_op = _parse_marker_op(tokenizer) tokenizer.consume("WS") marker_var_right = _parse_marker_var(tokenizer) tokenizer.consume("WS") return (marker_var_left, marker_op, marker_var_right)
def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503 """ marker_var = VARIABLE | QUOTED_STRING """ if tokenizer.check("VARIABLE"): return process_env_var(tokenizer.read().text.replace(".", "_")) elif tokenizer.check("QUOTED_STRING"): token = tokenizer.read() try: return process_python_str(token.text) except (SyntaxError, ValueError) as exc: raise ParserSyntaxError( "Invalid quoted string", source=tokenizer.source, span=(token.position, token.position + len(token.text)), ) from exc else: tokenizer.raise_syntax_error( message="Expected a marker variable or quoted string" )
def process_env_var(env_var: str) -> Variable: if env_var in ("platform_python_implementation", "python_implementation"): return Variable("platform_python_implementation") else: return Variable(env_var)
def process_python_str(python_str: str) -> Value: value = ast.literal_eval(python_str) return Value(str(value))
def _parse_marker_op(tokenizer: Tokenizer) -> Op: """ marker_op = IN | NOT IN | OP """ if tokenizer.check("IN"): tokenizer.read() return Op("in") elif tokenizer.check("NOT"): tokenizer.read() tokenizer.expect("WS", expected="whitespace after 'not'") tokenizer.expect("IN", expected="'in' after 'not'") return Op("not in") elif tokenizer.check("OP"): return Op(tokenizer.read().text) else: return tokenizer.raise_syntax_error( "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details."""Private version-range helpers used by :mod:`packaging.specifiers`."""
from __future__ import annotations
import enumimport functoolsfrom typing import ( TYPE_CHECKING, Any, Final,)
from .version import InvalidVersion, Version
if TYPE_CHECKING: from collections.abc import Callable, Iterable, Iterator, Sequence from typing import Union
# Total-order key for comparing two boundaries (boundary-vs-boundary only). # The post slot may be ``_BOUNDARY_INF`` for an AFTER_POSTS boundary. _BoundaryOrderSuffix = tuple[int, int, int, Union[int, float], int, int] _BoundaryOrderKey = tuple[int, tuple[int, ...], _BoundaryOrderSuffix, float]
__all__ = [ "FULL_RANGE", "bounds_for_spec", "coerce_version", "filter_by_ranges", "intersect_ranges", "intersect_specifier_bounds", "least_version_above", "matches_bounds_only", "range_is_empty", "ranges_are_prerelease_only", "resolve_prereleases", "standard_ranges", "wildcard_ranges",]
#: The smallest possible PEP 440 version. No valid version is less than this.MIN_VERSION: Final[Version] = Version("0.dev0")
#: The smallest non-pre-release version, i.e. the nearest non-pre-release at or#: above the ``-inf`` floor.MIN_RELEASE: Final[Version] = Version("0")
#: Sorts above any real post number and any local label, so a boundary can be#: ordered above the version family it covers when two boundaries are compared._BOUNDARY_INF: Final[float] = float("inf")
class BoundaryKind(enum.Enum): """Where a boundary marker sits in the version ordering."""
AFTER_LOCALS = enum.auto() # after V+local, before V.post0 AFTER_POSTS = enum.auto() # after V.postN, before next release
@functools.total_orderingclass BoundaryVersion: """A point on the version line between two real PEP 440 versions.
Relative to a base version V::
V < V+local < AFTER_LOCALS(V) < V.post0 < AFTER_POSTS(V)
AFTER_LOCALS is the upper bound of ``<=V``, ``==V``, ``!=V`` (no local), and the lower bound of the upper-side range of ``!=V``. AFTER_POSTS is the lower bound of ``>V`` (V final or pre-release), excluding V's post-releases per PEP 440. """
__slots__ = ( "_cached_dev", "_cached_epoch", "_cached_post", "_cached_pre", "_cached_trimmed_release", "kind", "version", )
def __init__(self, version: Version, kind: BoundaryKind) -> None: self.version = version self.kind = kind self._cached_trimmed_release = trim_release(version.release) self._cached_epoch = version.epoch self._cached_pre = version.pre self._cached_post = version.post self._cached_dev = version.dev
def _is_family(self, other: Version) -> bool: """Is ``other`` a version that this boundary sorts above?""" if other.epoch != self._cached_epoch: return False # Inline release-trim comparison: other.release matches the # trimmed release iff its leading slice is equal and any extra # components are zero. Avoids trim_release's tuple allocation. other_release = other.release trimmed_release = self._cached_trimmed_release trimmed_length = len(trimmed_release) if len(other_release) < trimmed_length: return False if other_release[:trimmed_length] != trimmed_release: return False for i in range(trimmed_length, len(other_release)): if other_release[i] != 0: return False if other.pre != self._cached_pre: return False if self.kind == BoundaryKind.AFTER_LOCALS: # Local family: same public version, any local label. return other.post == self._cached_post and other.dev == self._cached_dev # Post family: V itself + any post-release of V. return other.dev == self._cached_dev or other.post is not None
def _order_key(self) -> _BoundaryOrderKey: """Sort key placing this boundary just above the versions it covers.
It extends ``V``'s comparison key ``(epoch, release, suffix)`` with a trailing ``_BOUNDARY_INF`` local component, so the key sorts after ``V`` and every ``V+local`` (whose keys carry a real, finite local segment). ``suffix`` is the 6-int comparison suffix ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``.
For an AFTER_POSTS boundary the suffix is replaced with one whose post number is ``_BOUNDARY_INF``, so the key also sorts after every ``V.postN``. An AFTER_LOCALS boundary uses ``V``'s suffix unchanged. """ version_key = self.version._key suffix: _BoundaryOrderSuffix = version_key[2]
if self.kind == BoundaryKind.AFTER_POSTS: suffix = (suffix[0], suffix[1], 1, _BOUNDARY_INF, 1, 0)
return version_key[0], version_key[1], suffix, _BOUNDARY_INF
def __eq__(self, other: object) -> bool: # Key off the order key so equality matches the ``<`` / ``>`` order: # ``AFTER_POSTS(1.0)`` and ``AFTER_POSTS(1.0.post1)`` are the same point. if isinstance(other, BoundaryVersion): return self._order_key() == other._order_key() return NotImplemented
def __lt__(self, other: BoundaryVersion | Version) -> bool: if isinstance(other, BoundaryVersion): return self._order_key() < other._order_key() # boundary < other_version iff V < other AND other not in family. # The cheap V >= other path short-circuits before the family check. if not (self.version < other): return False return not self._is_family(other)
def __gt__(self, other: BoundaryVersion | Version) -> bool: # Defined directly to bypass functools.total_ordering's # NotImplemented round-trip on reflected ``Version < boundary``. if isinstance(other, BoundaryVersion): return self._order_key() > other._order_key() if self.version >= other: return True return self._is_family(other)
def __hash__(self) -> int: # Keyed to ``__eq__`` (the order key), so equal boundaries hash equal. return hash(self._order_key())
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.version!r}, {self.kind.name})"
if TYPE_CHECKING: _VersionOrBoundary = Union[Version, BoundaryVersion, None]
@functools.total_orderingclass LowerBound: """Lower bound of a version range.
A version *v* of ``None`` means unbounded below (-inf). At equal versions, ``[v`` sorts before ``(v`` because an inclusive bound starts earlier. """
__slots__ = ("_above", "inclusive", "version")
def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: self.version = version self.inclusive = inclusive # Pre-bind a predicate "is parsed at or above this lower # bound?" for the hot filter / contains loops. One direct # call per check, no operator-dispatch chain. if version is None: self._above: Callable[[Version], bool] | None = None elif isinstance(version, BoundaryVersion): # >V produces an AFTER_POSTS lower bound; the upper-side # range of !=V produces an AFTER_LOCALS lower bound. if version.kind == BoundaryKind.AFTER_POSTS: self._above = _make_above_after_posts(version.version) else: self._above = _make_above_after_locals(version.version) elif inclusive: self._above = version.__le__ else: self._above = version.__lt__
def __eq__(self, other: object) -> bool: if not isinstance(other, LowerBound): return NotImplemented return self.version == other.version and self.inclusive == other.inclusive
def __lt__(self, other: LowerBound) -> bool: if not isinstance(other, LowerBound): return NotImplemented # -inf < anything (except -inf itself). if self.version is None: return other.version is not None if other.version is None: return False if self.version != other.version: return self.version < other.version # [v < (v: inclusive starts earlier. return self.inclusive and not other.inclusive
def __hash__(self) -> int: return hash((self.version, self.inclusive))
def __repr__(self) -> str: bracket = "[" if self.inclusive else "(" return f"<{self.__class__.__name__} {bracket}{self.version!r}>"
@functools.total_orderingclass UpperBound: """Upper bound of a version range.
A version *v* of ``None`` means unbounded above (+inf). At equal versions, ``v)`` sorts before ``v]`` because an exclusive bound ends earlier. """
__slots__ = ("_below", "inclusive", "version")
def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: self.version = version self.inclusive = inclusive # Pre-bind a predicate "is parsed at or below this upper # bound?". See LowerBound for the rationale. if version is None: self._below: Callable[[Version], bool] | None = None elif isinstance(version, BoundaryVersion): # Standard specifiers only ever produce AFTER_LOCALS upper # bounds (from <=V / ==V / !=V with no local). if version.kind == BoundaryKind.AFTER_LOCALS: self._below = _make_below_after_locals(version.version) else: # An AFTER_POSTS upper is not produced by any specifier, but # range algebra reaches it: complementing ``>V`` flips the # ``AFTER_POSTS(V)`` lower into this upper bound. self._below = version.__ge__ elif inclusive: self._below = version.__ge__ else: self._below = version.__gt__
def __eq__(self, other: object) -> bool: if not isinstance(other, UpperBound): return NotImplemented return self.version == other.version and self.inclusive == other.inclusive
def __lt__(self, other: UpperBound) -> bool: if not isinstance(other, UpperBound): return NotImplemented # Nothing < +inf (except +inf itself). if self.version is None: return False if other.version is None: return True if self.version != other.version: return self.version < other.version # v) < v]: exclusive ends earlier. return not self.inclusive and other.inclusive
def __hash__(self) -> int: return hash((self.version, self.inclusive))
def __repr__(self) -> str: bracket = "]" if self.inclusive else ")" return f"<{self.__class__.__name__} {self.version!r}{bracket}>"
if TYPE_CHECKING: #: A single contiguous interval as a (lower, upper) bound pair. Interval = tuple[LowerBound, UpperBound]
NEG_INF: Final[LowerBound] = LowerBound(None, False)POS_INF: Final[UpperBound] = UpperBound(None, False)FULL_RANGE: Final[tuple[Interval]] = ((NEG_INF, POS_INF),)
def trim_release(release: tuple[int, ...]) -> tuple[int, ...]: """Strip trailing zeros from a release tuple for normalized comparison.""" end = len(release) while end > 1 and release[end - 1] == 0: end -= 1 return release if end == len(release) else release[:end]
def _next_prefix_dev0(version: Version) -> Version: """Smallest version in the next prefix: 1.2 -> 1.3.dev0.""" release = (*version.release[:-1], version.release[-1] + 1) return Version.from_parts(epoch=version.epoch, release=release, dev=0)
def _base_dev0(version: Version) -> Version: """The .dev0 of a version's base release: 1.2 -> 1.2.dev0.""" return Version.from_parts(epoch=version.epoch, release=version.release, dev=0)
def coerce_version(version: Version | str) -> Version | None: if not isinstance(version, Version): try: version = Version(version) except InvalidVersion: return None return version
def _make_above_after_posts(version: Version) -> Callable[[Version], bool]: """Predicate ``parsed > AFTER_POSTS(V)`` for a lower bound.
Per PEP 440, ``>V`` excludes V's post-releases unless V is itself a post-release. AFTER_POSTS sits above V and every V.postN (with or without local), and just below the next release. """ version_ge = version.__ge__ version_epoch = version.epoch version_pre = version.pre version_release_trimmed = trim_release(version.release) trimmed_length = len(version_release_trimmed)
def above(parsed: Version) -> bool: if version_ge(parsed): return False # parsed > V cmpkey-wise: above the boundary iff NOT in V's # post family. if parsed.epoch != version_epoch: return True parsed_release = parsed.release if len(parsed_release) < trimmed_length: return True if parsed_release[:trimmed_length] != version_release_trimmed: return True for i in range(trimmed_length, len(parsed_release)): if parsed_release[i] != 0: return True if parsed.pre != version_pre: return True
# Same release and pre as V: parsed is in V's post family (V itself, # V+local, or V.postN), which the boundary sits above. A V.devN # (different dev, no post) sorts before V and was already caught by # ``version_ge`` above, so the answer here is always "not above". return False
return above
def _make_above_after_locals(version: Version) -> Callable[[Version], bool]: """Predicate ``parsed > AFTER_LOCALS(V)`` for a lower bound.
Used by the upper-side range of ``!=V`` (when V has no local segment). AFTER_LOCALS sits above V and every ``V+local`` but just below ``V.post0``. """ version_ge = version.__ge__ version_epoch = version.epoch version_pre = version.pre version_post = version.post version_dev = version.dev version_release_trimmed = trim_release(version.release) trimmed_length = len(version_release_trimmed)
def above(parsed: Version) -> bool: if version_ge(parsed): return False # parsed > V cmpkey-wise: above the boundary iff NOT in V's # local family (same public version, any local segment). if parsed.epoch != version_epoch: return True parsed_release = parsed.release if len(parsed_release) < trimmed_length: return True if parsed_release[:trimmed_length] != version_release_trimmed: return True for i in range(trimmed_length, len(parsed_release)): if parsed_release[i] != 0: return True if parsed.pre != version_pre: return True if parsed.post != version_post: return True return parsed.dev != version_dev
return above
def _make_below_after_locals(version: Version) -> Callable[[Version], bool]: """Predicate ``parsed <= AFTER_LOCALS(V)`` for an upper bound.
Used by ``<=V``, ``==V``, ``!=V`` (no local). ``parsed`` is at or below the boundary when it is at or below V cmpkey-wise, or when it is in V's local family. """ version_ge = version.__ge__ version_epoch = version.epoch version_pre = version.pre version_post = version.post version_dev = version.dev version_release_trimmed = trim_release(version.release) trimmed_length = len(version_release_trimmed)
def below(parsed: Version) -> bool: if version_ge(parsed): return True # parsed > V cmpkey-wise: below the boundary iff in V's local # family. if parsed.epoch != version_epoch: return False parsed_release = parsed.release if len(parsed_release) < trimmed_length: return False if parsed_release[:trimmed_length] != version_release_trimmed: return False for i in range(trimmed_length, len(parsed_release)): if parsed_release[i] != 0: return False if parsed.pre != version_pre: return False if parsed.post != version_post: return False return parsed.dev == version_dev
return below
def least_version_above(boundary: BoundaryVersion) -> Version | None: """Smallest real version strictly above *boundary*, or ``None`` if none exists.""" base = boundary.version
if boundary.kind == BoundaryKind.AFTER_LOCALS: # AFTER_LOCALS(V) sits just below V.post0, so its least successor is # V.post0.dev0 (V.dev(N+1) if V has a dev, V.post(N+1).dev0 if a post). if base.dev is not None: return base.__replace__(dev=base.dev + 1, local=None) next_post = (base.post + 1) if base.post is not None else 0 return base.__replace__(post=next_post, dev=0, local=None)
# AFTER_POSTS(V): a pre-release V steps to the next pre-release's .dev0; # a final-release AFTER_POSTS has no least successor. if base.pre is not None: kind, number = base.pre return base.__replace__(pre=(kind, number + 1), post=None, dev=0, local=None)
return None
def range_is_empty(lower: LowerBound, upper: UpperBound) -> bool: """True when the range defined by *lower* and *upper* contains no versions.
A boundary lower sits just below the next real version, so an ordered pair is still empty when the upper excludes that least successor: ``(AFTER_POSTS(1.0a1), 1.0a2.dev0)`` holds no version. """ if upper.version is None: return False
if lower.version is None: # Nothing sorts below MIN_VERSION, so an exclusive upper at or below it # leaves an empty floor interval such as ``(-inf, 0.dev0)``. return ( not upper.inclusive and isinstance(upper.version, Version) and upper.version <= MIN_VERSION )
if isinstance(lower.version, BoundaryVersion): successor = least_version_above(lower.version) if successor is not None: if upper.version == successor: return not upper.inclusive return upper.version < successor
if lower.version == upper.version: return not (lower.inclusive and upper.inclusive)
return lower.version > upper.version
def intersect_ranges( left: Sequence[Interval], right: Sequence[Interval],) -> list[Interval]: """Intersect two sorted, non-overlapping range lists (two-pointer merge).""" result: list[Interval] = [] left_index = right_index = 0 while left_index < len(left) and right_index < len(right): left_lower, left_upper = left[left_index] right_lower, right_upper = right[right_index]
lower = max(left_lower, right_lower) upper = min(left_upper, right_upper)
if not range_is_empty(lower, upper): result.append((lower, upper))
# Advance whichever side has the smaller upper bound. if left_upper < right_upper: left_index += 1 else: right_index += 1
return result
def filter_by_ranges( ranges: Sequence[Interval], iterable: Iterable[Any], key: Callable[[Any], Version | str] | None, prereleases: bool | None, region: Sequence[Interval] = (),) -> Iterator[Any]: """Filter *iterable* against precomputed version *ranges*.
With ``prereleases=None``, the PEP 440 default applies: pre-releases are excluded unless no final matches, in which case buffered pre-releases come out at the end. A pre-release inside the opt-in ``region`` is the exception: it is force-admitted in place, as ``prereleases=True`` would yield it. A force-admitted pre-release is not a final, so it never suppresses the buffer. """ if prereleases is None: prerelease_buffer: list[Any] = [] found_final = False
if len(ranges) == 1: # Hot path: most specifiers and small SpecifierSets reduce to # a single contiguous range. lower, upper = ranges[0] above = lower._above below = upper._below for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue if above is not None and not above(parsed): continue if below is not None and not below(parsed): continue if not parsed.is_prerelease: found_final = True yield item elif region and matches_bounds_only(region, parsed): yield item elif not found_final: prerelease_buffer.append(item) if not found_final: yield from prerelease_buffer return
for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue for lower, upper in ranges: above = lower._above if above is not None and not above(parsed): break below = upper._below if below is None or below(parsed): if not parsed.is_prerelease: found_final = True yield item elif region and matches_bounds_only(region, parsed): yield item elif not found_final: prerelease_buffer.append(item) break if not found_final: yield from prerelease_buffer return
exclude_prereleases = prereleases is False
if len(ranges) == 1: # Hot path: most specifiers and small SpecifierSets reduce to # a single contiguous range. lower, upper = ranges[0] above = lower._above below = upper._below for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue if exclude_prereleases and parsed.is_prerelease: continue if above is not None and not above(parsed): continue if below is None or below(parsed): yield item return
for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue if exclude_prereleases and parsed.is_prerelease: continue for lower, upper in ranges: above = lower._above if above is not None and not above(parsed): break below = upper._below if below is None or below(parsed): yield item break
def _nearest_release_above_prerelease(version: Version) -> Version: """Smallest non-pre-release at or above a pre-release *version*.""" if version.pre is not None: # An a/b/rc pre-release drops to its final release, which outranks # every post-release of that pre-release (1.0a1.post0 -> 1.0). return version.__replace__(pre=None, post=None, dev=None, local=None)
# A dev-only release keeps its post-release (1.0.post0.dev0 -> 1.0.post0, # whose final 1.0 sorts below it). return version.__replace__(dev=None, local=None)
def _lowest_release_at_or_above(value: Version | BoundaryVersion | None) -> Version: """Smallest non-pre-release version at or above *value*.
``None`` is the ``-inf`` floor, whose nearest non-pre-release is :data:`MIN_RELEASE`. """ if value is None: return MIN_RELEASE if isinstance(value, BoundaryVersion): inner_version = value.version if inner_version.is_prerelease: return _nearest_release_above_prerelease(inner_version) # AFTER_LOCALS(1.0) -> nearest non-pre is 1.0.post0 # AFTER_LOCALS(1.0.post0) -> nearest non-pre is 1.0.post1 next_post = (inner_version.post + 1) if inner_version.post is not None else 0 return inner_version.__replace__(post=next_post, local=None)
if not value.is_prerelease: return value
return _nearest_release_above_prerelease(value)
def ranges_are_prerelease_only(ranges: Sequence[Interval]) -> bool: """True when every range in *ranges* contains only pre-releases.
Used to detect unsatisfiable specifier sets when ``prereleases=False``: if every range is pre-release-only, every contained version is excluded. """ for lower, upper in ranges: nearest = _lowest_release_at_or_above(lower.version) if upper.version is None or nearest < upper.version: return False if nearest == upper.version and upper.inclusive: return False return True
def wildcard_ranges(op: str, base: Version) -> list[Interval]: """Ranges for ==V.* and !=V.*.
==1.2.* -> [1.2.dev0, 1.3.dev0); !=1.2.* -> complement. """ lower = _base_dev0(base) upper = _next_prefix_dev0(base) if op == "==": return [(LowerBound(lower, True), UpperBound(upper, False))] # != return [ (NEG_INF, UpperBound(lower, False)), (LowerBound(upper, True), POS_INF), ]
def standard_ranges(op: str, version: Version, has_local: bool) -> list[Interval]: """Ranges for the standard PEP 440 operators (no wildcard, no ===).
*has_local* indicates whether the spec string included a ``+local`` segment; relevant only for ``==`` / ``!=`` to decide whether the upper bound includes V's local family. """ if op == ">=": return [(LowerBound(version, True), POS_INF)]
if op == "<=": return [ ( NEG_INF, UpperBound(BoundaryVersion(version, BoundaryKind.AFTER_LOCALS), True), ) ]
if op == ">": if version.dev is not None: # >V.devN: dev versions have no post-releases, so the # next real version is V.dev(N+1). lower_bound = version.__replace__(dev=version.dev + 1, local=None) return [(LowerBound(lower_bound, True), POS_INF)] if version.post is not None: # >V.postN: next real version is V.post(N+1).dev0. lower_bound = version.__replace__(post=version.post + 1, dev=0, local=None) return [(LowerBound(lower_bound, True), POS_INF)] # >V (final or pre-release V): exclude V itself, V+local, and # every V.postN per PEP 440. return [ ( LowerBound(BoundaryVersion(version, BoundaryKind.AFTER_POSTS), False), POS_INF, ) ]
if op == "<": # <V excludes pre-releases of V when V is not a pre-release. # V.dev0 is the earliest pre-release of V. bound = ( version if version.is_prerelease else version.__replace__(dev=0, local=None) ) if bound <= MIN_VERSION: return [] return [(NEG_INF, UpperBound(bound, False))]
# ==, !=: local versions of V match when the spec has no local segment. after_locals = BoundaryVersion(version, BoundaryKind.AFTER_LOCALS) upper = version if has_local else after_locals
if op == "==": return [(LowerBound(version, True), UpperBound(upper, True))]
if op == "!=": return [ (NEG_INF, UpperBound(version, False)), (LowerBound(upper, False), POS_INF), ]
if op == "~=": prefix = version.__replace__(release=version.release[:-1]) return [ (LowerBound(version, True), UpperBound(_next_prefix_dev0(prefix), False)) ]
raise ValueError(f"Unknown operator: {op!r}") # pragma: no cover
def bounds_for_spec(op: str, version_str: str, version: Version) -> list[Interval]: """Ranges for one specifier's ``(op, version_str)``.
Dispatches between the wildcard and standard builders. ``version`` is the parsed ``version_str`` (its base, without the trailing ``.*``, for wildcards). ``===`` is not handled here; its match is a literal string compared in :mod:`packaging.specifiers`. """ if version_str.endswith(".*"): return wildcard_ranges(op, version)
return standard_ranges(op, version, "+" in version_str)
def intersect_specifier_bounds( per_specifier_ranges: Iterable[Sequence[Interval]],) -> Sequence[Interval]: """Intersect each specifier's ranges into a single sequence.
Short-circuits once the running intersection is empty, since no later specifier can revive it. Callers must pass at least one specifier. """ result: Sequence[Interval] | None = None for sub in per_specifier_ranges: if result is None: result = sub else: result = intersect_ranges(result, sub) if not result: break
if result is None: # pragma: no cover - callers guard non-empty input raise RuntimeError("intersect_specifier_bounds called with no specifiers")
return result
def matches_bounds_only(ranges: Sequence[Interval], version: Version) -> bool: """Whether ``version`` falls within any of ``ranges``.
The pure bounds membership test, for a single already-parsed version with no pre-release policy applied. ``ranges`` are sorted and non-overlapping, so a version below one range's lower bound is below every later range too. """ for lower, upper in ranges: above = lower._above if above is not None and not above(version): return False
below = upper._below if below is None or below(version): return True
return False
def resolve_prereleases( configured: bool | None, autodetected: bool | None) -> bool | None: """Resolve a specifier's effective default pre-release policy.
An explicit ``configured`` value wins; otherwise an autodetected ``True`` propagates and anything else falls back to the PEP 440 default (``None``). """ if configured is not None: return configured
if autodetected: return True
return None123456789101112131415161718192021222324252627282930313233# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
"""Backward-compatibility shim for unpickling Version objects serialized beforepackaging 26.1.
Old pickles reference ``packaging._structures.InfinityType`` and``packaging._structures.NegativeInfinityType``. This module provides minimalstand-in classes so that ``pickle.loads()`` can resolve those references.The deserialized objects are not used for comparisons — ``Version.__setstate__``discards the stale ``_key`` cache and recomputes it from the core version fields."""
from __future__ import annotations
class InfinityType: """Stand-in for the removed ``InfinityType`` used in old comparison keys."""
def __repr__(self) -> str: return "Infinity"
class NegativeInfinityType: """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys."""
def __repr__(self) -> str: return "-Infinity"
Infinity = InfinityType()NegativeInfinity = NegativeInfinityType()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200from __future__ import annotations
import contextlibimport refrom dataclasses import dataclassfrom typing import TYPE_CHECKING, NoReturn
from .specifiers import Specifier
if TYPE_CHECKING: from collections.abc import Generator, Mapping
@dataclassclass Token: __slots__ = ("name", "position", "text")
name: str text: str position: int
class ParserSyntaxError(Exception): """The provided source text could not be parsed correctly."""
def __init__( self, message: str, *, source: str, span: tuple[int, int], ) -> None: self.span = span self.message = message self.source = source
super().__init__()
def __str__(self) -> str: marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" return f"{self.message}\n {self.source}\n {marker}"
DEFAULT_RULES: dict[str, re.Pattern[str]] = { "LEFT_PARENTHESIS": re.compile(r"\("), "RIGHT_PARENTHESIS": re.compile(r"\)"), "LEFT_BRACKET": re.compile(r"\["), "RIGHT_BRACKET": re.compile(r"\]"), "SEMICOLON": re.compile(r";"), "COMMA": re.compile(r","), "QUOTED_STRING": re.compile( r""" ( ('[^']*') | ("[^"]*") ) """, re.VERBOSE, ), "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"), "BOOLOP": re.compile(r"\b(or|and)\b"), "IN": re.compile(r"\bin\b"), "NOT": re.compile(r"\bnot\b"), "VARIABLE": re.compile( r""" \b( python_version |python_full_version |os[._]name |sys[._]platform |platform_(release|system) |platform[._](version|machine|python_implementation) |python_implementation |implementation_(name|version) |extras? |dependency_groups )\b """, re.VERBOSE, ), "SPECIFIER": re.compile( Specifier._specifier_regex_str, re.VERBOSE | re.IGNORECASE, ), "AT": re.compile(r"\@"), "URL": re.compile(r"[^ \t]+"), "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), "WS": re.compile(r"[ \t]+"), "END": re.compile(r"\Z"),}
class Tokenizer: """Context-sensitive token parsing.
Provides methods to examine the input stream to check whether the next token matches. """
__slots__ = ("next_token", "position", "rules", "source")
def __init__( self, source: str, *, rules: Mapping[str, re.Pattern[str]], ) -> None: self.source = source self.rules = rules self.next_token: Token | None = None self.position = 0
def consume(self, name: str) -> None: """Move beyond provided token name, if at current position.""" if self.check(name): self.read()
def check(self, name: str, *, peek: bool = False) -> bool: """Check whether the next token has the provided name.
By default, if the check succeeds, the token *must* be read before another check. If `peek` is set to `True`, the token is not loaded and would need to be checked again. """ assert self.next_token is None, ( f"Cannot check for {name!r}, already have {self.next_token!r}" ) assert name in self.rules, f"Unknown token name: {name!r}"
expression = self.rules[name]
match = expression.match(self.source, self.position) if match is None: return False if not peek: self.next_token = Token(name, match[0], self.position) return True
def expect(self, name: str, *, expected: str) -> Token: """Expect a certain token name next, failing with a syntax error otherwise.
The token is read and returned. """ if not self.check(name): raise self.raise_syntax_error(f"Expected {expected}") return self.read()
def read(self) -> Token: """Consume the next token and return it.""" token = self.next_token assert token is not None
self.position += len(token.text) self.next_token = None
return token
def raise_syntax_error( self, message: str, *, span_start: int | None = None, span_end: int | None = None, ) -> NoReturn: """Raise ParserSyntaxError at the given position.""" span = ( self.position if span_start is None else span_start, self.position if span_end is None else span_end, ) raise ParserSyntaxError( message, source=self.source, span=span, )
@contextlib.contextmanager def enclosing_tokens( self, open_token: str, close_token: str, *, around: str ) -> Generator[None, None, None]: if self.check(open_token): open_position = self.position self.read() else: open_position = None
yield
if open_position is None: return
if not self.check(close_token): self.raise_syntax_error( f"Expected matching {close_token} for {open_token}, after {around}", span_start=open_position, )
self.read()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335from __future__ import annotations
import refrom collections.abc import Mapping, Sequence
from .errors import _ErrorCollectorfrom .requirements import InvalidRequirement, Requirement
__all__ = [ "CyclicDependencyGroup", "DependencyGroupInclude", "DependencyGroupResolver", "DuplicateGroupNames", "InvalidDependencyGroupObject", "resolve_dependency_groups",]
def __dir__() -> list[str]: return __all__
# -----------# Error Types# -----------
class DuplicateGroupNames(ValueError): """ The same dependency groups were defined twice, with different non-normalized names.
.. versionadded:: 26.1 """
class CyclicDependencyGroup(ValueError): """ The dependency group includes form a cycle.
.. versionadded:: 26.1 """
def __init__(self, requested_group: str, group: str, include_group: str) -> None: self.requested_group = requested_group self.group = group self.include_group = include_group
if include_group == group: reason = f"{group} includes itself" else: reason = f"{include_group} -> {group}, {group} -> {include_group}" super().__init__( "Cyclic dependency group include while resolving " f"{requested_group}: {reason}" )
# Support pickling; ``args`` does not match ``__init__``'s signature. def __reduce__(self) -> tuple[type[CyclicDependencyGroup], tuple[str, str, str]]: return (self.__class__, (self.requested_group, self.group, self.include_group))
# in the PEP 735 spec, the tables in dependency group lists were described as# "Dependency Object Specifiers", but the only defined type of object was a# "Dependency Group Include" -- hence the naming of this error as "Object"class InvalidDependencyGroupObject(ValueError): """ A member of a dependency group was identified as a dict, but was not in a valid format.
.. versionadded:: 26.1 """
# ------------------------# Object Model & Interface# ------------------------
class DependencyGroupInclude: """ A reference to another dependency group by name.
.. versionadded:: 26.1 """
__slots__ = ("include_group",)
def __init__(self, include_group: str) -> None: """ Initialize a DependencyGroupInclude.
:param include_group: The name of the group referred to by this include. """ self.include_group = include_group
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.include_group!r})"
class DependencyGroupResolver: """ A resolver for Dependency Group data.
This class handles caching, name normalization, cycle detection, and other parsing requirements. There are only two public methods for exploring the data: ``lookup()`` and ``resolve()``.
:param dependency_groups: A mapping, as provided via pyproject ``[dependency-groups]``.
.. versionadded:: 26.1 """
def __init__( self, dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], ) -> None: errors = _ErrorCollector()
self.dependency_groups = _normalize_group_names(dependency_groups, errors)
# a map of group names to parsed data self._parsed_groups: dict[ str, tuple[Requirement | DependencyGroupInclude, ...] ] = {} # a map of group names to their ancestors, used for cycle detection self._include_graph_ancestors: dict[str, tuple[str, ...]] = {} # a cache of completed resolutions to Requirement lists self._resolve_cache: dict[str, tuple[Requirement, ...]] = {}
errors.finalize("[dependency-groups] data was invalid")
def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]: """ Lookup a group name, returning the parsed dependency data for that group. This will not resolve includes.
:param group: the name of the group to lookup """ group = _normalize_name(group)
with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._parse_group(group, errors)
def resolve(self, group: str) -> tuple[Requirement, ...]: """ Resolve a dependency group to a list of requirements.
:param group: the name of the group to resolve """ group = _normalize_name(group)
with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._resolve(group, group, errors)
def _resolve( self, group: str, requested_group: str, errors: _ErrorCollector ) -> tuple[Requirement, ...]: """ This is a helper for cached resolution to strings. It preserves the name of the group which the user initially requested in order to present a clearer error in the event that a cycle is detected.
:param group: The normalized name of the group to resolve. :param requested_group: The group which was used in the original, user-facing request. """ if group in self._resolve_cache: return self._resolve_cache[group]
parsed = self._parse_group(group, errors)
resolved_group = []
for item in parsed: if isinstance(item, Requirement): resolved_group.append(item) elif isinstance(item, DependencyGroupInclude): include_group = _normalize_name(item.include_group)
# if a group is cyclic, record the error # otherwise, follow the include_group reference # # this allows us to examine all includes in a group, even in the # presence of errors if include_group in self._include_graph_ancestors.get(group, ()): errors.error( CyclicDependencyGroup( requested_group, group, item.include_group ) ) else: self._include_graph_ancestors[include_group] = ( *self._include_graph_ancestors.get(group, ()), group, ) resolved_group.extend( self._resolve(include_group, requested_group, errors) ) else: # pragma: no cover raise NotImplementedError( f"Invalid dependency group item after parse: {item}" )
# in the event that errors were detected, present the group as empty and do not # cache the result # this ensures that repeated access to a cyclic group will raise multiple errors if errors.errors: return ()
self._resolve_cache[group] = tuple(resolved_group) return self._resolve_cache[group]
def _parse_group( self, group: str, errors: _ErrorCollector ) -> tuple[Requirement | DependencyGroupInclude, ...]: # short circuit -- never do the work twice if group in self._parsed_groups: return self._parsed_groups[group]
if group not in self.dependency_groups: errors.error(LookupError(f"Dependency group '{group}' not found")) return ()
raw_group = self.dependency_groups[group] if isinstance(raw_group, str): errors.error( TypeError( f"Dependency group {group!r} contained a string rather than a list." ) ) return ()
if not isinstance(raw_group, Sequence): errors.error( TypeError(f"Dependency group {group!r} is not a sequence type.") ) return ()
elements: list[Requirement | DependencyGroupInclude] = [] for item in raw_group: if isinstance(item, str): # packaging.requirements.Requirement parsing ensures that this is a # valid PEP 508 Dependency Specifier. Collect InvalidRequirement # if it throws that. with errors.collect(InvalidRequirement): elements.append(Requirement(item)) elif isinstance(item, Mapping): if tuple(item.keys()) != ("include-group",): errors.error( InvalidDependencyGroupObject( f"Invalid dependency group item: {item!r}" ) ) else: include_group = item["include-group"] if not isinstance(include_group, str): msg = ( "Dependency group include-group value is not a string: " f"{item!r}" ) errors.error(TypeError(msg)) else: elements.append( DependencyGroupInclude(include_group=include_group) ) else: errors.error(TypeError(f"Invalid dependency group item: {item!r}"))
if errors.errors: return ()
self._parsed_groups[group] = tuple(elements) return self._parsed_groups[group]
# --------------------# Functional Interface# --------------------
def resolve_dependency_groups( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str) -> tuple[str, ...]: """ Resolve a dependency group to a tuple of requirements, as strings.
:param dependency_groups: the parsed contents of the ``[dependency-groups]`` table from ``pyproject.toml`` :param groups: the name of the group(s) to resolve
.. versionadded:: 26.1 """ resolver = DependencyGroupResolver(dependency_groups) return tuple(str(r) for group in groups for r in resolver.resolve(group))
# ----------------# internal helpers# ----------------
_NORMALIZE_PATTERN = re.compile(r"[-_.]+")
def _normalize_name(name: str) -> str: return _NORMALIZE_PATTERN.sub("-", name).lower()
def _normalize_group_names( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], errors: _ErrorCollector,) -> dict[str, Sequence[str | Mapping[str, str]]]: original_names: dict[str, list[str]] = {} normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {}
for group_name, value in dependency_groups.items(): normed_group_name = _normalize_name(group_name) original_names.setdefault(normed_group_name, []).append(group_name) normalized_groups[normed_group_name] = value
for normed_name, names in original_names.items(): if len(names) > 1: errors.error( DuplicateGroupNames( "Duplicate dependency group names: " f"{normed_name} ({', '.join(names)})" ) )
return normalized_groups123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349from __future__ import annotations
import dataclassesimport reimport urllib.parsefrom collections.abc import Mappingfrom typing import TYPE_CHECKING, Any, Protocol, TypeVar
if TYPE_CHECKING: # pragma: no cover import sys from collections.abc import Collection from urllib.parse import SplitResult
if sys.version_info >= (3, 11): from typing import Self else: from typing_extensions import Self
__all__ = [ "ArchiveInfo", "DirInfo", "DirectUrl", "DirectUrlValidationError", "VcsInfo",]
def __dir__() -> list[str]: return __all__
_T = TypeVar("_T")
class _FromMappingProtocol(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
def _json_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return {key: value for key, value in data if value is not None}
def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type): raise DirectUrlValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value
def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _DirectUrlRequiredKeyError(key) return value
def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise DirectUrlValidationError(e, context=key) from e
_PEP610_USER_PASS_ENV_VARS_REGEX = re.compile( r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$")
def _strip_auth_from_netloc(netloc: str, safe_user_passwords: Collection[str]) -> str: if "@" not in netloc: return netloc user_pass, netloc_no_user_pass = netloc.rsplit("@", 1) if user_pass in safe_user_passwords: return netloc if _PEP610_USER_PASS_ENV_VARS_REGEX.match(user_pass): return netloc return netloc_no_user_pass
def _strip_url(url: str, safe_user_passwords: Collection[str]) -> str: """url with user:password part removed unless it is formed with environment variables as specified in PEP 610, or it is a safe user:password such as `git`. """ parsed_url = urllib.parse.urlsplit(url) netloc = _strip_auth_from_netloc(parsed_url.netloc, safe_user_passwords) return urllib.parse.urlunsplit( ( parsed_url.scheme, netloc, parsed_url.path, parsed_url.query, parsed_url.fragment, ) )
def _file_url_has_absolute_path(parsed_url: SplitResult) -> bool: return parsed_url.path.startswith("/")
class DirectUrlValidationError(Exception): """Raised when when input data is not spec-compliant.
.. versionadded:: 26.1 """
context: str | None = None message: str
def __init__( self, cause: str | Exception, *, context: str | None = None, ) -> None: if isinstance(cause, DirectUrlValidationError): if cause.context: self.context = ( f"{context}.{cause.context}" if context else cause.context ) else: self.context = context # pragma: no cover self.message = cause.message else: self.context = context self.message = str(cause)
def __str__(self) -> str: if self.context: return f"{self.message} in {self.context!r}" return self.message
class _DirectUrlRequiredKeyError(DirectUrlValidationError): def __init__(self, key: str) -> None: super().__init__("Missing required value", context=key)
@dataclasses.dataclass(frozen=True, init=False)class VcsInfo: """The version control information of a :class:`DirectUrl`."""
vcs: str commit_id: str requested_revision: str | None = None
def __init__( self, *, vcs: str, commit_id: str, requested_revision: str | None = None, ) -> None: object.__setattr__(self, "vcs", vcs) object.__setattr__(self, "commit_id", commit_id) object.__setattr__(self, "requested_revision", requested_revision)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: # We can't validate vcs value because is not closed. return cls( vcs=_get_required(d, str, "vcs"), requested_revision=_get(d, str, "requested_revision"), commit_id=_get_required(d, str, "commit_id"), )
@dataclasses.dataclass(frozen=True, init=False)class ArchiveInfo: """The archive information of a :class:`DirectUrl`."""
hashes: Mapping[str, str] | None = None
def __init__( self, *, hashes: Mapping[str, str] | None = None, ) -> None: object.__setattr__(self, "hashes", hashes)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: hashes = _get(d, Mapping, "hashes") # type: ignore[type-abstract] if hashes is not None and not all(isinstance(h, str) for h in hashes.values()): raise DirectUrlValidationError( "Hash values must be strings", context="hashes" ) legacy_hash = _get(d, str, "hash") if legacy_hash is not None: if "=" not in legacy_hash: raise DirectUrlValidationError( "Invalid hash format (expected '<algorithm>=<hash>')", context="hash", ) hash_algorithm, hash_value = legacy_hash.split("=", 1) if hashes is None: # if `hashes` are not present, we can derive it from the legacy `hash` hashes = {hash_algorithm: hash_value} else: # if `hashes` are present, the legacy `hash` must match one of them if hash_algorithm not in hashes: raise DirectUrlValidationError( f"Algorithm {hash_algorithm!r} used in hash field " f"is not present in hashes field", context="hashes", ) if hashes[hash_algorithm] != hash_value: raise DirectUrlValidationError( f"Algorithm {hash_algorithm!r} used in hash field " f"has different value in hashes field", context="hash", ) return cls(hashes=hashes)
@dataclasses.dataclass(frozen=True, init=False)class DirInfo: """The local directory information of a :class:`DirectUrl`."""
editable: bool | None = None
def __init__( self, *, editable: bool | None = None, ) -> None: object.__setattr__(self, "editable", editable)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: return cls( editable=_get(d, bool, "editable"), )
@dataclasses.dataclass(frozen=True, init=False)class DirectUrl: """A class representing a direct URL.
.. versionadded:: 26.1 """
url: str archive_info: ArchiveInfo | None = None vcs_info: VcsInfo | None = None dir_info: DirInfo | None = None subdirectory: str | None = None # XXX Path or str?
def __init__( self, *, url: str, archive_info: ArchiveInfo | None = None, vcs_info: VcsInfo | None = None, dir_info: DirInfo | None = None, subdirectory: str | None = None, ) -> None: object.__setattr__(self, "url", url) object.__setattr__(self, "archive_info", archive_info) object.__setattr__(self, "vcs_info", vcs_info) object.__setattr__(self, "dir_info", dir_info) object.__setattr__(self, "subdirectory", subdirectory)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: direct_url = cls( url=_get_required(d, str, "url"), archive_info=_get_object(d, ArchiveInfo, "archive_info"), vcs_info=_get_object(d, VcsInfo, "vcs_info"), dir_info=_get_object(d, DirInfo, "dir_info"), subdirectory=_get(d, str, "subdirectory"), ) if ( bool(direct_url.vcs_info) + bool(direct_url.archive_info) + bool(direct_url.dir_info) ) != 1: raise DirectUrlValidationError( "Exactly one of vcs_info, archive_info, dir_info must be present" ) if direct_url.dir_info is not None: parsed_url = urllib.parse.urlsplit(direct_url.url) if parsed_url.scheme != "file": raise DirectUrlValidationError( "URL scheme must be file:// when dir_info is present", context="url", ) if not _file_url_has_absolute_path(parsed_url): raise DirectUrlValidationError( "File URL must be absolute when dir_info is present", context="url", ) # XXX subdirectory must be relative, can we, should we validate that here? return direct_url
@classmethod def from_dict(cls, d: Mapping[str, Any], /) -> Self: """Create and validate a DirectUrl instance from a JSON dictionary.""" return cls._from_dict(d)
def to_dict( self, *, generate_legacy_hash: bool = False, strip_user_password: bool = True, safe_user_passwords: Collection[str] = ("git",), ) -> Mapping[str, Any]: """Convert the DirectUrl instance to a JSON dictionary.
:param generate_legacy_hash: If True, include a legacy `hash` field in `archive_info` for backward compatibility with tools that don't support the `hashes` field. :param strip_user_password: If True, strip user:password from the URL unless it is formed with environment variables as specified in PEP 610, or it is a safe user:password such as `git`. :param safe_user_passwords: A collection of user:password strings that should not be stripped from the URL even if `strip_user_password` is True. """ res = dataclasses.asdict(self, dict_factory=_json_dict_factory) if generate_legacy_hash and self.archive_info and self.archive_info.hashes: hash_algorithm, hash_value = next(iter(self.archive_info.hashes.items())) res["archive_info"]["hash"] = f"{hash_algorithm}={hash_value}" if strip_user_password: res["url"] = _strip_url(self.url, safe_user_passwords) return res
def validate(self) -> None: """Validate the DirectUrl instance against the specification.
Raises :class:`DirectUrlValidationError` if invalid. """ self.from_dict(self.to_dict())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from __future__ import annotations
import contextlibimport dataclassesimport sysimport typing
__all__ = ["ExceptionGroup"]
def __dir__() -> list[str]: return __all__
if sys.version_info >= (3, 11): # pragma: no cover from builtins import ExceptionGroupelse: # pragma: no cover
class ExceptionGroup(Exception): """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
If :external:exc:`ExceptionGroup` is already defined by Python itself, that version is used instead. """
message: str exceptions: list[Exception]
def __init__(self, message: str, exceptions: list[Exception]) -> None: self.message = message self.exceptions = exceptions
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
@dataclasses.dataclassclass _ErrorCollector: """ Collect errors into ExceptionGroups.
Used like this:
collector = _ErrorCollector() # Add a single exception collector.error(ValueError("one"))
# Supports nesting, including combining ExceptionGroups with collector.collect(): raise ValueError("two") collector.finalize("Found some errors")
Since making a collector and then calling finalize later is a common pattern, a convenience method ``on_exit`` is provided. """
errors: list[Exception] = dataclasses.field(default_factory=list, init=False)
def finalize(self, msg: str) -> None: """Raise a group exception if there are any errors.""" if self.errors: raise ExceptionGroup(msg, self.errors)
@contextlib.contextmanager def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]: """ Calls finalize if no uncollected errors were present.
Uncollected errors are raised normally. """ yield self self.finalize(msg)
@contextlib.contextmanager def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]: """ Context manager to collect errors into the error list.
Must be inside loops, as only one error can be collected at a time. """ error_classes = err_cls or (Exception,) try: yield except ExceptionGroup as error: self.errors.extend(error.exceptions) except error_classes as error: self.errors.append(error)
def error( self, error: Exception, ) -> None: """Add an error to the list.""" self.errors.append(error)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198######################################################################################### Adapted from:# https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py## MIT License## Copyright (c) 2017-present Ofek Lev <oss@ofek.dev>## 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.### With additional allowance of arbitrary `LicenseRef-` identifiers, not just# `LicenseRef-Public-Domain` and `LicenseRef-Proprietary`.########################################################################################from __future__ import annotations
import refrom typing import NewType, cast
from ._spdx import EXCEPTIONS, LICENSES
__all__ = [ "InvalidLicenseExpression", "NormalizedLicenseExpression", "canonicalize_license_expression",]
# Simple __dir__ implementation since there are no public submodulesdef __dir__() -> list[str]: return __all__
license_ref_allowed = re.compile("^[A-Za-z0-9.-]+$")
NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str)"""A :class:`typing.NewType` of :class:`str`, representing a normalizedLicense-Expression."""
class InvalidLicenseExpression(ValueError): """Raised when a license-expression string is invalid
>>> from packaging.licenses import canonicalize_license_expression >>> canonicalize_license_expression("invalid") Traceback (most recent call last): ... packaging.licenses.InvalidLicenseExpression: Unknown license: 'invalid' """
def canonicalize_license_expression( raw_license_expression: str,) -> NormalizedLicenseExpression: """ This function takes a valid License-Expression, and returns the normalized form of it.
The return type is typed as :class:`NormalizedLicenseExpression`. This allows type checkers to help require that a string has passed through this function before use.
:param str raw_license_expression: The License-Expression to canonicalize. :raises InvalidLicenseExpression: If the License-Expression is invalid due to an invalid/unknown license identifier or invalid syntax.
.. doctest::
>>> from packaging.licenses import canonicalize_license_expression >>> canonicalize_license_expression("mit") 'MIT' >>> canonicalize_license_expression("mit and (apache-2.0 or bsd-2-clause)") 'MIT AND (Apache-2.0 OR BSD-2-Clause)' >>> canonicalize_license_expression("(mit") Traceback (most recent call last): ... InvalidLicenseExpression: Invalid license expression: '(mit' >>> canonicalize_license_expression("Use-it-after-midnight") Traceback (most recent call last): ... InvalidLicenseExpression: Unknown license: 'Use-it-after-midnight' """ if not raw_license_expression: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message)
# Pad any parentheses so tokenization can be achieved by merely splitting on # whitespace. license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ") licenseref_prefix = "LicenseRef-" license_refs = { ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :] for ref in license_expression.split() if ref.lower().startswith(licenseref_prefix.lower()) }
# Normalize to lower case so we can look up licenses/exceptions # and so boolean operators are Python-compatible. license_expression = license_expression.lower()
tokens = license_expression.split()
# Rather than implementing a parenthesis/boolean logic parser, create an # expression that Python can parse. Everything that is not involved with the # grammar itself is replaced with the placeholder `False` and the resultant # expression should become a valid Python expression. python_tokens = [] for token in tokens: if token not in {"or", "and", "with", "(", ")"}: python_tokens.append("False") elif token == "with": python_tokens.append("or") elif ( token == "(" and python_tokens and python_tokens[-1] not in {"or", "and", "("} ) or (token == ")" and python_tokens and python_tokens[-1] == "("): message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) else: python_tokens.append(token)
python_expression = " ".join(python_tokens) try: compile(python_expression, "", "eval") except SyntaxError: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) from None
# Take a final pass to check for unknown licenses/exceptions. normalized_tokens = [] last_license_start = False for index, token in enumerate(tokens): if token in {"or", "and", "with", "(", ")"}: if token == "with" and ( not last_license_start or index + 1 == len(tokens) or tokens[index + 1] in {"or", "and", "with", "(", ")"} ): message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(token.upper()) last_license_start = False continue
if normalized_tokens and normalized_tokens[-1] == "WITH": if token not in EXCEPTIONS: message = f"Unknown license exception: {token!r}" raise InvalidLicenseExpression(message)
normalized_tokens.append(EXCEPTIONS[token]["id"]) last_license_start = False else: if token.endswith("+"): final_token = token[:-1] suffix = "+" else: final_token = token suffix = ""
if final_token.startswith("licenseref-"): license_ref_id = final_token[len("licenseref-") :] if suffix or not license_ref_allowed.match(license_ref_id): message = f"Invalid licenseref: {token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(license_refs[final_token]) else: if final_token not in LICENSES: message = f"Unknown license: {final_token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(LICENSES[final_token]["id"] + suffix) last_license_start = True
normalized_expression = " ".join(normalized_tokens)
return cast( "NormalizedLicenseExpression", normalized_expression.replace("( ", "(").replace(" )", ")"), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
from __future__ import annotations
from typing import TypedDict
class SPDXLicense(TypedDict): id: str deprecated: bool
class SPDXException(TypedDict): id: str deprecated: bool
VERSION = '3.27.0'
LICENSES: dict[str, SPDXLicense] = { '0bsd': {'id': '0BSD', 'deprecated': False}, '3d-slicer-1.0': {'id': '3D-Slicer-1.0', 'deprecated': False}, 'aal': {'id': 'AAL', 'deprecated': False}, 'abstyles': {'id': 'Abstyles', 'deprecated': False}, 'adacore-doc': {'id': 'AdaCore-doc', 'deprecated': False}, 'adobe-2006': {'id': 'Adobe-2006', 'deprecated': False}, 'adobe-display-postscript': {'id': 'Adobe-Display-PostScript', 'deprecated': False}, 'adobe-glyph': {'id': 'Adobe-Glyph', 'deprecated': False}, 'adobe-utopia': {'id': 'Adobe-Utopia', 'deprecated': False}, 'adsl': {'id': 'ADSL', 'deprecated': False}, 'afl-1.1': {'id': 'AFL-1.1', 'deprecated': False}, 'afl-1.2': {'id': 'AFL-1.2', 'deprecated': False}, 'afl-2.0': {'id': 'AFL-2.0', 'deprecated': False}, 'afl-2.1': {'id': 'AFL-2.1', 'deprecated': False}, 'afl-3.0': {'id': 'AFL-3.0', 'deprecated': False}, 'afmparse': {'id': 'Afmparse', 'deprecated': False}, 'agpl-1.0': {'id': 'AGPL-1.0', 'deprecated': True}, 'agpl-1.0-only': {'id': 'AGPL-1.0-only', 'deprecated': False}, 'agpl-1.0-or-later': {'id': 'AGPL-1.0-or-later', 'deprecated': False}, 'agpl-3.0': {'id': 'AGPL-3.0', 'deprecated': True}, 'agpl-3.0-only': {'id': 'AGPL-3.0-only', 'deprecated': False}, 'agpl-3.0-or-later': {'id': 'AGPL-3.0-or-later', 'deprecated': False}, 'aladdin': {'id': 'Aladdin', 'deprecated': False}, 'amd-newlib': {'id': 'AMD-newlib', 'deprecated': False}, 'amdplpa': {'id': 'AMDPLPA', 'deprecated': False}, 'aml': {'id': 'AML', 'deprecated': False}, 'aml-glslang': {'id': 'AML-glslang', 'deprecated': False}, 'ampas': {'id': 'AMPAS', 'deprecated': False}, 'antlr-pd': {'id': 'ANTLR-PD', 'deprecated': False}, 'antlr-pd-fallback': {'id': 'ANTLR-PD-fallback', 'deprecated': False}, 'any-osi': {'id': 'any-OSI', 'deprecated': False}, 'any-osi-perl-modules': {'id': 'any-OSI-perl-modules', 'deprecated': False}, 'apache-1.0': {'id': 'Apache-1.0', 'deprecated': False}, 'apache-1.1': {'id': 'Apache-1.1', 'deprecated': False}, 'apache-2.0': {'id': 'Apache-2.0', 'deprecated': False}, 'apafml': {'id': 'APAFML', 'deprecated': False}, 'apl-1.0': {'id': 'APL-1.0', 'deprecated': False}, 'app-s2p': {'id': 'App-s2p', 'deprecated': False}, 'apsl-1.0': {'id': 'APSL-1.0', 'deprecated': False}, 'apsl-1.1': {'id': 'APSL-1.1', 'deprecated': False}, 'apsl-1.2': {'id': 'APSL-1.2', 'deprecated': False}, 'apsl-2.0': {'id': 'APSL-2.0', 'deprecated': False}, 'arphic-1999': {'id': 'Arphic-1999', 'deprecated': False}, 'artistic-1.0': {'id': 'Artistic-1.0', 'deprecated': False}, 'artistic-1.0-cl8': {'id': 'Artistic-1.0-cl8', 'deprecated': False}, 'artistic-1.0-perl': {'id': 'Artistic-1.0-Perl', 'deprecated': False}, 'artistic-2.0': {'id': 'Artistic-2.0', 'deprecated': False}, 'artistic-dist': {'id': 'Artistic-dist', 'deprecated': False}, 'aspell-ru': {'id': 'Aspell-RU', 'deprecated': False}, 'aswf-digital-assets-1.0': {'id': 'ASWF-Digital-Assets-1.0', 'deprecated': False}, 'aswf-digital-assets-1.1': {'id': 'ASWF-Digital-Assets-1.1', 'deprecated': False}, 'baekmuk': {'id': 'Baekmuk', 'deprecated': False}, 'bahyph': {'id': 'Bahyph', 'deprecated': False}, 'barr': {'id': 'Barr', 'deprecated': False}, 'bcrypt-solar-designer': {'id': 'bcrypt-Solar-Designer', 'deprecated': False}, 'beerware': {'id': 'Beerware', 'deprecated': False}, 'bitstream-charter': {'id': 'Bitstream-Charter', 'deprecated': False}, 'bitstream-vera': {'id': 'Bitstream-Vera', 'deprecated': False}, 'bittorrent-1.0': {'id': 'BitTorrent-1.0', 'deprecated': False}, 'bittorrent-1.1': {'id': 'BitTorrent-1.1', 'deprecated': False}, 'blessing': {'id': 'blessing', 'deprecated': False}, 'blueoak-1.0.0': {'id': 'BlueOak-1.0.0', 'deprecated': False}, 'boehm-gc': {'id': 'Boehm-GC', 'deprecated': False}, 'boehm-gc-without-fee': {'id': 'Boehm-GC-without-fee', 'deprecated': False}, 'borceux': {'id': 'Borceux', 'deprecated': False}, 'brian-gladman-2-clause': {'id': 'Brian-Gladman-2-Clause', 'deprecated': False}, 'brian-gladman-3-clause': {'id': 'Brian-Gladman-3-Clause', 'deprecated': False}, 'bsd-1-clause': {'id': 'BSD-1-Clause', 'deprecated': False}, 'bsd-2-clause': {'id': 'BSD-2-Clause', 'deprecated': False}, 'bsd-2-clause-darwin': {'id': 'BSD-2-Clause-Darwin', 'deprecated': False}, 'bsd-2-clause-first-lines': {'id': 'BSD-2-Clause-first-lines', 'deprecated': False}, 'bsd-2-clause-freebsd': {'id': 'BSD-2-Clause-FreeBSD', 'deprecated': True}, 'bsd-2-clause-netbsd': {'id': 'BSD-2-Clause-NetBSD', 'deprecated': True}, 'bsd-2-clause-patent': {'id': 'BSD-2-Clause-Patent', 'deprecated': False}, 'bsd-2-clause-pkgconf-disclaimer': {'id': 'BSD-2-Clause-pkgconf-disclaimer', 'deprecated': False}, 'bsd-2-clause-views': {'id': 'BSD-2-Clause-Views', 'deprecated': False}, 'bsd-3-clause': {'id': 'BSD-3-Clause', 'deprecated': False}, 'bsd-3-clause-acpica': {'id': 'BSD-3-Clause-acpica', 'deprecated': False}, 'bsd-3-clause-attribution': {'id': 'BSD-3-Clause-Attribution', 'deprecated': False}, 'bsd-3-clause-clear': {'id': 'BSD-3-Clause-Clear', 'deprecated': False}, 'bsd-3-clause-flex': {'id': 'BSD-3-Clause-flex', 'deprecated': False}, 'bsd-3-clause-hp': {'id': 'BSD-3-Clause-HP', 'deprecated': False}, 'bsd-3-clause-lbnl': {'id': 'BSD-3-Clause-LBNL', 'deprecated': False}, 'bsd-3-clause-modification': {'id': 'BSD-3-Clause-Modification', 'deprecated': False}, 'bsd-3-clause-no-military-license': {'id': 'BSD-3-Clause-No-Military-License', 'deprecated': False}, 'bsd-3-clause-no-nuclear-license': {'id': 'BSD-3-Clause-No-Nuclear-License', 'deprecated': False}, 'bsd-3-clause-no-nuclear-license-2014': {'id': 'BSD-3-Clause-No-Nuclear-License-2014', 'deprecated': False}, 'bsd-3-clause-no-nuclear-warranty': {'id': 'BSD-3-Clause-No-Nuclear-Warranty', 'deprecated': False}, 'bsd-3-clause-open-mpi': {'id': 'BSD-3-Clause-Open-MPI', 'deprecated': False}, 'bsd-3-clause-sun': {'id': 'BSD-3-Clause-Sun', 'deprecated': False}, 'bsd-4-clause': {'id': 'BSD-4-Clause', 'deprecated': False}, 'bsd-4-clause-shortened': {'id': 'BSD-4-Clause-Shortened', 'deprecated': False}, 'bsd-4-clause-uc': {'id': 'BSD-4-Clause-UC', 'deprecated': False}, 'bsd-4.3reno': {'id': 'BSD-4.3RENO', 'deprecated': False}, 'bsd-4.3tahoe': {'id': 'BSD-4.3TAHOE', 'deprecated': False}, 'bsd-advertising-acknowledgement': {'id': 'BSD-Advertising-Acknowledgement', 'deprecated': False}, 'bsd-attribution-hpnd-disclaimer': {'id': 'BSD-Attribution-HPND-disclaimer', 'deprecated': False}, 'bsd-inferno-nettverk': {'id': 'BSD-Inferno-Nettverk', 'deprecated': False}, 'bsd-protection': {'id': 'BSD-Protection', 'deprecated': False}, 'bsd-source-beginning-file': {'id': 'BSD-Source-beginning-file', 'deprecated': False}, 'bsd-source-code': {'id': 'BSD-Source-Code', 'deprecated': False}, 'bsd-systemics': {'id': 'BSD-Systemics', 'deprecated': False}, 'bsd-systemics-w3works': {'id': 'BSD-Systemics-W3Works', 'deprecated': False}, 'bsl-1.0': {'id': 'BSL-1.0', 'deprecated': False}, 'busl-1.1': {'id': 'BUSL-1.1', 'deprecated': False}, 'bzip2-1.0.5': {'id': 'bzip2-1.0.5', 'deprecated': True}, 'bzip2-1.0.6': {'id': 'bzip2-1.0.6', 'deprecated': False}, 'c-uda-1.0': {'id': 'C-UDA-1.0', 'deprecated': False}, 'cal-1.0': {'id': 'CAL-1.0', 'deprecated': False}, 'cal-1.0-combined-work-exception': {'id': 'CAL-1.0-Combined-Work-Exception', 'deprecated': False}, 'caldera': {'id': 'Caldera', 'deprecated': False}, 'caldera-no-preamble': {'id': 'Caldera-no-preamble', 'deprecated': False}, 'catharon': {'id': 'Catharon', 'deprecated': False}, 'catosl-1.1': {'id': 'CATOSL-1.1', 'deprecated': False}, 'cc-by-1.0': {'id': 'CC-BY-1.0', 'deprecated': False}, 'cc-by-2.0': {'id': 'CC-BY-2.0', 'deprecated': False}, 'cc-by-2.5': {'id': 'CC-BY-2.5', 'deprecated': False}, 'cc-by-2.5-au': {'id': 'CC-BY-2.5-AU', 'deprecated': False}, 'cc-by-3.0': {'id': 'CC-BY-3.0', 'deprecated': False}, 'cc-by-3.0-at': {'id': 'CC-BY-3.0-AT', 'deprecated': False}, 'cc-by-3.0-au': {'id': 'CC-BY-3.0-AU', 'deprecated': False}, 'cc-by-3.0-de': {'id': 'CC-BY-3.0-DE', 'deprecated': False}, 'cc-by-3.0-igo': {'id': 'CC-BY-3.0-IGO', 'deprecated': False}, 'cc-by-3.0-nl': {'id': 'CC-BY-3.0-NL', 'deprecated': False}, 'cc-by-3.0-us': {'id': 'CC-BY-3.0-US', 'deprecated': False}, 'cc-by-4.0': {'id': 'CC-BY-4.0', 'deprecated': False}, 'cc-by-nc-1.0': {'id': 'CC-BY-NC-1.0', 'deprecated': False}, 'cc-by-nc-2.0': {'id': 'CC-BY-NC-2.0', 'deprecated': False}, 'cc-by-nc-2.5': {'id': 'CC-BY-NC-2.5', 'deprecated': False}, 'cc-by-nc-3.0': {'id': 'CC-BY-NC-3.0', 'deprecated': False}, 'cc-by-nc-3.0-de': {'id': 'CC-BY-NC-3.0-DE', 'deprecated': False}, 'cc-by-nc-4.0': {'id': 'CC-BY-NC-4.0', 'deprecated': False}, 'cc-by-nc-nd-1.0': {'id': 'CC-BY-NC-ND-1.0', 'deprecated': False}, 'cc-by-nc-nd-2.0': {'id': 'CC-BY-NC-ND-2.0', 'deprecated': False}, 'cc-by-nc-nd-2.5': {'id': 'CC-BY-NC-ND-2.5', 'deprecated': False}, 'cc-by-nc-nd-3.0': {'id': 'CC-BY-NC-ND-3.0', 'deprecated': False}, 'cc-by-nc-nd-3.0-de': {'id': 'CC-BY-NC-ND-3.0-DE', 'deprecated': False}, 'cc-by-nc-nd-3.0-igo': {'id': 'CC-BY-NC-ND-3.0-IGO', 'deprecated': False}, 'cc-by-nc-nd-4.0': {'id': 'CC-BY-NC-ND-4.0', 'deprecated': False}, 'cc-by-nc-sa-1.0': {'id': 'CC-BY-NC-SA-1.0', 'deprecated': False}, 'cc-by-nc-sa-2.0': {'id': 'CC-BY-NC-SA-2.0', 'deprecated': False}, 'cc-by-nc-sa-2.0-de': {'id': 'CC-BY-NC-SA-2.0-DE', 'deprecated': False}, 'cc-by-nc-sa-2.0-fr': {'id': 'CC-BY-NC-SA-2.0-FR', 'deprecated': False}, 'cc-by-nc-sa-2.0-uk': {'id': 'CC-BY-NC-SA-2.0-UK', 'deprecated': False}, 'cc-by-nc-sa-2.5': {'id': 'CC-BY-NC-SA-2.5', 'deprecated': False}, 'cc-by-nc-sa-3.0': {'id': 'CC-BY-NC-SA-3.0', 'deprecated': False}, 'cc-by-nc-sa-3.0-de': {'id': 'CC-BY-NC-SA-3.0-DE', 'deprecated': False}, 'cc-by-nc-sa-3.0-igo': {'id': 'CC-BY-NC-SA-3.0-IGO', 'deprecated': False}, 'cc-by-nc-sa-4.0': {'id': 'CC-BY-NC-SA-4.0', 'deprecated': False}, 'cc-by-nd-1.0': {'id': 'CC-BY-ND-1.0', 'deprecated': False}, 'cc-by-nd-2.0': {'id': 'CC-BY-ND-2.0', 'deprecated': False}, 'cc-by-nd-2.5': {'id': 'CC-BY-ND-2.5', 'deprecated': False}, 'cc-by-nd-3.0': {'id': 'CC-BY-ND-3.0', 'deprecated': False}, 'cc-by-nd-3.0-de': {'id': 'CC-BY-ND-3.0-DE', 'deprecated': False}, 'cc-by-nd-4.0': {'id': 'CC-BY-ND-4.0', 'deprecated': False}, 'cc-by-sa-1.0': {'id': 'CC-BY-SA-1.0', 'deprecated': False}, 'cc-by-sa-2.0': {'id': 'CC-BY-SA-2.0', 'deprecated': False}, 'cc-by-sa-2.0-uk': {'id': 'CC-BY-SA-2.0-UK', 'deprecated': False}, 'cc-by-sa-2.1-jp': {'id': 'CC-BY-SA-2.1-JP', 'deprecated': False}, 'cc-by-sa-2.5': {'id': 'CC-BY-SA-2.5', 'deprecated': False}, 'cc-by-sa-3.0': {'id': 'CC-BY-SA-3.0', 'deprecated': False}, 'cc-by-sa-3.0-at': {'id': 'CC-BY-SA-3.0-AT', 'deprecated': False}, 'cc-by-sa-3.0-de': {'id': 'CC-BY-SA-3.0-DE', 'deprecated': False}, 'cc-by-sa-3.0-igo': {'id': 'CC-BY-SA-3.0-IGO', 'deprecated': False}, 'cc-by-sa-4.0': {'id': 'CC-BY-SA-4.0', 'deprecated': False}, 'cc-pddc': {'id': 'CC-PDDC', 'deprecated': False}, 'cc-pdm-1.0': {'id': 'CC-PDM-1.0', 'deprecated': False}, 'cc-sa-1.0': {'id': 'CC-SA-1.0', 'deprecated': False}, 'cc0-1.0': {'id': 'CC0-1.0', 'deprecated': False}, 'cddl-1.0': {'id': 'CDDL-1.0', 'deprecated': False}, 'cddl-1.1': {'id': 'CDDL-1.1', 'deprecated': False}, 'cdl-1.0': {'id': 'CDL-1.0', 'deprecated': False}, 'cdla-permissive-1.0': {'id': 'CDLA-Permissive-1.0', 'deprecated': False}, 'cdla-permissive-2.0': {'id': 'CDLA-Permissive-2.0', 'deprecated': False}, 'cdla-sharing-1.0': {'id': 'CDLA-Sharing-1.0', 'deprecated': False}, 'cecill-1.0': {'id': 'CECILL-1.0', 'deprecated': False}, 'cecill-1.1': {'id': 'CECILL-1.1', 'deprecated': False}, 'cecill-2.0': {'id': 'CECILL-2.0', 'deprecated': False}, 'cecill-2.1': {'id': 'CECILL-2.1', 'deprecated': False}, 'cecill-b': {'id': 'CECILL-B', 'deprecated': False}, 'cecill-c': {'id': 'CECILL-C', 'deprecated': False}, 'cern-ohl-1.1': {'id': 'CERN-OHL-1.1', 'deprecated': False}, 'cern-ohl-1.2': {'id': 'CERN-OHL-1.2', 'deprecated': False}, 'cern-ohl-p-2.0': {'id': 'CERN-OHL-P-2.0', 'deprecated': False}, 'cern-ohl-s-2.0': {'id': 'CERN-OHL-S-2.0', 'deprecated': False}, 'cern-ohl-w-2.0': {'id': 'CERN-OHL-W-2.0', 'deprecated': False}, 'cfitsio': {'id': 'CFITSIO', 'deprecated': False}, 'check-cvs': {'id': 'check-cvs', 'deprecated': False}, 'checkmk': {'id': 'checkmk', 'deprecated': False}, 'clartistic': {'id': 'ClArtistic', 'deprecated': False}, 'clips': {'id': 'Clips', 'deprecated': False}, 'cmu-mach': {'id': 'CMU-Mach', 'deprecated': False}, 'cmu-mach-nodoc': {'id': 'CMU-Mach-nodoc', 'deprecated': False}, 'cnri-jython': {'id': 'CNRI-Jython', 'deprecated': False}, 'cnri-python': {'id': 'CNRI-Python', 'deprecated': False}, 'cnri-python-gpl-compatible': {'id': 'CNRI-Python-GPL-Compatible', 'deprecated': False}, 'coil-1.0': {'id': 'COIL-1.0', 'deprecated': False}, 'community-spec-1.0': {'id': 'Community-Spec-1.0', 'deprecated': False}, 'condor-1.1': {'id': 'Condor-1.1', 'deprecated': False}, 'copyleft-next-0.3.0': {'id': 'copyleft-next-0.3.0', 'deprecated': False}, 'copyleft-next-0.3.1': {'id': 'copyleft-next-0.3.1', 'deprecated': False}, 'cornell-lossless-jpeg': {'id': 'Cornell-Lossless-JPEG', 'deprecated': False}, 'cpal-1.0': {'id': 'CPAL-1.0', 'deprecated': False}, 'cpl-1.0': {'id': 'CPL-1.0', 'deprecated': False}, 'cpol-1.02': {'id': 'CPOL-1.02', 'deprecated': False}, 'cronyx': {'id': 'Cronyx', 'deprecated': False}, 'crossword': {'id': 'Crossword', 'deprecated': False}, 'cryptoswift': {'id': 'CryptoSwift', 'deprecated': False}, 'crystalstacker': {'id': 'CrystalStacker', 'deprecated': False}, 'cua-opl-1.0': {'id': 'CUA-OPL-1.0', 'deprecated': False}, 'cube': {'id': 'Cube', 'deprecated': False}, 'curl': {'id': 'curl', 'deprecated': False}, 'cve-tou': {'id': 'cve-tou', 'deprecated': False}, 'd-fsl-1.0': {'id': 'D-FSL-1.0', 'deprecated': False}, 'dec-3-clause': {'id': 'DEC-3-Clause', 'deprecated': False}, 'diffmark': {'id': 'diffmark', 'deprecated': False}, 'dl-de-by-2.0': {'id': 'DL-DE-BY-2.0', 'deprecated': False}, 'dl-de-zero-2.0': {'id': 'DL-DE-ZERO-2.0', 'deprecated': False}, 'doc': {'id': 'DOC', 'deprecated': False}, 'docbook-dtd': {'id': 'DocBook-DTD', 'deprecated': False}, 'docbook-schema': {'id': 'DocBook-Schema', 'deprecated': False}, 'docbook-stylesheet': {'id': 'DocBook-Stylesheet', 'deprecated': False}, 'docbook-xml': {'id': 'DocBook-XML', 'deprecated': False}, 'dotseqn': {'id': 'Dotseqn', 'deprecated': False}, 'drl-1.0': {'id': 'DRL-1.0', 'deprecated': False}, 'drl-1.1': {'id': 'DRL-1.1', 'deprecated': False}, 'dsdp': {'id': 'DSDP', 'deprecated': False}, 'dtoa': {'id': 'dtoa', 'deprecated': False}, 'dvipdfm': {'id': 'dvipdfm', 'deprecated': False}, 'ecl-1.0': {'id': 'ECL-1.0', 'deprecated': False}, 'ecl-2.0': {'id': 'ECL-2.0', 'deprecated': False}, 'ecos-2.0': {'id': 'eCos-2.0', 'deprecated': True}, 'efl-1.0': {'id': 'EFL-1.0', 'deprecated': False}, 'efl-2.0': {'id': 'EFL-2.0', 'deprecated': False}, 'egenix': {'id': 'eGenix', 'deprecated': False}, 'elastic-2.0': {'id': 'Elastic-2.0', 'deprecated': False}, 'entessa': {'id': 'Entessa', 'deprecated': False}, 'epics': {'id': 'EPICS', 'deprecated': False}, 'epl-1.0': {'id': 'EPL-1.0', 'deprecated': False}, 'epl-2.0': {'id': 'EPL-2.0', 'deprecated': False}, 'erlpl-1.1': {'id': 'ErlPL-1.1', 'deprecated': False}, 'etalab-2.0': {'id': 'etalab-2.0', 'deprecated': False}, 'eudatagrid': {'id': 'EUDatagrid', 'deprecated': False}, 'eupl-1.0': {'id': 'EUPL-1.0', 'deprecated': False}, 'eupl-1.1': {'id': 'EUPL-1.1', 'deprecated': False}, 'eupl-1.2': {'id': 'EUPL-1.2', 'deprecated': False}, 'eurosym': {'id': 'Eurosym', 'deprecated': False}, 'fair': {'id': 'Fair', 'deprecated': False}, 'fbm': {'id': 'FBM', 'deprecated': False}, 'fdk-aac': {'id': 'FDK-AAC', 'deprecated': False}, 'ferguson-twofish': {'id': 'Ferguson-Twofish', 'deprecated': False}, 'frameworx-1.0': {'id': 'Frameworx-1.0', 'deprecated': False}, 'freebsd-doc': {'id': 'FreeBSD-DOC', 'deprecated': False}, 'freeimage': {'id': 'FreeImage', 'deprecated': False}, 'fsfap': {'id': 'FSFAP', 'deprecated': False}, 'fsfap-no-warranty-disclaimer': {'id': 'FSFAP-no-warranty-disclaimer', 'deprecated': False}, 'fsful': {'id': 'FSFUL', 'deprecated': False}, 'fsfullr': {'id': 'FSFULLR', 'deprecated': False}, 'fsfullrsd': {'id': 'FSFULLRSD', 'deprecated': False}, 'fsfullrwd': {'id': 'FSFULLRWD', 'deprecated': False}, 'fsl-1.1-alv2': {'id': 'FSL-1.1-ALv2', 'deprecated': False}, 'fsl-1.1-mit': {'id': 'FSL-1.1-MIT', 'deprecated': False}, 'ftl': {'id': 'FTL', 'deprecated': False}, 'furuseth': {'id': 'Furuseth', 'deprecated': False}, 'fwlw': {'id': 'fwlw', 'deprecated': False}, 'game-programming-gems': {'id': 'Game-Programming-Gems', 'deprecated': False}, 'gcr-docs': {'id': 'GCR-docs', 'deprecated': False}, 'gd': {'id': 'GD', 'deprecated': False}, 'generic-xts': {'id': 'generic-xts', 'deprecated': False}, 'gfdl-1.1': {'id': 'GFDL-1.1', 'deprecated': True}, 'gfdl-1.1-invariants-only': {'id': 'GFDL-1.1-invariants-only', 'deprecated': False}, 'gfdl-1.1-invariants-or-later': {'id': 'GFDL-1.1-invariants-or-later', 'deprecated': False}, 'gfdl-1.1-no-invariants-only': {'id': 'GFDL-1.1-no-invariants-only', 'deprecated': False}, 'gfdl-1.1-no-invariants-or-later': {'id': 'GFDL-1.1-no-invariants-or-later', 'deprecated': False}, 'gfdl-1.1-only': {'id': 'GFDL-1.1-only', 'deprecated': False}, 'gfdl-1.1-or-later': {'id': 'GFDL-1.1-or-later', 'deprecated': False}, 'gfdl-1.2': {'id': 'GFDL-1.2', 'deprecated': True}, 'gfdl-1.2-invariants-only': {'id': 'GFDL-1.2-invariants-only', 'deprecated': False}, 'gfdl-1.2-invariants-or-later': {'id': 'GFDL-1.2-invariants-or-later', 'deprecated': False}, 'gfdl-1.2-no-invariants-only': {'id': 'GFDL-1.2-no-invariants-only', 'deprecated': False}, 'gfdl-1.2-no-invariants-or-later': {'id': 'GFDL-1.2-no-invariants-or-later', 'deprecated': False}, 'gfdl-1.2-only': {'id': 'GFDL-1.2-only', 'deprecated': False}, 'gfdl-1.2-or-later': {'id': 'GFDL-1.2-or-later', 'deprecated': False}, 'gfdl-1.3': {'id': 'GFDL-1.3', 'deprecated': True}, 'gfdl-1.3-invariants-only': {'id': 'GFDL-1.3-invariants-only', 'deprecated': False}, 'gfdl-1.3-invariants-or-later': {'id': 'GFDL-1.3-invariants-or-later', 'deprecated': False}, 'gfdl-1.3-no-invariants-only': {'id': 'GFDL-1.3-no-invariants-only', 'deprecated': False}, 'gfdl-1.3-no-invariants-or-later': {'id': 'GFDL-1.3-no-invariants-or-later', 'deprecated': False}, 'gfdl-1.3-only': {'id': 'GFDL-1.3-only', 'deprecated': False}, 'gfdl-1.3-or-later': {'id': 'GFDL-1.3-or-later', 'deprecated': False}, 'giftware': {'id': 'Giftware', 'deprecated': False}, 'gl2ps': {'id': 'GL2PS', 'deprecated': False}, 'glide': {'id': 'Glide', 'deprecated': False}, 'glulxe': {'id': 'Glulxe', 'deprecated': False}, 'glwtpl': {'id': 'GLWTPL', 'deprecated': False}, 'gnuplot': {'id': 'gnuplot', 'deprecated': False}, 'gpl-1.0': {'id': 'GPL-1.0', 'deprecated': True}, 'gpl-1.0+': {'id': 'GPL-1.0+', 'deprecated': True}, 'gpl-1.0-only': {'id': 'GPL-1.0-only', 'deprecated': False}, 'gpl-1.0-or-later': {'id': 'GPL-1.0-or-later', 'deprecated': False}, 'gpl-2.0': {'id': 'GPL-2.0', 'deprecated': True}, 'gpl-2.0+': {'id': 'GPL-2.0+', 'deprecated': True}, 'gpl-2.0-only': {'id': 'GPL-2.0-only', 'deprecated': False}, 'gpl-2.0-or-later': {'id': 'GPL-2.0-or-later', 'deprecated': False}, 'gpl-2.0-with-autoconf-exception': {'id': 'GPL-2.0-with-autoconf-exception', 'deprecated': True}, 'gpl-2.0-with-bison-exception': {'id': 'GPL-2.0-with-bison-exception', 'deprecated': True}, 'gpl-2.0-with-classpath-exception': {'id': 'GPL-2.0-with-classpath-exception', 'deprecated': True}, 'gpl-2.0-with-font-exception': {'id': 'GPL-2.0-with-font-exception', 'deprecated': True}, 'gpl-2.0-with-gcc-exception': {'id': 'GPL-2.0-with-GCC-exception', 'deprecated': True}, 'gpl-3.0': {'id': 'GPL-3.0', 'deprecated': True}, 'gpl-3.0+': {'id': 'GPL-3.0+', 'deprecated': True}, 'gpl-3.0-only': {'id': 'GPL-3.0-only', 'deprecated': False}, 'gpl-3.0-or-later': {'id': 'GPL-3.0-or-later', 'deprecated': False}, 'gpl-3.0-with-autoconf-exception': {'id': 'GPL-3.0-with-autoconf-exception', 'deprecated': True}, 'gpl-3.0-with-gcc-exception': {'id': 'GPL-3.0-with-GCC-exception', 'deprecated': True}, 'graphics-gems': {'id': 'Graphics-Gems', 'deprecated': False}, 'gsoap-1.3b': {'id': 'gSOAP-1.3b', 'deprecated': False}, 'gtkbook': {'id': 'gtkbook', 'deprecated': False}, 'gutmann': {'id': 'Gutmann', 'deprecated': False}, 'haskellreport': {'id': 'HaskellReport', 'deprecated': False}, 'hdf5': {'id': 'HDF5', 'deprecated': False}, 'hdparm': {'id': 'hdparm', 'deprecated': False}, 'hidapi': {'id': 'HIDAPI', 'deprecated': False}, 'hippocratic-2.1': {'id': 'Hippocratic-2.1', 'deprecated': False}, 'hp-1986': {'id': 'HP-1986', 'deprecated': False}, 'hp-1989': {'id': 'HP-1989', 'deprecated': False}, 'hpnd': {'id': 'HPND', 'deprecated': False}, 'hpnd-dec': {'id': 'HPND-DEC', 'deprecated': False}, 'hpnd-doc': {'id': 'HPND-doc', 'deprecated': False}, 'hpnd-doc-sell': {'id': 'HPND-doc-sell', 'deprecated': False}, 'hpnd-export-us': {'id': 'HPND-export-US', 'deprecated': False}, 'hpnd-export-us-acknowledgement': {'id': 'HPND-export-US-acknowledgement', 'deprecated': False}, 'hpnd-export-us-modify': {'id': 'HPND-export-US-modify', 'deprecated': False}, 'hpnd-export2-us': {'id': 'HPND-export2-US', 'deprecated': False}, 'hpnd-fenneberg-livingston': {'id': 'HPND-Fenneberg-Livingston', 'deprecated': False}, 'hpnd-inria-imag': {'id': 'HPND-INRIA-IMAG', 'deprecated': False}, 'hpnd-intel': {'id': 'HPND-Intel', 'deprecated': False}, 'hpnd-kevlin-henney': {'id': 'HPND-Kevlin-Henney', 'deprecated': False}, 'hpnd-markus-kuhn': {'id': 'HPND-Markus-Kuhn', 'deprecated': False}, 'hpnd-merchantability-variant': {'id': 'HPND-merchantability-variant', 'deprecated': False}, 'hpnd-mit-disclaimer': {'id': 'HPND-MIT-disclaimer', 'deprecated': False}, 'hpnd-netrek': {'id': 'HPND-Netrek', 'deprecated': False}, 'hpnd-pbmplus': {'id': 'HPND-Pbmplus', 'deprecated': False}, 'hpnd-sell-mit-disclaimer-xserver': {'id': 'HPND-sell-MIT-disclaimer-xserver', 'deprecated': False}, 'hpnd-sell-regexpr': {'id': 'HPND-sell-regexpr', 'deprecated': False}, 'hpnd-sell-variant': {'id': 'HPND-sell-variant', 'deprecated': False}, 'hpnd-sell-variant-mit-disclaimer': {'id': 'HPND-sell-variant-MIT-disclaimer', 'deprecated': False}, 'hpnd-sell-variant-mit-disclaimer-rev': {'id': 'HPND-sell-variant-MIT-disclaimer-rev', 'deprecated': False}, 'hpnd-uc': {'id': 'HPND-UC', 'deprecated': False}, 'hpnd-uc-export-us': {'id': 'HPND-UC-export-US', 'deprecated': False}, 'htmltidy': {'id': 'HTMLTIDY', 'deprecated': False}, 'ibm-pibs': {'id': 'IBM-pibs', 'deprecated': False}, 'icu': {'id': 'ICU', 'deprecated': False}, 'iec-code-components-eula': {'id': 'IEC-Code-Components-EULA', 'deprecated': False}, 'ijg': {'id': 'IJG', 'deprecated': False}, 'ijg-short': {'id': 'IJG-short', 'deprecated': False}, 'imagemagick': {'id': 'ImageMagick', 'deprecated': False}, 'imatix': {'id': 'iMatix', 'deprecated': False}, 'imlib2': {'id': 'Imlib2', 'deprecated': False}, 'info-zip': {'id': 'Info-ZIP', 'deprecated': False}, 'inner-net-2.0': {'id': 'Inner-Net-2.0', 'deprecated': False}, 'innosetup': {'id': 'InnoSetup', 'deprecated': False}, 'intel': {'id': 'Intel', 'deprecated': False}, 'intel-acpi': {'id': 'Intel-ACPI', 'deprecated': False}, 'interbase-1.0': {'id': 'Interbase-1.0', 'deprecated': False}, 'ipa': {'id': 'IPA', 'deprecated': False}, 'ipl-1.0': {'id': 'IPL-1.0', 'deprecated': False}, 'isc': {'id': 'ISC', 'deprecated': False}, 'isc-veillard': {'id': 'ISC-Veillard', 'deprecated': False}, 'jam': {'id': 'Jam', 'deprecated': False}, 'jasper-2.0': {'id': 'JasPer-2.0', 'deprecated': False}, 'jove': {'id': 'jove', 'deprecated': False}, 'jpl-image': {'id': 'JPL-image', 'deprecated': False}, 'jpnic': {'id': 'JPNIC', 'deprecated': False}, 'json': {'id': 'JSON', 'deprecated': False}, 'kastrup': {'id': 'Kastrup', 'deprecated': False}, 'kazlib': {'id': 'Kazlib', 'deprecated': False}, 'knuth-ctan': {'id': 'Knuth-CTAN', 'deprecated': False}, 'lal-1.2': {'id': 'LAL-1.2', 'deprecated': False}, 'lal-1.3': {'id': 'LAL-1.3', 'deprecated': False}, 'latex2e': {'id': 'Latex2e', 'deprecated': False}, 'latex2e-translated-notice': {'id': 'Latex2e-translated-notice', 'deprecated': False}, 'leptonica': {'id': 'Leptonica', 'deprecated': False}, 'lgpl-2.0': {'id': 'LGPL-2.0', 'deprecated': True}, 'lgpl-2.0+': {'id': 'LGPL-2.0+', 'deprecated': True}, 'lgpl-2.0-only': {'id': 'LGPL-2.0-only', 'deprecated': False}, 'lgpl-2.0-or-later': {'id': 'LGPL-2.0-or-later', 'deprecated': False}, 'lgpl-2.1': {'id': 'LGPL-2.1', 'deprecated': True}, 'lgpl-2.1+': {'id': 'LGPL-2.1+', 'deprecated': True}, 'lgpl-2.1-only': {'id': 'LGPL-2.1-only', 'deprecated': False}, 'lgpl-2.1-or-later': {'id': 'LGPL-2.1-or-later', 'deprecated': False}, 'lgpl-3.0': {'id': 'LGPL-3.0', 'deprecated': True}, 'lgpl-3.0+': {'id': 'LGPL-3.0+', 'deprecated': True}, 'lgpl-3.0-only': {'id': 'LGPL-3.0-only', 'deprecated': False}, 'lgpl-3.0-or-later': {'id': 'LGPL-3.0-or-later', 'deprecated': False}, 'lgpllr': {'id': 'LGPLLR', 'deprecated': False}, 'libpng': {'id': 'Libpng', 'deprecated': False}, 'libpng-1.6.35': {'id': 'libpng-1.6.35', 'deprecated': False}, 'libpng-2.0': {'id': 'libpng-2.0', 'deprecated': False}, 'libselinux-1.0': {'id': 'libselinux-1.0', 'deprecated': False}, 'libtiff': {'id': 'libtiff', 'deprecated': False}, 'libutil-david-nugent': {'id': 'libutil-David-Nugent', 'deprecated': False}, 'liliq-p-1.1': {'id': 'LiLiQ-P-1.1', 'deprecated': False}, 'liliq-r-1.1': {'id': 'LiLiQ-R-1.1', 'deprecated': False}, 'liliq-rplus-1.1': {'id': 'LiLiQ-Rplus-1.1', 'deprecated': False}, 'linux-man-pages-1-para': {'id': 'Linux-man-pages-1-para', 'deprecated': False}, 'linux-man-pages-copyleft': {'id': 'Linux-man-pages-copyleft', 'deprecated': False}, 'linux-man-pages-copyleft-2-para': {'id': 'Linux-man-pages-copyleft-2-para', 'deprecated': False}, 'linux-man-pages-copyleft-var': {'id': 'Linux-man-pages-copyleft-var', 'deprecated': False}, 'linux-openib': {'id': 'Linux-OpenIB', 'deprecated': False}, 'loop': {'id': 'LOOP', 'deprecated': False}, 'lpd-document': {'id': 'LPD-document', 'deprecated': False}, 'lpl-1.0': {'id': 'LPL-1.0', 'deprecated': False}, 'lpl-1.02': {'id': 'LPL-1.02', 'deprecated': False}, 'lppl-1.0': {'id': 'LPPL-1.0', 'deprecated': False}, 'lppl-1.1': {'id': 'LPPL-1.1', 'deprecated': False}, 'lppl-1.2': {'id': 'LPPL-1.2', 'deprecated': False}, 'lppl-1.3a': {'id': 'LPPL-1.3a', 'deprecated': False}, 'lppl-1.3c': {'id': 'LPPL-1.3c', 'deprecated': False}, 'lsof': {'id': 'lsof', 'deprecated': False}, 'lucida-bitmap-fonts': {'id': 'Lucida-Bitmap-Fonts', 'deprecated': False}, 'lzma-sdk-9.11-to-9.20': {'id': 'LZMA-SDK-9.11-to-9.20', 'deprecated': False}, 'lzma-sdk-9.22': {'id': 'LZMA-SDK-9.22', 'deprecated': False}, 'mackerras-3-clause': {'id': 'Mackerras-3-Clause', 'deprecated': False}, 'mackerras-3-clause-acknowledgment': {'id': 'Mackerras-3-Clause-acknowledgment', 'deprecated': False}, 'magaz': {'id': 'magaz', 'deprecated': False}, 'mailprio': {'id': 'mailprio', 'deprecated': False}, 'makeindex': {'id': 'MakeIndex', 'deprecated': False}, 'man2html': {'id': 'man2html', 'deprecated': False}, 'martin-birgmeier': {'id': 'Martin-Birgmeier', 'deprecated': False}, 'mcphee-slideshow': {'id': 'McPhee-slideshow', 'deprecated': False}, 'metamail': {'id': 'metamail', 'deprecated': False}, 'minpack': {'id': 'Minpack', 'deprecated': False}, 'mips': {'id': 'MIPS', 'deprecated': False}, 'miros': {'id': 'MirOS', 'deprecated': False}, 'mit': {'id': 'MIT', 'deprecated': False}, 'mit-0': {'id': 'MIT-0', 'deprecated': False}, 'mit-advertising': {'id': 'MIT-advertising', 'deprecated': False}, 'mit-click': {'id': 'MIT-Click', 'deprecated': False}, 'mit-cmu': {'id': 'MIT-CMU', 'deprecated': False}, 'mit-enna': {'id': 'MIT-enna', 'deprecated': False}, 'mit-feh': {'id': 'MIT-feh', 'deprecated': False}, 'mit-festival': {'id': 'MIT-Festival', 'deprecated': False}, 'mit-khronos-old': {'id': 'MIT-Khronos-old', 'deprecated': False}, 'mit-modern-variant': {'id': 'MIT-Modern-Variant', 'deprecated': False}, 'mit-open-group': {'id': 'MIT-open-group', 'deprecated': False}, 'mit-testregex': {'id': 'MIT-testregex', 'deprecated': False}, 'mit-wu': {'id': 'MIT-Wu', 'deprecated': False}, 'mitnfa': {'id': 'MITNFA', 'deprecated': False}, 'mmixware': {'id': 'MMIXware', 'deprecated': False}, 'motosoto': {'id': 'Motosoto', 'deprecated': False}, 'mpeg-ssg': {'id': 'MPEG-SSG', 'deprecated': False}, 'mpi-permissive': {'id': 'mpi-permissive', 'deprecated': False}, 'mpich2': {'id': 'mpich2', 'deprecated': False}, 'mpl-1.0': {'id': 'MPL-1.0', 'deprecated': False}, 'mpl-1.1': {'id': 'MPL-1.1', 'deprecated': False}, 'mpl-2.0': {'id': 'MPL-2.0', 'deprecated': False}, 'mpl-2.0-no-copyleft-exception': {'id': 'MPL-2.0-no-copyleft-exception', 'deprecated': False}, 'mplus': {'id': 'mplus', 'deprecated': False}, 'ms-lpl': {'id': 'MS-LPL', 'deprecated': False}, 'ms-pl': {'id': 'MS-PL', 'deprecated': False}, 'ms-rl': {'id': 'MS-RL', 'deprecated': False}, 'mtll': {'id': 'MTLL', 'deprecated': False}, 'mulanpsl-1.0': {'id': 'MulanPSL-1.0', 'deprecated': False}, 'mulanpsl-2.0': {'id': 'MulanPSL-2.0', 'deprecated': False}, 'multics': {'id': 'Multics', 'deprecated': False}, 'mup': {'id': 'Mup', 'deprecated': False}, 'naist-2003': {'id': 'NAIST-2003', 'deprecated': False}, 'nasa-1.3': {'id': 'NASA-1.3', 'deprecated': False}, 'naumen': {'id': 'Naumen', 'deprecated': False}, 'nbpl-1.0': {'id': 'NBPL-1.0', 'deprecated': False}, 'ncbi-pd': {'id': 'NCBI-PD', 'deprecated': False}, 'ncgl-uk-2.0': {'id': 'NCGL-UK-2.0', 'deprecated': False}, 'ncl': {'id': 'NCL', 'deprecated': False}, 'ncsa': {'id': 'NCSA', 'deprecated': False}, 'net-snmp': {'id': 'Net-SNMP', 'deprecated': True}, 'netcdf': {'id': 'NetCDF', 'deprecated': False}, 'newsletr': {'id': 'Newsletr', 'deprecated': False}, 'ngpl': {'id': 'NGPL', 'deprecated': False}, 'ngrep': {'id': 'ngrep', 'deprecated': False}, 'nicta-1.0': {'id': 'NICTA-1.0', 'deprecated': False}, 'nist-pd': {'id': 'NIST-PD', 'deprecated': False}, 'nist-pd-fallback': {'id': 'NIST-PD-fallback', 'deprecated': False}, 'nist-software': {'id': 'NIST-Software', 'deprecated': False}, 'nlod-1.0': {'id': 'NLOD-1.0', 'deprecated': False}, 'nlod-2.0': {'id': 'NLOD-2.0', 'deprecated': False}, 'nlpl': {'id': 'NLPL', 'deprecated': False}, 'nokia': {'id': 'Nokia', 'deprecated': False}, 'nosl': {'id': 'NOSL', 'deprecated': False}, 'noweb': {'id': 'Noweb', 'deprecated': False}, 'npl-1.0': {'id': 'NPL-1.0', 'deprecated': False}, 'npl-1.1': {'id': 'NPL-1.1', 'deprecated': False}, 'nposl-3.0': {'id': 'NPOSL-3.0', 'deprecated': False}, 'nrl': {'id': 'NRL', 'deprecated': False}, 'ntia-pd': {'id': 'NTIA-PD', 'deprecated': False}, 'ntp': {'id': 'NTP', 'deprecated': False}, 'ntp-0': {'id': 'NTP-0', 'deprecated': False}, 'nunit': {'id': 'Nunit', 'deprecated': True}, 'o-uda-1.0': {'id': 'O-UDA-1.0', 'deprecated': False}, 'oar': {'id': 'OAR', 'deprecated': False}, 'occt-pl': {'id': 'OCCT-PL', 'deprecated': False}, 'oclc-2.0': {'id': 'OCLC-2.0', 'deprecated': False}, 'odbl-1.0': {'id': 'ODbL-1.0', 'deprecated': False}, 'odc-by-1.0': {'id': 'ODC-By-1.0', 'deprecated': False}, 'offis': {'id': 'OFFIS', 'deprecated': False}, 'ofl-1.0': {'id': 'OFL-1.0', 'deprecated': False}, 'ofl-1.0-no-rfn': {'id': 'OFL-1.0-no-RFN', 'deprecated': False}, 'ofl-1.0-rfn': {'id': 'OFL-1.0-RFN', 'deprecated': False}, 'ofl-1.1': {'id': 'OFL-1.1', 'deprecated': False}, 'ofl-1.1-no-rfn': {'id': 'OFL-1.1-no-RFN', 'deprecated': False}, 'ofl-1.1-rfn': {'id': 'OFL-1.1-RFN', 'deprecated': False}, 'ogc-1.0': {'id': 'OGC-1.0', 'deprecated': False}, 'ogdl-taiwan-1.0': {'id': 'OGDL-Taiwan-1.0', 'deprecated': False}, 'ogl-canada-2.0': {'id': 'OGL-Canada-2.0', 'deprecated': False}, 'ogl-uk-1.0': {'id': 'OGL-UK-1.0', 'deprecated': False}, 'ogl-uk-2.0': {'id': 'OGL-UK-2.0', 'deprecated': False}, 'ogl-uk-3.0': {'id': 'OGL-UK-3.0', 'deprecated': False}, 'ogtsl': {'id': 'OGTSL', 'deprecated': False}, 'oldap-1.1': {'id': 'OLDAP-1.1', 'deprecated': False}, 'oldap-1.2': {'id': 'OLDAP-1.2', 'deprecated': False}, 'oldap-1.3': {'id': 'OLDAP-1.3', 'deprecated': False}, 'oldap-1.4': {'id': 'OLDAP-1.4', 'deprecated': False}, 'oldap-2.0': {'id': 'OLDAP-2.0', 'deprecated': False}, 'oldap-2.0.1': {'id': 'OLDAP-2.0.1', 'deprecated': False}, 'oldap-2.1': {'id': 'OLDAP-2.1', 'deprecated': False}, 'oldap-2.2': {'id': 'OLDAP-2.2', 'deprecated': False}, 'oldap-2.2.1': {'id': 'OLDAP-2.2.1', 'deprecated': False}, 'oldap-2.2.2': {'id': 'OLDAP-2.2.2', 'deprecated': False}, 'oldap-2.3': {'id': 'OLDAP-2.3', 'deprecated': False}, 'oldap-2.4': {'id': 'OLDAP-2.4', 'deprecated': False}, 'oldap-2.5': {'id': 'OLDAP-2.5', 'deprecated': False}, 'oldap-2.6': {'id': 'OLDAP-2.6', 'deprecated': False}, 'oldap-2.7': {'id': 'OLDAP-2.7', 'deprecated': False}, 'oldap-2.8': {'id': 'OLDAP-2.8', 'deprecated': False}, 'olfl-1.3': {'id': 'OLFL-1.3', 'deprecated': False}, 'oml': {'id': 'OML', 'deprecated': False}, 'openpbs-2.3': {'id': 'OpenPBS-2.3', 'deprecated': False}, 'openssl': {'id': 'OpenSSL', 'deprecated': False}, 'openssl-standalone': {'id': 'OpenSSL-standalone', 'deprecated': False}, 'openvision': {'id': 'OpenVision', 'deprecated': False}, 'opl-1.0': {'id': 'OPL-1.0', 'deprecated': False}, 'opl-uk-3.0': {'id': 'OPL-UK-3.0', 'deprecated': False}, 'opubl-1.0': {'id': 'OPUBL-1.0', 'deprecated': False}, 'oset-pl-2.1': {'id': 'OSET-PL-2.1', 'deprecated': False}, 'osl-1.0': {'id': 'OSL-1.0', 'deprecated': False}, 'osl-1.1': {'id': 'OSL-1.1', 'deprecated': False}, 'osl-2.0': {'id': 'OSL-2.0', 'deprecated': False}, 'osl-2.1': {'id': 'OSL-2.1', 'deprecated': False}, 'osl-3.0': {'id': 'OSL-3.0', 'deprecated': False}, 'padl': {'id': 'PADL', 'deprecated': False}, 'parity-6.0.0': {'id': 'Parity-6.0.0', 'deprecated': False}, 'parity-7.0.0': {'id': 'Parity-7.0.0', 'deprecated': False}, 'pddl-1.0': {'id': 'PDDL-1.0', 'deprecated': False}, 'php-3.0': {'id': 'PHP-3.0', 'deprecated': False}, 'php-3.01': {'id': 'PHP-3.01', 'deprecated': False}, 'pixar': {'id': 'Pixar', 'deprecated': False}, 'pkgconf': {'id': 'pkgconf', 'deprecated': False}, 'plexus': {'id': 'Plexus', 'deprecated': False}, 'pnmstitch': {'id': 'pnmstitch', 'deprecated': False}, 'polyform-noncommercial-1.0.0': {'id': 'PolyForm-Noncommercial-1.0.0', 'deprecated': False}, 'polyform-small-business-1.0.0': {'id': 'PolyForm-Small-Business-1.0.0', 'deprecated': False}, 'postgresql': {'id': 'PostgreSQL', 'deprecated': False}, 'ppl': {'id': 'PPL', 'deprecated': False}, 'psf-2.0': {'id': 'PSF-2.0', 'deprecated': False}, 'psfrag': {'id': 'psfrag', 'deprecated': False}, 'psutils': {'id': 'psutils', 'deprecated': False}, 'python-2.0': {'id': 'Python-2.0', 'deprecated': False}, 'python-2.0.1': {'id': 'Python-2.0.1', 'deprecated': False}, 'python-ldap': {'id': 'python-ldap', 'deprecated': False}, 'qhull': {'id': 'Qhull', 'deprecated': False}, 'qpl-1.0': {'id': 'QPL-1.0', 'deprecated': False}, 'qpl-1.0-inria-2004': {'id': 'QPL-1.0-INRIA-2004', 'deprecated': False}, 'radvd': {'id': 'radvd', 'deprecated': False}, 'rdisc': {'id': 'Rdisc', 'deprecated': False}, 'rhecos-1.1': {'id': 'RHeCos-1.1', 'deprecated': False}, 'rpl-1.1': {'id': 'RPL-1.1', 'deprecated': False}, 'rpl-1.5': {'id': 'RPL-1.5', 'deprecated': False}, 'rpsl-1.0': {'id': 'RPSL-1.0', 'deprecated': False}, 'rsa-md': {'id': 'RSA-MD', 'deprecated': False}, 'rscpl': {'id': 'RSCPL', 'deprecated': False}, 'ruby': {'id': 'Ruby', 'deprecated': False}, 'ruby-pty': {'id': 'Ruby-pty', 'deprecated': False}, 'sax-pd': {'id': 'SAX-PD', 'deprecated': False}, 'sax-pd-2.0': {'id': 'SAX-PD-2.0', 'deprecated': False}, 'saxpath': {'id': 'Saxpath', 'deprecated': False}, 'scea': {'id': 'SCEA', 'deprecated': False}, 'schemereport': {'id': 'SchemeReport', 'deprecated': False}, 'sendmail': {'id': 'Sendmail', 'deprecated': False}, 'sendmail-8.23': {'id': 'Sendmail-8.23', 'deprecated': False}, 'sendmail-open-source-1.1': {'id': 'Sendmail-Open-Source-1.1', 'deprecated': False}, 'sgi-b-1.0': {'id': 'SGI-B-1.0', 'deprecated': False}, 'sgi-b-1.1': {'id': 'SGI-B-1.1', 'deprecated': False}, 'sgi-b-2.0': {'id': 'SGI-B-2.0', 'deprecated': False}, 'sgi-opengl': {'id': 'SGI-OpenGL', 'deprecated': False}, 'sgp4': {'id': 'SGP4', 'deprecated': False}, 'shl-0.5': {'id': 'SHL-0.5', 'deprecated': False}, 'shl-0.51': {'id': 'SHL-0.51', 'deprecated': False}, 'simpl-2.0': {'id': 'SimPL-2.0', 'deprecated': False}, 'sissl': {'id': 'SISSL', 'deprecated': False}, 'sissl-1.2': {'id': 'SISSL-1.2', 'deprecated': False}, 'sl': {'id': 'SL', 'deprecated': False}, 'sleepycat': {'id': 'Sleepycat', 'deprecated': False}, 'smail-gpl': {'id': 'SMAIL-GPL', 'deprecated': False}, 'smlnj': {'id': 'SMLNJ', 'deprecated': False}, 'smppl': {'id': 'SMPPL', 'deprecated': False}, 'snia': {'id': 'SNIA', 'deprecated': False}, 'snprintf': {'id': 'snprintf', 'deprecated': False}, 'sofa': {'id': 'SOFA', 'deprecated': False}, 'softsurfer': {'id': 'softSurfer', 'deprecated': False}, 'soundex': {'id': 'Soundex', 'deprecated': False}, 'spencer-86': {'id': 'Spencer-86', 'deprecated': False}, 'spencer-94': {'id': 'Spencer-94', 'deprecated': False}, 'spencer-99': {'id': 'Spencer-99', 'deprecated': False}, 'spl-1.0': {'id': 'SPL-1.0', 'deprecated': False}, 'ssh-keyscan': {'id': 'ssh-keyscan', 'deprecated': False}, 'ssh-openssh': {'id': 'SSH-OpenSSH', 'deprecated': False}, 'ssh-short': {'id': 'SSH-short', 'deprecated': False}, 'ssleay-standalone': {'id': 'SSLeay-standalone', 'deprecated': False}, 'sspl-1.0': {'id': 'SSPL-1.0', 'deprecated': False}, 'standardml-nj': {'id': 'StandardML-NJ', 'deprecated': True}, 'sugarcrm-1.1.3': {'id': 'SugarCRM-1.1.3', 'deprecated': False}, 'sul-1.0': {'id': 'SUL-1.0', 'deprecated': False}, 'sun-ppp': {'id': 'Sun-PPP', 'deprecated': False}, 'sun-ppp-2000': {'id': 'Sun-PPP-2000', 'deprecated': False}, 'sunpro': {'id': 'SunPro', 'deprecated': False}, 'swl': {'id': 'SWL', 'deprecated': False}, 'swrule': {'id': 'swrule', 'deprecated': False}, 'symlinks': {'id': 'Symlinks', 'deprecated': False}, 'tapr-ohl-1.0': {'id': 'TAPR-OHL-1.0', 'deprecated': False}, 'tcl': {'id': 'TCL', 'deprecated': False}, 'tcp-wrappers': {'id': 'TCP-wrappers', 'deprecated': False}, 'termreadkey': {'id': 'TermReadKey', 'deprecated': False}, 'tgppl-1.0': {'id': 'TGPPL-1.0', 'deprecated': False}, 'thirdeye': {'id': 'ThirdEye', 'deprecated': False}, 'threeparttable': {'id': 'threeparttable', 'deprecated': False}, 'tmate': {'id': 'TMate', 'deprecated': False}, 'torque-1.1': {'id': 'TORQUE-1.1', 'deprecated': False}, 'tosl': {'id': 'TOSL', 'deprecated': False}, 'tpdl': {'id': 'TPDL', 'deprecated': False}, 'tpl-1.0': {'id': 'TPL-1.0', 'deprecated': False}, 'trustedqsl': {'id': 'TrustedQSL', 'deprecated': False}, 'ttwl': {'id': 'TTWL', 'deprecated': False}, 'ttyp0': {'id': 'TTYP0', 'deprecated': False}, 'tu-berlin-1.0': {'id': 'TU-Berlin-1.0', 'deprecated': False}, 'tu-berlin-2.0': {'id': 'TU-Berlin-2.0', 'deprecated': False}, 'ubuntu-font-1.0': {'id': 'Ubuntu-font-1.0', 'deprecated': False}, 'ucar': {'id': 'UCAR', 'deprecated': False}, 'ucl-1.0': {'id': 'UCL-1.0', 'deprecated': False}, 'ulem': {'id': 'ulem', 'deprecated': False}, 'umich-merit': {'id': 'UMich-Merit', 'deprecated': False}, 'unicode-3.0': {'id': 'Unicode-3.0', 'deprecated': False}, 'unicode-dfs-2015': {'id': 'Unicode-DFS-2015', 'deprecated': False}, 'unicode-dfs-2016': {'id': 'Unicode-DFS-2016', 'deprecated': False}, 'unicode-tou': {'id': 'Unicode-TOU', 'deprecated': False}, 'unixcrypt': {'id': 'UnixCrypt', 'deprecated': False}, 'unlicense': {'id': 'Unlicense', 'deprecated': False}, 'unlicense-libtelnet': {'id': 'Unlicense-libtelnet', 'deprecated': False}, 'unlicense-libwhirlpool': {'id': 'Unlicense-libwhirlpool', 'deprecated': False}, 'upl-1.0': {'id': 'UPL-1.0', 'deprecated': False}, 'urt-rle': {'id': 'URT-RLE', 'deprecated': False}, 'vim': {'id': 'Vim', 'deprecated': False}, 'vostrom': {'id': 'VOSTROM', 'deprecated': False}, 'vsl-1.0': {'id': 'VSL-1.0', 'deprecated': False}, 'w3c': {'id': 'W3C', 'deprecated': False}, 'w3c-19980720': {'id': 'W3C-19980720', 'deprecated': False}, 'w3c-20150513': {'id': 'W3C-20150513', 'deprecated': False}, 'w3m': {'id': 'w3m', 'deprecated': False}, 'watcom-1.0': {'id': 'Watcom-1.0', 'deprecated': False}, 'widget-workshop': {'id': 'Widget-Workshop', 'deprecated': False}, 'wsuipa': {'id': 'Wsuipa', 'deprecated': False}, 'wtfpl': {'id': 'WTFPL', 'deprecated': False}, 'wwl': {'id': 'wwl', 'deprecated': False}, 'wxwindows': {'id': 'wxWindows', 'deprecated': True}, 'x11': {'id': 'X11', 'deprecated': False}, 'x11-distribute-modifications-variant': {'id': 'X11-distribute-modifications-variant', 'deprecated': False}, 'x11-swapped': {'id': 'X11-swapped', 'deprecated': False}, 'xdebug-1.03': {'id': 'Xdebug-1.03', 'deprecated': False}, 'xerox': {'id': 'Xerox', 'deprecated': False}, 'xfig': {'id': 'Xfig', 'deprecated': False}, 'xfree86-1.1': {'id': 'XFree86-1.1', 'deprecated': False}, 'xinetd': {'id': 'xinetd', 'deprecated': False}, 'xkeyboard-config-zinoviev': {'id': 'xkeyboard-config-Zinoviev', 'deprecated': False}, 'xlock': {'id': 'xlock', 'deprecated': False}, 'xnet': {'id': 'Xnet', 'deprecated': False}, 'xpp': {'id': 'xpp', 'deprecated': False}, 'xskat': {'id': 'XSkat', 'deprecated': False}, 'xzoom': {'id': 'xzoom', 'deprecated': False}, 'ypl-1.0': {'id': 'YPL-1.0', 'deprecated': False}, 'ypl-1.1': {'id': 'YPL-1.1', 'deprecated': False}, 'zed': {'id': 'Zed', 'deprecated': False}, 'zeeff': {'id': 'Zeeff', 'deprecated': False}, 'zend-2.0': {'id': 'Zend-2.0', 'deprecated': False}, 'zimbra-1.3': {'id': 'Zimbra-1.3', 'deprecated': False}, 'zimbra-1.4': {'id': 'Zimbra-1.4', 'deprecated': False}, 'zlib': {'id': 'Zlib', 'deprecated': False}, 'zlib-acknowledgement': {'id': 'zlib-acknowledgement', 'deprecated': False}, 'zpl-1.1': {'id': 'ZPL-1.1', 'deprecated': False}, 'zpl-2.0': {'id': 'ZPL-2.0', 'deprecated': False}, 'zpl-2.1': {'id': 'ZPL-2.1', 'deprecated': False},}
EXCEPTIONS: dict[str, SPDXException] = { '389-exception': {'id': '389-exception', 'deprecated': False}, 'asterisk-exception': {'id': 'Asterisk-exception', 'deprecated': False}, 'asterisk-linking-protocols-exception': {'id': 'Asterisk-linking-protocols-exception', 'deprecated': False}, 'autoconf-exception-2.0': {'id': 'Autoconf-exception-2.0', 'deprecated': False}, 'autoconf-exception-3.0': {'id': 'Autoconf-exception-3.0', 'deprecated': False}, 'autoconf-exception-generic': {'id': 'Autoconf-exception-generic', 'deprecated': False}, 'autoconf-exception-generic-3.0': {'id': 'Autoconf-exception-generic-3.0', 'deprecated': False}, 'autoconf-exception-macro': {'id': 'Autoconf-exception-macro', 'deprecated': False}, 'bison-exception-1.24': {'id': 'Bison-exception-1.24', 'deprecated': False}, 'bison-exception-2.2': {'id': 'Bison-exception-2.2', 'deprecated': False}, 'bootloader-exception': {'id': 'Bootloader-exception', 'deprecated': False}, 'cgal-linking-exception': {'id': 'CGAL-linking-exception', 'deprecated': False}, 'classpath-exception-2.0': {'id': 'Classpath-exception-2.0', 'deprecated': False}, 'clisp-exception-2.0': {'id': 'CLISP-exception-2.0', 'deprecated': False}, 'cryptsetup-openssl-exception': {'id': 'cryptsetup-OpenSSL-exception', 'deprecated': False}, 'digia-qt-lgpl-exception-1.1': {'id': 'Digia-Qt-LGPL-exception-1.1', 'deprecated': False}, 'digirule-foss-exception': {'id': 'DigiRule-FOSS-exception', 'deprecated': False}, 'ecos-exception-2.0': {'id': 'eCos-exception-2.0', 'deprecated': False}, 'erlang-otp-linking-exception': {'id': 'erlang-otp-linking-exception', 'deprecated': False}, 'fawkes-runtime-exception': {'id': 'Fawkes-Runtime-exception', 'deprecated': False}, 'fltk-exception': {'id': 'FLTK-exception', 'deprecated': False}, 'fmt-exception': {'id': 'fmt-exception', 'deprecated': False}, 'font-exception-2.0': {'id': 'Font-exception-2.0', 'deprecated': False}, 'freertos-exception-2.0': {'id': 'freertos-exception-2.0', 'deprecated': False}, 'gcc-exception-2.0': {'id': 'GCC-exception-2.0', 'deprecated': False}, 'gcc-exception-2.0-note': {'id': 'GCC-exception-2.0-note', 'deprecated': False}, 'gcc-exception-3.1': {'id': 'GCC-exception-3.1', 'deprecated': False}, 'gmsh-exception': {'id': 'Gmsh-exception', 'deprecated': False}, 'gnat-exception': {'id': 'GNAT-exception', 'deprecated': False}, 'gnome-examples-exception': {'id': 'GNOME-examples-exception', 'deprecated': False}, 'gnu-compiler-exception': {'id': 'GNU-compiler-exception', 'deprecated': False}, 'gnu-javamail-exception': {'id': 'gnu-javamail-exception', 'deprecated': False}, 'gpl-3.0-389-ds-base-exception': {'id': 'GPL-3.0-389-ds-base-exception', 'deprecated': False}, 'gpl-3.0-interface-exception': {'id': 'GPL-3.0-interface-exception', 'deprecated': False}, 'gpl-3.0-linking-exception': {'id': 'GPL-3.0-linking-exception', 'deprecated': False}, 'gpl-3.0-linking-source-exception': {'id': 'GPL-3.0-linking-source-exception', 'deprecated': False}, 'gpl-cc-1.0': {'id': 'GPL-CC-1.0', 'deprecated': False}, 'gstreamer-exception-2005': {'id': 'GStreamer-exception-2005', 'deprecated': False}, 'gstreamer-exception-2008': {'id': 'GStreamer-exception-2008', 'deprecated': False}, 'harbour-exception': {'id': 'harbour-exception', 'deprecated': False}, 'i2p-gpl-java-exception': {'id': 'i2p-gpl-java-exception', 'deprecated': False}, 'independent-modules-exception': {'id': 'Independent-modules-exception', 'deprecated': False}, 'kicad-libraries-exception': {'id': 'KiCad-libraries-exception', 'deprecated': False}, 'lgpl-3.0-linking-exception': {'id': 'LGPL-3.0-linking-exception', 'deprecated': False}, 'libpri-openh323-exception': {'id': 'libpri-OpenH323-exception', 'deprecated': False}, 'libtool-exception': {'id': 'Libtool-exception', 'deprecated': False}, 'linux-syscall-note': {'id': 'Linux-syscall-note', 'deprecated': False}, 'llgpl': {'id': 'LLGPL', 'deprecated': False}, 'llvm-exception': {'id': 'LLVM-exception', 'deprecated': False}, 'lzma-exception': {'id': 'LZMA-exception', 'deprecated': False}, 'mif-exception': {'id': 'mif-exception', 'deprecated': False}, 'mxml-exception': {'id': 'mxml-exception', 'deprecated': False}, 'nokia-qt-exception-1.1': {'id': 'Nokia-Qt-exception-1.1', 'deprecated': True}, 'ocaml-lgpl-linking-exception': {'id': 'OCaml-LGPL-linking-exception', 'deprecated': False}, 'occt-exception-1.0': {'id': 'OCCT-exception-1.0', 'deprecated': False}, 'openjdk-assembly-exception-1.0': {'id': 'OpenJDK-assembly-exception-1.0', 'deprecated': False}, 'openvpn-openssl-exception': {'id': 'openvpn-openssl-exception', 'deprecated': False}, 'pcre2-exception': {'id': 'PCRE2-exception', 'deprecated': False}, 'polyparse-exception': {'id': 'polyparse-exception', 'deprecated': False}, 'ps-or-pdf-font-exception-20170817': {'id': 'PS-or-PDF-font-exception-20170817', 'deprecated': False}, 'qpl-1.0-inria-2004-exception': {'id': 'QPL-1.0-INRIA-2004-exception', 'deprecated': False}, 'qt-gpl-exception-1.0': {'id': 'Qt-GPL-exception-1.0', 'deprecated': False}, 'qt-lgpl-exception-1.1': {'id': 'Qt-LGPL-exception-1.1', 'deprecated': False}, 'qwt-exception-1.0': {'id': 'Qwt-exception-1.0', 'deprecated': False}, 'romic-exception': {'id': 'romic-exception', 'deprecated': False}, 'rrdtool-floss-exception-2.0': {'id': 'RRDtool-FLOSS-exception-2.0', 'deprecated': False}, 'sane-exception': {'id': 'SANE-exception', 'deprecated': False}, 'shl-2.0': {'id': 'SHL-2.0', 'deprecated': False}, 'shl-2.1': {'id': 'SHL-2.1', 'deprecated': False}, 'stunnel-exception': {'id': 'stunnel-exception', 'deprecated': False}, 'swi-exception': {'id': 'SWI-exception', 'deprecated': False}, 'swift-exception': {'id': 'Swift-exception', 'deprecated': False}, 'texinfo-exception': {'id': 'Texinfo-exception', 'deprecated': False}, 'u-boot-exception-2.0': {'id': 'u-boot-exception-2.0', 'deprecated': False}, 'ubdl-exception': {'id': 'UBDL-exception', 'deprecated': False}, 'universal-foss-exception-1.0': {'id': 'Universal-FOSS-exception-1.0', 'deprecated': False}, 'vsftpd-openssl-exception': {'id': 'vsftpd-openssl-exception', 'deprecated': False}, 'wxwindows-exception-3.1': {'id': 'WxWindows-exception-3.1', 'deprecated': False}, 'x11vnc-openssl-exception': {'id': 'x11vnc-openssl-exception', 'deprecated': False},}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
from __future__ import annotations
import functoolsimport operatorimport osimport platformimport sysfrom collections.abc import Set as AbstractSetfrom typing import TYPE_CHECKING, Callable, Literal, TypedDict, Union, cast
from ._parser import MarkerAtom, MarkerList, Op, Value, Variablefrom ._parser import parse_marker as _parse_markerfrom ._tokenizer import ParserSyntaxErrorfrom .specifiers import InvalidSpecifier, Specifierfrom .utils import canonicalize_name
if TYPE_CHECKING: from collections.abc import Mapping
__all__ = [ "Environment", "EvaluateContext", "InvalidMarker", "Marker", "UndefinedComparison", "UndefinedEnvironmentName", "default_environment",]
def __dir__() -> list[str]: return __all__
Operator = Callable[[str, Union[str, AbstractSet[str]]], bool]EvaluateContext = Literal["metadata", "lock_file", "requirement"]"""A ``typing.Literal`` enumerating valid marker evaluation contexts.
Valid values for the ``context`` passed to :meth:`Marker.evaluate` are:
* ``"metadata"`` (for core metadata; default)* ``"lock_file"`` (for lock files)* ``"requirement"`` (i.e. all other situations)
.. versionadded:: 25.0"""
MARKERS_ALLOWING_SET = {"extras", "dependency_groups"}MARKERS_REQUIRING_VERSION = { "implementation_version", "platform_release", "python_full_version", "python_version",}
class InvalidMarker(ValueError): """Raised when attempting to create a :class:`Marker` from invalid input.
This error indicates that the given marker string does not conform to the :ref:`specification of dependency specifiers <pypug:dependency-specifiers>`. """
class UndefinedComparison(ValueError): """Raised when evaluating an unsupported marker comparison.
This can happen when marker values are compared as versions but do not conform to the :ref:`specification of version specifiers <pypug:version-specifiers>`. """
class UndefinedEnvironmentName(KeyError): """Raised when evaluating a marker that references a missing environment key.
Subclasses :class:`KeyError` so that code catching the bare ``KeyError`` that a missing environment lookup historically produced keeps working.
.. versionchanged:: 26.3 Now subclasses :class:`KeyError` (was :class:`ValueError`) and is raised by :meth:`Marker.evaluate` for missing environment keys, where a bare ``KeyError`` was raised before. """
class Environment(TypedDict): """ A dictionary that represents a Python environment as captured by :func:`default_environment`. All fields are required. """
implementation_name: str """The implementation's identifier, e.g. ``'cpython'``."""
implementation_version: str """ The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or ``'7.3.13'`` for PyPy3.10 v7.3.13. """
os_name: str """ The value of :py:data:`os.name`. The name of the operating system dependent module imported, e.g. ``'posix'``. """
platform_machine: str """ Returns the machine type, e.g. ``'i386'``.
An empty string if the value cannot be determined. """
platform_release: str """ The system's release, e.g. ``'2.2.0'`` or ``'NT'``.
An empty string if the value cannot be determined. """
platform_system: str """ The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``.
An empty string if the value cannot be determined. """
platform_version: str """ The system's release version, e.g. ``'#3 on degas'``.
An empty string if the value cannot be determined. """
python_full_version: str """ The Python version as string ``'major.minor.patchlevel'``.
Note that unlike the Python :py:data:`sys.version`, this value will always include the patchlevel (it defaults to 0). """
platform_python_implementation: str """ A string identifying the Python implementation, e.g. ``'CPython'``. """
python_version: str """The Python version as string ``'major.minor'``."""
sys_platform: str """ This string contains a platform identifier that can be used to append platform-specific components to :py:data:`sys.path`, for instance.
For Unix systems, except on Linux and AIX, this is the lowercased OS name as returned by ``uname -s`` with the first part of the version as returned by ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python was built. """
def _normalize_extras( result: MarkerList | MarkerAtom | str,) -> MarkerList | MarkerAtom | str: if isinstance(result, list): return [_normalize_extras(r) for r in result] if not isinstance(result, tuple): return result
lhs, op, rhs = result if isinstance(lhs, Variable) and lhs.value == "extra" and isinstance(rhs, Value): normalized_extra = canonicalize_name(rhs.value) rhs = Value(normalized_extra) elif isinstance(rhs, Variable) and rhs.value == "extra" and isinstance(lhs, Value): normalized_extra = canonicalize_name(lhs.value) lhs = Value(normalized_extra) elif ( isinstance(rhs, Variable) and rhs.value in MARKERS_ALLOWING_SET and isinstance(lhs, Value) ): # PEP 685 (extras) / PEP 735 (dependency_groups): the set-valued membership # literal must also be normalized. evaluate() already canonicalizes both # operands for these keys (see _normalize), so normalizing the literal at # parse time keeps __str__/__eq__/__hash__ consistent with evaluate() -- e.g. # Marker('"Foo" in extras') and Marker('"foo" in extras') must compare and # hash equal (the membership variable is always the right-hand operand). lhs = Value(canonicalize_name(lhs.value)) return lhs, op, rhs
def _normalize_extra_values(results: MarkerList) -> MarkerList: """ Normalize extra values. """
return [_normalize_extras(r) for r in results]
def _format_marker( marker: list[str] | MarkerAtom | str, first: bool | None = True) -> str: assert isinstance(marker, (list, tuple, str))
# Unwrap a redundant [[...]] wrapper, but keep the nesting context so a # nested group keeps the parentheses its and/or precedence needs. if ( isinstance(marker, list) and len(marker) == 1 and isinstance(marker[0], (list, tuple)) ): return _format_marker(marker[0], first=first)
if isinstance(marker, list): inner = (_format_marker(m, first=False) for m in marker) if first: return " ".join(inner) else: return "(" + " ".join(inner) + ")" elif isinstance(marker, tuple): return " ".join([m.serialize() for m in marker]) else: return marker
_operators: dict[str, Operator] = { "in": lambda lhs, rhs: lhs in rhs, "not in": lambda lhs, rhs: lhs not in rhs, "<": lambda _lhs, _rhs: False, "<=": operator.eq, "==": operator.eq, "!=": operator.ne, ">=": operator.eq, ">": lambda _lhs, _rhs: False,}
def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool: op_str = op.serialize() if key in MARKERS_REQUIRING_VERSION: try: spec = Specifier(f"{op_str}{rhs}") except InvalidSpecifier: pass else: return spec.contains(lhs, prereleases=True)
oper: Operator | None = _operators.get(op_str) if oper is None: raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.")
return oper(lhs, rhs)
def _normalize( lhs: str, rhs: str | AbstractSet[str], key: str) -> tuple[str, str | AbstractSet[str]]: # PEP 685 - Comparison of extra names for optional distribution dependencies # https://peps.python.org/pep-0685/ # > When comparing extra names, tools MUST normalize the names being # > compared using the semantics outlined in PEP 503 for names if key == "extra": assert isinstance(rhs, str), "extra value must be a string" # Both sides are normalized at this point already return (lhs, rhs) if key in MARKERS_ALLOWING_SET: if isinstance(rhs, str): # pragma: no cover return (canonicalize_name(lhs), canonicalize_name(rhs)) else: return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs})
# other environment markers don't have such standards return lhs, rhs
def _lookup_environment( environment: dict[str, str | AbstractSet[str]], key: str) -> str | AbstractSet[str]: try: return environment[key] except KeyError: raise UndefinedEnvironmentName(key) from None
def _evaluate_markers( markers: MarkerList, environment: dict[str, str | AbstractSet[str]]) -> bool: groups: list[list[bool]] = [[]]
for marker in markers: if isinstance(marker, list): groups[-1].append(_evaluate_markers(marker, environment)) elif isinstance(marker, tuple): lhs, op, rhs = marker
if isinstance(lhs, Variable): environment_key = lhs.value lhs_value = _lookup_environment(environment, environment_key) rhs_value = rhs.value else: lhs_value = lhs.value environment_key = rhs.value rhs_value = _lookup_environment(environment, environment_key)
if not isinstance(lhs_value, str): raise UndefinedComparison( f"Set-valued marker {environment_key!r} can only be used " f'with the membership form (e.g. "<name>" in ' f"{environment_key}); it cannot appear on the left-hand " f"side of {op.serialize()!r}." ) lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key)) elif marker == "or": groups.append([]) elif marker == "and": pass else: # pragma: nocover raise TypeError(f"Unexpected marker {marker!r}")
return any(all(item) for item in groups)
def _format_full_version(info: sys._version_info) -> str: version = f"{info.major}.{info.minor}.{info.micro}" kind = info.releaselevel if kind != "final": version += kind[0] + str(info.serial) return version
@functools.cachedef _cached_default_environment() -> Environment: """Build the default marker environment for the current Python process.
The values are derived from process-constant data (the running interpreter and the host platform), so this is cached and built only once. The result is shared between callers and must never be mutated; :func:`default_environment` returns a fresh copy. """ iver = _format_full_version(sys.implementation.version) implementation_name = sys.implementation.name return { "implementation_name": implementation_name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": ".".join(platform.python_version_tuple()[:2]), "sys_platform": sys.platform, }
def default_environment() -> Environment: """Return the default marker environment for the current Python process.
This is the base environment used by :meth:`Marker.evaluate`. A fresh copy is returned on every call so callers may freely mutate the result; a shallow copy suffices because all values are immutable strings.
.. versionchanged:: 26.3 The environment is computed once per process and cached, since it is derived from process-constant data. Patching ``platform``/``sys``/``os`` after the first call has no effect; pass an explicit ``environment`` to :meth:`Marker.evaluate` to evaluate against different values. """ return cast("Environment", dict(_cached_default_environment()))
class Marker: """Represents a parsed dependency marker expression.
Marker expressions are parsed according to the :ref:`specification of dependency specifiers <pypug:dependency-specifiers>`.
:param marker: The string representation of a marker expression. :raises InvalidMarker: If ``marker`` cannot be parsed.
Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases.
.. versionchanged:: 26.2
Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """
__slots__ = ("_markers",)
def __init__(self, marker: str) -> None: # Note: We create a Marker object without calling this constructor in # packaging.requirements.Requirement. If any additional logic is # added here, make sure to mirror/adapt Requirement.
# If this fails and throws an error, the repr still expects _markers to # be defined. self._markers: MarkerList = []
try: self._markers = _normalize_extra_values(_parse_marker(marker)) # The attribute `_markers` can be described in terms of a recursive type: # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] # # For example, the following expression: # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") # # is parsed into: # [ # (<Variable('python_version')>, <Op('>')>, <Value('3.6')>), # 'and', # [ # (<Variable('python_version')>, <Op('==')>, <Value('3.6')>), # 'or', # (<Variable('os_name')>, <Op('==')>, <Value('unix')>) # ] # ] except ParserSyntaxError as e: raise InvalidMarker(str(e)) from e
@classmethod def _from_markers(cls, markers: MarkerList) -> Marker: """Create a Marker instance from a pre-parsed marker tree.
This avoids re-parsing serialised marker strings when combining markers. """ new = cls.__new__(cls) new._markers = markers return new
def __str__(self) -> str: return _format_marker(self._markers)
def __repr__(self) -> str: return f"<{self.__class__.__name__}({str(self)!r})>"
def __hash__(self) -> int: return hash(str(self))
def __eq__(self, other: object) -> bool: if not isinstance(other, Marker): return NotImplemented
return str(self) == str(other)
def __getstate__(self) -> str: # Return the marker expression string for compactness and stability. # Internal Node objects are excluded; the string is re-parsed on load. return str(self)
def __setstate__(self, state: object) -> None: if isinstance(state, str): # New format (26.2+): just the marker expression string. try: self._markers = _normalize_extra_values(_parse_marker(state)) except ParserSyntaxError as exc: raise TypeError(f"Cannot restore Marker from {state!r}") from exc return if isinstance(state, dict) and "_markers" in state: # Old format (packaging <= 26.1, no __slots__): plain __dict__. markers = state["_markers"] if isinstance(markers, list): self._markers = markers return if isinstance(state, tuple) and len(state) == 2: # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). _, slot_dict = state if isinstance(slot_dict, dict) and "_markers" in slot_dict: markers = slot_dict["_markers"] if isinstance(markers, list): self._markers = markers return raise TypeError(f"Cannot restore Marker from {state!r}")
def __and__(self, other: Marker) -> Marker: """Combine this marker with another using ``and``.
.. versionadded:: 26.1 """ if not isinstance(other, Marker): return NotImplemented return self._from_markers([self._markers, "and", other._markers])
def __or__(self, other: Marker) -> Marker: """Combine this marker with another using ``or``.
.. versionadded:: 26.1 """ if not isinstance(other, Marker): return NotImplemented return self._from_markers([self._markers, "or", other._markers])
def evaluate( self, environment: Mapping[str, str | AbstractSet[str]] | None = None, context: EvaluateContext = "metadata", ) -> bool: """Evaluate a marker.
Return the boolean from evaluating this marker against the environment. The environment is determined from the current Python process unless passed in explicitly.
:param environment: Mapping containing keys and values to override the detected environment. :param EvaluateContext context: The context in which the marker is evaluated, which influences what marker names are considered valid. Accepted values are ``"metadata"`` (for core metadata; default), ``"lock_file"``, and ``"requirement"`` (i.e. all other situations). :raises UndefinedComparison: If the marker uses a comparison on values that are not valid versions per the :ref:`specification of version specifiers <pypug:version-specifiers>`. :raises UndefinedEnvironmentName: If the marker references a value that is missing from the evaluation environment. :returns: ``True`` if the marker matches, otherwise ``False``.
.. versionchanged:: 25.0 Added the ``context`` parameter, which influences which marker names are considered valid. """ current_environment = cast( "dict[str, str | AbstractSet[str]]", default_environment() ) if context == "lock_file": current_environment |= { "extras": frozenset(), "dependency_groups": frozenset(), } elif context == "metadata": current_environment["extra"] = ""
if environment is not None: current_environment |= environment if "extra" in current_environment: # The API used to allow setting extra to None. We need to handle # this case for backwards compatibility. Also skip running # normalize name if extra is empty. extra = cast("str | None", current_environment["extra"]) current_environment["extra"] = canonicalize_name(extra) if extra else ""
return _evaluate_markers( self._markers, _repair_python_full_version(current_environment) )
def _pep440_python_full_version(python_full_version: str) -> str: """ Work around platform.python_version() returning something that is not PEP 440 compliant for non-tagged Python builds. """ if python_full_version.endswith("+"): return f"{python_full_version}local" return python_full_version
def _repair_python_full_version( env: dict[str, str | AbstractSet[str]],) -> dict[str, str | AbstractSet[str]]: """ Work around platform.python_version() returning something that is not PEP 440 compliant for non-tagged Python builds. """ python_full_version = cast("str", env["python_full_version"]) env["python_full_version"] = _pep440_python_full_version(python_full_version) return env1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054from __future__ import annotations
import email.headerimport email.messageimport email.parserimport email.policyimport keywordimport pathlibimport reimport typingfrom typing import ( Any, Callable, Generic, Literal, TypedDict, cast,)
from . import licenses, requirements, specifiers, utilsfrom . import version as version_modulefrom .errors import ExceptionGroup, _ErrorCollector
if typing.TYPE_CHECKING: from .licenses import NormalizedLicenseExpression from .version import Version
T = typing.TypeVar("T")
__all__ = [ "ExceptionGroup", # Keep this for a bit (makes mypy happy w/ 26.0 compat) "InvalidMetadata", "Metadata", "RFC822Message", "RFC822Policy", "RawMetadata", "parse_email",]
def __dir__() -> list[str]: return __all__
class InvalidMetadata(ValueError): """A metadata field contains invalid data.
.. versionadded:: 23.2 """
field: str """The name of the field that contains invalid data."""
def __init__(self, field: str, message: str) -> None: self.field = field super().__init__(message)
# Support pickling; ``args`` does not match ``__init__``'s signature. def __reduce__(self) -> tuple[type[InvalidMetadata], tuple[str, str]]: return (self.__class__, (self.field, self.args[0]))
# The RawMetadata class attempts to make as few assumptions about the underlying# serialization formats as possible. The idea is that as long as a serialization# formats offer some very basic primitives in *some* way then we can support# serializing to and from that format.class RawMetadata(TypedDict, total=False): """A dictionary of raw core metadata.
Each field in core metadata maps to a key of this dictionary (when data is provided). The key is lower-case and underscores are used instead of dashes compared to the equivalent core metadata field. Any core metadata field that can be specified multiple times or can hold multiple values in a single field have a key with a plural name. See :class:`Metadata` whose attributes match the keys of this dictionary.
Core metadata fields that can be specified multiple times are stored as a list or dict depending on which is appropriate for the field. Any fields which hold multiple values in a single field are stored as a list. All fields are considered optional. """
# Metadata 1.0 - PEP 241 metadata_version: str name: str version: str platforms: list[str] summary: str description: str keywords: list[str] home_page: str author: str author_email: str license: str
# Metadata 1.1 - PEP 314 supported_platforms: list[str] download_url: str classifiers: list[str] requires: list[str] provides: list[str] obsoletes: list[str]
# Metadata 1.2 - PEP 345 maintainer: str maintainer_email: str requires_dist: list[str] provides_dist: list[str] obsoletes_dist: list[str] requires_python: str requires_external: list[str] project_urls: dict[str, str]
# Metadata 2.0 # PEP 426 attempted to completely revamp the metadata format # but got stuck without ever being able to build consensus on # it and ultimately ended up withdrawn. # # However, a number of tools had started emitting METADATA with # `2.0` Metadata-Version, so for historical reasons, this version # was skipped.
# Metadata 2.1 - PEP 566 description_content_type: str provides_extra: list[str]
# Metadata 2.2 - PEP 643 dynamic: list[str]
# Metadata 2.3 - PEP 685 # No new fields were added in PEP 685, just some edge case were # tightened up to provide better interoperability.
# Metadata 2.4 - PEP 639 license_expression: str """.. versionadded:: 24.2""" license_files: list[str] """.. versionadded:: 24.2"""
# Metadata 2.5 - PEP 794 import_names: list[str] """.. versionadded:: 26.0""" import_namespaces: list[str] """.. versionadded:: 26.0"""
# Metadata 2.6 - PEP 808 (no new fields, behavior change for Dynamic)
# 'keywords' is special as it's a string in the core metadata spec, but we# represent it as a list._STRING_FIELDS = { "author", "author_email", "description", "description_content_type", "download_url", "home_page", "license", "license_expression", "maintainer", "maintainer_email", "metadata_version", "name", "requires_python", "summary", "version",}
_LIST_FIELDS = { "classifiers", "dynamic", "license_files", "obsoletes", "obsoletes_dist", "platforms", "provides", "provides_dist", "provides_extra", "requires", "requires_dist", "requires_external", "supported_platforms", "import_names", "import_namespaces",}
_DICT_FIELDS = { "project_urls",}
def _parse_keywords(data: str) -> list[str]: """Split a string of comma-separated keywords into a list of keywords.""" return [k.strip() for k in data.split(",")]
def _parse_project_urls(data: list[str]) -> dict[str, str]: """Parse a list of label/URL string pairings separated by a comma.""" urls = {} for pair in data: # Our logic is slightly tricky here as we want to try and do # *something* reasonable with malformed data. # # The main thing that we have to worry about, is data that does # not have a ',' at all to split the label from the Value. There # isn't a singular right answer here, and we will fail validation # later on (if the caller is validating) so it doesn't *really* # matter, but since the missing value has to be an empty str # and our return value is dict[str, str], if we let the key # be the missing value, then they'd have multiple '' values that # overwrite each other in a accumulating dict. # # The other potential issue is that it's possible to have the # same label multiple times in the metadata, with no solid "right" # answer with what to do in that case. As such, we'll do the only # thing we can, which is treat the field as unparsable and add it # to our list of unparsed fields. # # TODO: The spec doesn't say anything about if the keys should be # considered case sensitive or not... logically they should # be case-preserving and case-insensitive, but doing that # would open up more cases where we might have duplicate # entries. label, _, url = (s.strip() for s in pair.partition(","))
if label in urls: # The label already exists in our set of urls, so this field # is unparsable, and we can just add the whole thing to our # unparsable data and stop processing it. raise KeyError("duplicate labels in project urls") urls[label] = url
return urls
def _get_payload(msg: email.message.Message, source: bytes | str) -> str: """Get the body of the message.""" # If our source is a str, then our caller has managed encodings for us, # and we don't need to deal with it. if isinstance(source, str): payload = msg.get_payload() # A multipart payload makes get_payload() return a list of messages # rather than a str; route it to ``unparsed``. if not isinstance(payload, str): raise ValueError("payload is not a string") # noqa: TRY004 return payload # If our source is a bytes, then we're managing the encoding and we need # to deal with it. else: bpayload = msg.get_payload(decode=True) # A multipart payload makes get_payload(decode=True) return None; # route it to ``unparsed``. if not isinstance(bpayload, bytes): raise ValueError("payload in an invalid encoding") # noqa: TRY004 try: return bpayload.decode("utf8", "strict") except UnicodeDecodeError as exc: raise ValueError("payload in an invalid encoding") from exc
# The various parse_FORMAT functions here are intended to be as lenient as# possible in their parsing, while still returning a correctly typed# RawMetadata.## To aid in this, we also generally want to do as little touching of the# data as possible, except where there are possibly some historic holdovers# that make valid data awkward to work with.## While this is a lower level, intermediate format than our ``Metadata``# class, some light touch ups can make a massive difference in usability.
# Map METADATA fields to RawMetadata._EMAIL_TO_RAW_MAPPING = { "author": "author", "author-email": "author_email", "classifier": "classifiers", "description": "description", "description-content-type": "description_content_type", "download-url": "download_url", "dynamic": "dynamic", "home-page": "home_page", "import-name": "import_names", "import-namespace": "import_namespaces", "keywords": "keywords", "license": "license", "license-expression": "license_expression", "license-file": "license_files", "maintainer": "maintainer", "maintainer-email": "maintainer_email", "metadata-version": "metadata_version", "name": "name", "obsoletes": "obsoletes", "obsoletes-dist": "obsoletes_dist", "platform": "platforms", "project-url": "project_urls", "provides": "provides", "provides-dist": "provides_dist", "provides-extra": "provides_extra", "requires": "requires", "requires-dist": "requires_dist", "requires-external": "requires_external", "requires-python": "requires_python", "summary": "summary", "supported-platform": "supported_platforms", "version": "version",}_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
# A bare "\r" makes the email generator raise ``HeaderWriteError``, and on# CPython releases without the CVE-2024-6923 fix any ``str.splitlines``# boundary ends the header line, so fold all of them, not just "\n"._LINE_BOUNDARY_RE = re.compile(r"\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]")
# This class is for writing RFC822 messagesclass RFC822Policy(email.policy.EmailPolicy): """ This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse`` implementation that handles multi-line values, and some nice defaults.
.. versionadded:: 26.0 """
utf8 = True mangle_from_ = False max_line_length = 0
def header_store_parse(self, name: str, value: str) -> tuple[str, str]: size = len(name) + 2 value = _LINE_BOUNDARY_RE.sub("\n" + " " * size, value) return (name, value)
# This class is for writing RFC822 messagesclass RFC822Message(email.message.EmailMessage): """ This is :class:`email.message.EmailMessage` with two small changes: it defaults to our `RFC822Policy`, and it correctly writes unicode when being called with `bytes()`.
.. versionadded:: 26.0 """
def __init__(self) -> None: super().__init__(policy=RFC822Policy())
def as_bytes( self, unixfrom: bool = False, policy: email.policy.Policy | None = None ) -> bytes: """ Return the bytes representation of the message.
This handles unicode encoding. """ return self.as_string(unixfrom, policy=policy).encode("utf-8")
def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
This function returns a two-item tuple of dicts. The first dict is of recognized fields from the core metadata specification. Fields that can be parsed and translated into Python's built-in types are converted appropriately. All other fields are left as-is. Fields that are allowed to appear multiple times are stored as lists.
The second dict contains all other fields from the metadata. This includes any unrecognized fields. It also includes any fields which are expected to be parsed into a built-in type but were not formatted appropriately. Finally, any fields that are expected to appear only once but are repeated are included in this dict.
""" raw: dict[str, str | list[str] | dict[str, str]] = {} unparsed: dict[str, list[str]] = {}
if isinstance(data, str): parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) else: parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
# We have to wrap parsed.keys() in a set, because in the case of multiple # values for a key (a list), the key will appear multiple times in the # list of keys, but we're avoiding that by using get_all(). for name_with_case in frozenset(parsed.keys()): # Header names in RFC are case insensitive, so we'll normalize to all # lower case to make comparisons easier. name = name_with_case.lower()
# We use get_all() here, even for fields that aren't multiple use, # because otherwise someone could have e.g. two Name fields, and we # would just silently ignore it rather than doing something about it. headers = parsed.get_all(name) or []
# The way the email module works when parsing bytes is that it # unconditionally decodes the bytes as ascii using the surrogateescape # handler. When you pull that data back out (such as with get_all() ), # it looks to see if the str has any surrogate escapes, and if it does # it wraps it in a Header object instead of returning the string. # # As such, we'll look for those Header objects, and fix up the encoding. value = [] # Flag if we have run into any issues processing the headers, thus # signalling that the data belongs in 'unparsed'. valid_encoding = True for h in headers: # It's unclear if this can return more types than just a Header or # a str, so we'll just assert here to make sure. assert isinstance(h, (email.header.Header, str))
# If it's a header object, we need to do our little dance to get # the real data out of it. In cases where there is invalid data # we're going to end up with mojibake, but there's no obvious, good # way around that without reimplementing parts of the Header object # ourselves. # # That should be fine since, if mojibacked happens, this key is # going into the unparsed dict anyways. if isinstance(h, email.header.Header): # The Header object stores it's data as chunks, and each chunk # can be independently encoded, so we'll need to check each # of them. chunks: list[tuple[bytes, str | None]] = [] for binary, _encoding in email.header.decode_header(h): try: binary.decode("utf8", "strict") except UnicodeDecodeError: # Enable mojibake. encoding = "latin1" valid_encoding = False else: encoding = "utf8" chunks.append((binary, encoding))
# Turn our chunks back into a Header object, then let that # Header object do the right thing to turn them into a # string for us. value.append(str(email.header.make_header(chunks))) # This is already a string, so just add it. else: value.append(h)
# We've processed all of our values to get them into a list of str, # but we may have mojibake data, in which case this is an unparsed # field. if not valid_encoding: unparsed[name] = value continue
raw_name = _EMAIL_TO_RAW_MAPPING.get(name) if raw_name is None: # This is a bit of a weird situation, we've encountered a key that # we don't know what it means, so we don't know whether it's meant # to be a list or not. # # Since we can't really tell one way or another, we'll just leave it # as a list, even though it may be a single item list, because that's # what makes the most sense for email headers. unparsed[name] = value continue
# If this is one of our string fields, then we'll check to see if our # value is a list of a single item. If it is then we'll assume that # it was emitted as a single string, and unwrap the str from inside # the list. # # If it's any other kind of data, then we haven't the faintest clue # what we should parse it as, and we have to just add it to our list # of unparsed stuff. if raw_name in _STRING_FIELDS and len(value) == 1: raw[raw_name] = value[0] # If this is import_names, we need to special case the empty field # case, which converts to an empty list instead of None. We can't let # the empty case slip through, as it will fail validation. elif raw_name == "import_names" and value == [""]: raw[raw_name] = [] # If this is one of our list of string fields, then we can just assign # the value, since email *only* has strings, and our get_all() call # above ensures that this is a list. elif raw_name in _LIST_FIELDS: raw[raw_name] = value # Special Case: Keywords # The keywords field is implemented in the metadata spec as a str, # but it conceptually is a list of strings, and is serialized using # ", ".join(keywords), so we'll do some light data massaging to turn # this into what it logically is. elif raw_name == "keywords" and len(value) == 1: raw[raw_name] = _parse_keywords(value[0]) # Special Case: Project-URL # The project urls is implemented in the metadata spec as a list of # specially-formatted strings that represent a key and a value, which # is fundamentally a mapping, however the email format doesn't support # mappings in a sane way, so it was crammed into a list of strings # instead. # # We will do a little light data massaging to turn this into a map as # it logically should be. elif raw_name == "project_urls": try: raw[raw_name] = _parse_project_urls(value) except KeyError: unparsed[name] = value # Nothing that we've done has managed to parse this, so it'll just # throw it in our unparsable data and move on. else: unparsed[name] = value
# We need to support getting the Description from the message payload in # addition to getting it from the the headers. This does mean, though, there # is the possibility of it being set both ways, in which case we put both # in 'unparsed' since we don't know which is right. try: payload = _get_payload(parsed, data) except ValueError: unparsed.setdefault("description", []).append( parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] ) else: if payload: # Check to see if we've already got a description, if so then both # it, and this body move to unparsable. if "description" in raw: description_header = cast("str", raw.pop("description")) unparsed.setdefault("description", []).extend( [description_header, payload] ) elif "description" in unparsed: unparsed["description"].append(payload) else: raw["description"] = payload
# We need to cast our `raw` to a metadata, because a TypedDict only support # literal key names, but we're computing our key names on purpose, but the # way this function is implemented, our `TypedDict` can only have valid key # names. return cast("RawMetadata", raw), unparsed
_NOT_FOUND = object()
# Keep the two values in sync._VALID_METADATA_VERSIONS = [ "1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6",]_MetadataVersion = Literal[ "1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6"]
_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
class _Validator(Generic[T]): """Validate a metadata field.
All _process_*() methods correspond to a core metadata field. The method is called with the field's raw value. If the raw value is valid it is returned in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause as appropriate). """
name: str raw_name: str added: _MetadataVersion
def __init__( self, *, added: _MetadataVersion = "1.0", ) -> None: self.added = added
def __set_name__(self, _owner: Metadata, name: str) -> None: self.name = name self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: # With Python 3.8, the caching can be replaced with functools.cached_property(). # No need to check the cache as attribute lookup will resolve into the # instance's __dict__ before __get__ is called. cache = instance.__dict__ value = instance._raw.get(self.name)
# To make the _process_* methods easier, we'll check if the value is None # and if this field is NOT a required attribute, and if both of those # things are true, we'll skip the the converter. This will mean that the # converters never have to deal with the None union. if self.name in _REQUIRED_ATTRS or value is not None: try: converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") except AttributeError: pass else: value = converter(value)
cache[self.name] = value try: del instance._raw[self.name] # type: ignore[misc] except KeyError: pass
return cast("T", value)
def _invalid_metadata( self, msg: str, cause: Exception | None = None ) -> InvalidMetadata: exc = InvalidMetadata(self.raw_name, msg) exc.__cause__ = cause return exc
def _process_metadata_version(self, value: str) -> _MetadataVersion: # Implicitly makes Metadata-Version required. if value not in _VALID_METADATA_VERSIONS: raise self._invalid_metadata(f"{value!r} is not a valid metadata version") return cast("_MetadataVersion", value)
def _process_name(self, value: str) -> str: if not value: raise self._invalid_metadata(f"{self.raw_name!r} is a required field") # Validate the name as a side-effect. try: utils.canonicalize_name(value, validate=True) except utils.InvalidName as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc else: return value
def _process_version(self, value: str) -> Version: if not value: raise self._invalid_metadata(f"{self.raw_name!r} is a required field") try: return version_module.parse(value) except version_module.InvalidVersion as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc
def _process_summary(self, value: str) -> str: """Check the field contains no line breaks.""" if _LINE_BOUNDARY_RE.search(value): raise self._invalid_metadata(f"{self.raw_name!r} must be a single line") return value
def _process_description_content_type(self, value: str) -> str: content_types = {"text/plain", "text/x-rst", "text/markdown"} invalid_msg = ( f"{self.raw_name!r} must be one of {list(content_types)}, not {value!r}" ) message = email.message.EmailMessage() try: message["content-type"] = value # The email parser can raise IndexError on malformed RFC 2231 # parameters such as "text/plain; x*". except (ValueError, IndexError) as exc: msg = f"{value!r} is not a valid content type for {self.raw_name!r}" raise self._invalid_metadata(msg, cause=exc) from exc content_type_header = message["content-type"] if content_type_header.defects: defect = content_type_header.defects[0] msg = ( f"{value!r} is not a valid content type for {self.raw_name!r}: {defect}" ) raise self._invalid_metadata(msg, cause=defect) from defect
content_type, parameters = ( # Defaults to `text/plain` if parsing failed. message.get_content_type().lower(), content_type_header.params, ) # Check if content-type is valid or defaulted to `text/plain` and thus was # not parseable. if content_type not in content_types or content_type not in value.lower(): raise self._invalid_metadata(invalid_msg)
charset = parameters.get("charset", "UTF-8") if charset.lower() != "utf-8": raise self._invalid_metadata( f"{self.raw_name!r} can only specify the UTF-8 charset, not {charset!r}" )
markdown_variants = {"GFM", "CommonMark"} variant = parameters.get("variant", "GFM") # Use an acceptable default. if content_type == "text/markdown" and variant not in markdown_variants: raise self._invalid_metadata( f"valid Markdown variants for {self.raw_name!r} are " f"{list(markdown_variants)}, not {variant!r}", ) return value
def _process_dynamic(self, value: list[str]) -> list[str]: dynamic_fields = list(map(str.lower, value)) for dynamic_field in dynamic_fields: if dynamic_field in {"name", "version", "metadata-version"}: raise self._invalid_metadata( f"{dynamic_field!r} is not allowed as a dynamic field" ) elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: raise self._invalid_metadata( f"{dynamic_field!r} is not a valid dynamic field" ) return dynamic_fields
def _process_provides_extra( self, value: list[str], ) -> list[utils.NormalizedName]: normalized_names = [] try: for name in value: normalized_names.append(utils.canonicalize_name(name, validate=True)) except utils.InvalidName as exc: raise self._invalid_metadata( f"{name!r} is invalid for {self.raw_name!r}", cause=exc ) from exc else: return normalized_names
def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: try: return specifiers.SpecifierSet(value) except specifiers.InvalidSpecifier as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc
def _process_requires_dist( self, value: list[str], ) -> list[requirements.Requirement]: reqs = [] try: for req in value: reqs.append(requirements.Requirement(req)) except requirements.InvalidRequirement as exc: raise self._invalid_metadata( f"{req!r} is invalid for {self.raw_name!r}", cause=exc ) from exc else: return reqs
def _process_license_expression(self, value: str) -> NormalizedLicenseExpression: try: return licenses.canonicalize_license_expression(value) except ValueError as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc
def _process_license_files(self, value: list[str]) -> list[str]: paths = [] for path in value: if ".." in path: raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, " "parent directory indicators are not allowed" ) if "*" in path: raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, paths must be resolved" ) if ( pathlib.PurePosixPath(path).is_absolute() or pathlib.PureWindowsPath(path).is_absolute() ): raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, paths must be relative" ) if pathlib.PureWindowsPath(path).as_posix() != path: raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, " "paths must use '/' delimiter" ) paths.append(path) return paths
def _process_import_names(self, value: list[str]) -> list[str]: for import_name in value: name, semicolon, private = import_name.partition(";") name = name.rstrip() for identifier in name.split("."): if not identifier.isidentifier(): raise self._invalid_metadata( f"{name!r} is invalid for {self.raw_name!r}; " f"{identifier!r} is not a valid identifier" ) elif keyword.iskeyword(identifier): raise self._invalid_metadata( f"{name!r} is invalid for {self.raw_name!r}; " f"{identifier!r} is a keyword" ) if semicolon and private.lstrip() != "private": raise self._invalid_metadata( f"{import_name!r} is invalid for {self.raw_name!r}; " "the only valid option is 'private'" ) return value
_process_import_namespaces = _process_import_names
class Metadata: """Representation of distribution metadata.
Compared to :class:`RawMetadata`, this class provides objects representing metadata fields instead of only using built-in types. Any invalid metadata will cause :exc:`InvalidMetadata` to be raised (with a :py:attr:`~BaseException.__cause__` attribute as appropriate).
.. versionadded:: 23.2
.. versionchanged:: 24.0 Optional attributes now return None when the field is absent instead of raising. """
_raw: RawMetadata
@classmethod def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: """Create an instance from :class:`RawMetadata`.
If *validate* is true, all metadata will be validated and all related exceptions will be gathered and raised as an :class:`ExceptionGroup`; otherwise, validation happens per attribute when it is accessed. """ ins = cls() ins._raw = data.copy() # Mutations occur due to caching enriched values.
if validate: collector = _ErrorCollector() metadata_version = None with collector.collect(InvalidMetadata): metadata_version = ins.metadata_version metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
# Make sure to check for the fields that are present, the required # fields (so their absence can be reported). fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS # Remove fields that have already been checked. fields_to_check -= {"metadata_version"}
for key in fields_to_check: try: if metadata_version: # Can't use getattr() as that triggers descriptor protocol which # will fail due to no value for the instance argument. try: field_metadata_version = cls.__dict__[key].added except KeyError: exc = InvalidMetadata(key, f"unrecognized field: {key!r}") collector.error(exc) continue field_age = _VALID_METADATA_VERSIONS.index( field_metadata_version ) if field_age > metadata_age: field = _RAW_TO_EMAIL_MAPPING[key] exc = InvalidMetadata( field, f"{field} introduced in metadata version " f"{field_metadata_version}, not {metadata_version}", ) collector.error(exc) continue getattr(ins, key) except InvalidMetadata as exc: collector.error(exc)
collector.finalize("invalid metadata")
return ins
@classmethod def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: """Parse metadata from email headers.
If *validate* is true, the metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ raw, unparsed = parse_email(data)
if validate: with _ErrorCollector().on_exit("invalid or unparsed metadata") as collector: for unparsed_key in unparsed: if unparsed_key in _EMAIL_TO_RAW_MAPPING: message = f"{unparsed_key!r} has invalid data" else: message = f"unrecognized field: {unparsed_key!r}" collector.error(InvalidMetadata(unparsed_key, message)) try: validated = cls.from_raw(raw, validate=validate) except ExceptionGroup as exc_group: # The no-branch pragmas cover arcs only seen by Python 3.9. for exc in exc_group.exceptions: # pragma: no branch # A required field reported above as unparsed is absent # from `raw`, so skip from_raw's duplicate "missing" # complaint. if not ( isinstance(exc, InvalidMetadata) and exc.field in unparsed and _EMAIL_TO_RAW_MAPPING.get(exc.field) not in raw ): collector.error(exc) else: if not collector.errors: # pragma: no branch return validated
return cls.from_raw(raw, validate=validate)
metadata_version: _Validator[_MetadataVersion] = _Validator() """:external:ref:`core-metadata-metadata-version` (required; validated to be a valid metadata version)""" # `name` is not normalized/typed to NormalizedName so as to provide access to # the original/raw name. name: _Validator[str] = _Validator() """:external:ref:`core-metadata-name` (required; validated using :func:`~packaging.utils.canonicalize_name` and its *validate* parameter)""" version: _Validator[Version] = _Validator() """:external:ref:`core-metadata-version` (required)""" dynamic: _Validator[list[str] | None] = _Validator( added="2.2", ) """:external:ref:`core-metadata-dynamic` (validated against core metadata field names and lowercased)""" platforms: _Validator[list[str] | None] = _Validator() """:external:ref:`core-metadata-platform`""" supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") """:external:ref:`core-metadata-supported-platform`""" summary: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body """:external:ref:`core-metadata-description`""" description_content_type: _Validator[str | None] = _Validator(added="2.1") """:external:ref:`core-metadata-description-content-type` (validated)""" keywords: _Validator[list[str] | None] = _Validator() """:external:ref:`core-metadata-keywords`""" home_page: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-home-page`""" download_url: _Validator[str | None] = _Validator(added="1.1") """:external:ref:`core-metadata-download-url`""" author: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-author`""" author_email: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-author-email`""" maintainer: _Validator[str | None] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer`""" maintainer_email: _Validator[str | None] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer-email`""" license: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-license`""" license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( added="2.4" ) """:external:ref:`core-metadata-license-expression`
.. versionadded:: 24.2 """ license_files: _Validator[list[str] | None] = _Validator(added="2.4") """:external:ref:`core-metadata-license-file`
.. versionadded:: 24.2 """ classifiers: _Validator[list[str] | None] = _Validator(added="1.1") """:external:ref:`core-metadata-classifier`""" requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-dist`""" requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-python`""" # Because `Requires-External` allows for non-PEP 440 version specifiers, we # don't do any processing on the values. requires_external: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-requires-external`""" project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-project-url`""" # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation # regardless of metadata version. provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( added="2.1", ) """:external:ref:`core-metadata-provides-extra`""" provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-provides-dist`""" obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-obsoletes-dist`""" import_names: _Validator[list[str] | None] = _Validator(added="2.5") """:external:ref:`core-metadata-import-name`
.. versionadded:: 26.0 """ import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") """:external:ref:`core-metadata-import-namespace`
.. versionadded:: 26.0 """ requires: _Validator[list[str] | None] = _Validator(added="1.1") """``Requires`` (deprecated)""" provides: _Validator[list[str] | None] = _Validator(added="1.1") """``Provides`` (deprecated)""" obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") """``Obsoletes`` (deprecated)"""
def as_rfc822(self) -> RFC822Message: """ Return an RFC822 message with the metadata.
.. versionadded:: 26.0 """ message = RFC822Message() self._write_metadata(message) return message
def _write_metadata(self, message: RFC822Message) -> None: """ Return an RFC822 message with the metadata. """ for name, validator in self.__class__.__dict__.items(): if isinstance(validator, _Validator) and name != "description": value = getattr(self, name) email_name = _RAW_TO_EMAIL_MAPPING[name] if value is not None: if email_name == "project-url": for label, url in value.items(): message[email_name] = f"{label}, {url}" elif email_name == "keywords": message[email_name] = ",".join(value) elif email_name == "import-name" and value == []: message[email_name] = "" elif isinstance(value, list): for item in value: message[email_name] = str(item) else: message[email_name] = str(value)
# The description is a special case because it is in the body of the message. if self.description is not None: message.set_payload(self.description)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943from __future__ import annotations
import dataclassesimport loggingimport refrom collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetimefrom typing import ( TYPE_CHECKING, Any, Callable, Protocol, TypeVar, cast,)from urllib.parse import unquote, urlparse
from .markers import ( Environment, Marker, _pep440_python_full_version, default_environment,)from .specifiers import SpecifierSetfrom .tags import create_compatible_tags_selector, sys_tagsfrom .utils import ( NormalizedName, is_normalized_name, parse_sdist_filename, parse_wheel_filename,)from .version import Version
if TYPE_CHECKING: # pragma: no cover from collections.abc import Collection, Iterator from pathlib import Path
from typing_extensions import Self
from .tags import Tag
_logger = logging.getLogger(__name__)
__all__ = [ "Package", "PackageArchive", "PackageDirectory", "PackageSdist", "PackageVcs", "PackageWheel", "Pylock", "PylockSelectError", "PylockUnsupportedVersionError", "PylockValidationError", "is_valid_pylock_path",]
def __dir__() -> list[str]: return __all__
_T = TypeVar("_T")_T2 = TypeVar("_T2")
class _FromMappingProtocol(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ...
_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol)
_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$")
def is_valid_pylock_path(path: Path) -> bool: """Check if the given path is a valid pylock file path.""" return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name))
def _toml_key(key: str) -> str: return key.replace("_", "-")
def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 if isinstance(value, (Version, Marker, SpecifierSet)): return str(value) if isinstance(value, Sequence) and key == "environments": return [str(v) for v in value] return value
def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return { _toml_key(key): _toml_value(key, value) for key, value in data if value is not None }
def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type) or ( # Special case: bool is a subclass of int, but TOML distinguishes the two expected_type is int and isinstance(value, bool) ): raise PylockValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value
def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _PylockRequiredKeyError(key) return value
def _get_sequence( d: Mapping[str, Any], expected_item_type: type[_T], key: str) -> Sequence[_T] | None: """Get a list value from the dictionary and verify it's the expected items type.""" if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] return None if isinstance(value, (str, bytes)): # special case: str and bytes are Sequences, but we want to reject it raise PylockValidationError( f"Unexpected type {type(value).__name__} (expected Sequence)", context=key, ) for i, item in enumerate(value): if not isinstance(item, expected_item_type): raise PylockValidationError( f"Unexpected type {type(item).__name__} " f"(expected {expected_item_type.__name__})", context=f"{key}[{i}]", ) return value
def _get_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str,) -> _T2 | None: """Get a value from the dictionary, verify it's the expected type, and convert to the target type.
This assumes the target_type constructor accepts the value. """ if (value := _get(d, expected_type, key)) is None: return None try: return target_type(value) except Exception as e: raise PylockValidationError(e, context=key) from e
def _get_required_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str,) -> _T2: """Get a required value from the dict, verify it's the expected type, and convert to the target type.""" if (value := _get_as(d, expected_type, target_type, key)) is None: raise _PylockRequiredKeyError(key) return value
def _get_sequence_as( d: Mapping[str, Any], expected_item_type: type[_T], target_item_type: Callable[[_T], _T2], key: str,) -> list[_T2] | None: """Get list value from dictionary and verify expected items type.""" if (value := _get_sequence(d, expected_item_type, key)) is None: return None result = [] try: for item in value: typed_item = target_item_type(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result
def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise PylockValidationError(e, context=key) from e
def _get_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str) -> list[_FromMappingProtocolT] | None: """Get a list value from the dictionary and convert its items to a dataclass.""" if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] return None result: list[_FromMappingProtocolT] = [] try: for item in value: typed_item = target_item_type._from_dict(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result
def _get_required_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str) -> Sequence[_FromMappingProtocolT]: """Get a required list value from the dictionary and convert its items to a dataclass.""" if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: raise _PylockRequiredKeyError(key) return result
def _validate_normalized_name(name: str) -> NormalizedName: """Validate that a string is a NormalizedName.""" if not is_normalized_name(name): raise PylockValidationError(f"Name {name!r} is not normalized") return NormalizedName(name)
def _validate_path_url(path: str | None, url: str | None) -> None: if not path and not url: raise PylockValidationError("path or url must be provided")
def _path_name(path: str | None) -> str | None: if not path: return None # If the path is relative it MAY use POSIX-style path separators explicitly # for portability if "/" in path: return path.rsplit("/", 1)[-1] elif "\\" in path: return path.rsplit("\\", 1)[-1] else: return path
def _url_name(url: str | None) -> str | None: if not url: return None url_path = urlparse(url).path # The last path component is percent-encoded, so decode it to the file name return unquote(url_path.rsplit("/", 1)[-1])
def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: if not hashes: raise PylockValidationError("At least one hash must be provided") if not all(isinstance(hash_val, str) for hash_val in hashes.values()): raise PylockValidationError("Hash values must be strings") return hashes
class PylockValidationError(Exception): """Raised when when input data is not spec-compliant."""
context: str | None = None message: str
def __init__( self, cause: str | Exception, *, context: str | None = None, ) -> None: if isinstance(cause, PylockValidationError): if cause.context: self.context = ( f"{context}.{cause.context}" if context else cause.context ) else: self.context = context self.message = cause.message else: self.context = context self.message = str(cause)
def __str__(self) -> str: if self.context: return f"{self.message} in {self.context!r}" return self.message
class _PylockRequiredKeyError(PylockValidationError): def __init__(self, key: str) -> None: super().__init__("Missing required value", context=key)
class PylockUnsupportedVersionError(PylockValidationError): """Raised when encountering an unsupported `lock_version`."""
class PylockSelectError(Exception): """Base exception for errors raised by :meth:`Pylock.select`.
.. versionadded:: 26.1 """
@dataclass(frozen=True, init=False)class PackageVcs: type: str url: str | None = None path: str | None = None requested_revision: str | None = None commit_id: str # type: ignore[misc] subdirectory: str | None = None
def __init__( self, *, type: str, url: str | None = None, path: str | None = None, requested_revision: str | None = None, commit_id: str, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "type", type) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "requested_revision", requested_revision) object.__setattr__(self, "commit_id", commit_id) object.__setattr__(self, "subdirectory", subdirectory)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_vcs = cls( type=_get_required(d, str, "type"), url=_get(d, str, "url"), path=_get(d, str, "path"), requested_revision=_get(d, str, "requested-revision"), commit_id=_get_required(d, str, "commit-id"), subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_vcs.path, package_vcs.url) return package_vcs
@dataclass(frozen=True, init=False)class PackageDirectory: path: str editable: bool | None = None subdirectory: str | None = None
def __init__( self, *, path: str, editable: bool | None = None, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "path", path) object.__setattr__(self, "editable", editable) object.__setattr__(self, "subdirectory", subdirectory)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: return cls( path=_get_required(d, str, "path"), editable=_get(d, bool, "editable"), subdirectory=_get(d, str, "subdirectory"), )
@dataclass(frozen=True, init=False)class PackageArchive: url: str | None = None path: str | None = None size: int | None = None upload_time: datetime | None = None hashes: Mapping[str, str] # type: ignore[misc] subdirectory: str | None = None
def __init__( self, *, url: str | None = None, path: str | None = None, size: int | None = None, upload_time: datetime | None = None, hashes: Mapping[str, str], subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "hashes", hashes) object.__setattr__(self, "subdirectory", subdirectory)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_archive = cls( url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), upload_time=_get(d, datetime, "upload-time"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_archive.path, package_archive.url) return package_archive
@dataclass(frozen=True, init=False)class PackageSdist: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc]
def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_sdist = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_sdist.path, package_sdist.url) return package_sdist
@property def filename(self) -> str: """Get the filename of the sdist.
.. versionadded:: 26.1 """ filename = self.name or _path_name(self.path) or _url_name(self.url) if not filename: raise PylockValidationError("Cannot determine sdist filename") return filename
@dataclass(frozen=True, init=False)class PackageWheel: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc]
def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_wheel = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_wheel.path, package_wheel.url) return package_wheel
@property def filename(self) -> str: """Get the filename of the wheel.""" filename = self.name or _path_name(self.path) or _url_name(self.url) if not filename: raise PylockValidationError("Cannot determine wheel filename") return filename
@dataclass(frozen=True, init=False)class Package: name: NormalizedName version: Version | None = None marker: Marker | None = None requires_python: SpecifierSet | None = None dependencies: Sequence[Mapping[str, Any]] | None = None vcs: PackageVcs | None = None directory: PackageDirectory | None = None archive: PackageArchive | None = None index: str | None = None sdist: PackageSdist | None = None wheels: Sequence[PackageWheel] | None = None attestation_identities: Sequence[Mapping[str, Any]] | None = None tool: Mapping[str, Any] | None = None
def __init__( self, *, name: NormalizedName, version: Version | None = None, marker: Marker | None = None, requires_python: SpecifierSet | None = None, dependencies: Sequence[Mapping[str, Any]] | None = None, vcs: PackageVcs | None = None, directory: PackageDirectory | None = None, archive: PackageArchive | None = None, index: str | None = None, sdist: PackageSdist | None = None, wheels: Sequence[PackageWheel] | None = None, attestation_identities: Sequence[Mapping[str, Any]] | None = None, tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "version", version) object.__setattr__(self, "marker", marker) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "dependencies", dependencies) object.__setattr__(self, "vcs", vcs) object.__setattr__(self, "directory", directory) object.__setattr__(self, "archive", archive) object.__setattr__(self, "index", index) object.__setattr__(self, "sdist", sdist) object.__setattr__(self, "wheels", wheels) object.__setattr__(self, "attestation_identities", attestation_identities) object.__setattr__(self, "tool", tool)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package = cls( name=_get_required_as(d, str, _validate_normalized_name, "name"), version=_get_as(d, str, Version, "version"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] marker=_get_as(d, str, Marker, "marker"), vcs=_get_object(d, PackageVcs, "vcs"), directory=_get_object(d, PackageDirectory, "directory"), archive=_get_object(d, PackageArchive, "archive"), index=_get(d, str, "index"), sdist=_get_object(d, PackageSdist, "sdist"), wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) distributions = bool(package.sdist) + len(package.wheels or []) direct_urls = ( bool(package.vcs) + bool(package.directory) + bool(package.archive) ) if distributions > 0 and direct_urls > 0: raise PylockValidationError( "None of vcs, directory, archive must be set if sdist or wheels are set" ) if distributions == 0 and direct_urls != 1: raise PylockValidationError( "Exactly one of vcs, directory, archive must be set " "if sdist and wheels are not set" ) for i, wheel in enumerate(package.wheels or []): try: (name, version, _, _) = parse_wheel_filename(wheel.filename) except Exception as e: raise PylockValidationError( f"Invalid wheel filename {wheel.filename!r}", context=f"wheels[{i}]", ) from e if name != package.name: raise PylockValidationError( f"Name in {wheel.filename!r} is not consistent with " f"package name {package.name!r}", context=f"wheels[{i}]", ) if package.version and version != package.version: raise PylockValidationError( f"Version in {wheel.filename!r} is not consistent with " f"package version {str(package.version)!r}", context=f"wheels[{i}]", ) if package.sdist: try: name, version = parse_sdist_filename(package.sdist.filename) except Exception as e: raise PylockValidationError( f"Invalid sdist filename {package.sdist.filename!r}", context="sdist", ) from e if name != package.name: raise PylockValidationError( f"Name in {package.sdist.filename!r} is not consistent with " f"package name {package.name!r}", context="sdist", ) if package.version and version != package.version: raise PylockValidationError( f"Version in {package.sdist.filename!r} is not consistent with " f"package version {str(package.version)!r}", context="sdist", ) try: for i, attestation_identity in enumerate( # noqa: B007 package.attestation_identities or [] ): _get_required(attestation_identity, str, "kind") except Exception as e: raise PylockValidationError( e, context=f"attestation-identities[{i}]" ) from e return package
@property def is_direct(self) -> bool: return not (self.sdist or self.wheels)
@dataclass(frozen=True, init=False)class Pylock: """A class representing a pylock file."""
lock_version: Version environments: Sequence[Marker] | None = None requires_python: SpecifierSet | None = None extras: Sequence[NormalizedName] | None = None dependency_groups: Sequence[str] | None = None default_groups: Sequence[str] | None = None created_by: str # type: ignore[misc] packages: Sequence[Package] # type: ignore[misc] tool: Mapping[str, Any] | None = None
def __init__( self, *, lock_version: Version, environments: Sequence[Marker] | None = None, requires_python: SpecifierSet | None = None, extras: Sequence[NormalizedName] | None = None, dependency_groups: Sequence[str] | None = None, default_groups: Sequence[str] | None = None, created_by: str, packages: Sequence[Package], tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "lock_version", lock_version) object.__setattr__(self, "environments", environments) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "extras", extras) object.__setattr__(self, "dependency_groups", dependency_groups) object.__setattr__(self, "default_groups", default_groups) object.__setattr__(self, "created_by", created_by) object.__setattr__(self, "packages", packages) object.__setattr__(self, "tool", tool)
@classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: pylock = cls( lock_version=_get_required_as(d, str, Version, "lock-version"), environments=_get_sequence_as(d, str, Marker, "environments"), extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), dependency_groups=_get_sequence(d, str, "dependency-groups"), default_groups=_get_sequence(d, str, "default-groups"), created_by=_get_required(d, str, "created-by"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), packages=_get_required_sequence_of_objects(d, Package, "packages"), tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) if not Version("1") <= pylock.lock_version < Version("2"): raise PylockUnsupportedVersionError( f"pylock version {pylock.lock_version} is not supported" ) if pylock.lock_version > Version("1.0"): _logger.warning( "pylock minor version %s is not supported", pylock.lock_version ) return pylock
@classmethod def from_dict(cls, d: Mapping[str, Any], /) -> Self: """Create and validate a Pylock instance from a TOML dictionary.
Raises :class:`PylockValidationError` if the input data is not spec-compliant. """ return cls._from_dict(d)
def to_dict(self) -> Mapping[str, Any]: """Convert the Pylock instance to a TOML dictionary.""" return dataclasses.asdict(self, dict_factory=_toml_dict_factory)
def validate(self) -> None: """Validate the Pylock instance against the specification.
Raises :class:`PylockValidationError` otherwise.""" self.from_dict(self.to_dict())
def select( self, *, environment: Environment | None = None, tags: Sequence[Tag] | None = None, extras: Collection[str] | None = None, dependency_groups: Collection[str] | None = None, prefer_sdist_predicate: Callable[[NormalizedName], bool] | None = None, ) -> Iterator[ tuple[ Package, PackageVcs | PackageDirectory | PackageArchive | PackageWheel | PackageSdist, ] ]: """Select what to install from the lock file.
The *environment* and *tags* parameters represent the environment being selected for. If unspecified, ``packaging.markers.default_environment()`` and ``packaging.tags.sys_tags()`` are used.
The *extras* parameter represents the extras to install.
The *dependency_groups* parameter represents the groups to install. If unspecified, the default groups are used.
The *prefer_sdist_predicate* parameter is called for packages with a source distribution. If it returns ``True``, the source distribution is selected before attempting wheel compatibility. If no source distribution is available, wheel selection proceeds as usual without calling the predicate.
This method must be used on valid Pylock instances (i.e. one obtained from :meth:`Pylock.from_dict` or if constructed manually, after calling :meth:`Pylock.validate`).
.. versionadded:: 26.1
.. versionchanged:: 26.3 Added the *prefer_sdist_predicate* parameter. """ compatible_tags_selector = create_compatible_tags_selector( tags if tags is not None else sys_tags() )
# #. Gather the extras and dependency groups to install and set ``extras`` and # ``dependency_groups`` for marker evaluation, respectively. # # #. ``extras`` SHOULD be set to the empty set by default. # #. ``dependency_groups`` SHOULD be the set created from # :ref:`pylock-default-groups` by default. env = cast( "dict[str, str | frozenset[str]]", dict( environment or {}, # Marker.evaluate will fill-up extras=frozenset(extras or []), dependency_groups=frozenset( (self.default_groups or []) if dependency_groups is None # to allow selecting no group else dependency_groups ), ), ) env_python_full_version = _pep440_python_full_version( environment["python_full_version"] if environment else default_environment()["python_full_version"] )
# #. Check if the metadata version specified by :ref:`pylock-lock-version` is # supported; an error or warning MUST be raised as appropriate. # Covered by lock.validate() which is a precondition for this method.
# #. If :ref:`pylock-requires-python` is specified, check that the environment # being installed for meets the requirement; an error MUST be raised if it is # not met. if self.requires_python and not self.requires_python.contains( env_python_full_version, ): raise PylockSelectError( f"python_full_version {env_python_full_version!r} " f"in provided environment does not satisfy the Python version " f"requirement {str(self.requires_python)!r}" )
# #. If :ref:`pylock-environments` is specified, check that at least one of the # environment marker expressions is satisfied; an error MUST be raised if no # expression is satisfied. if self.environments: for env_marker in self.environments: if env_marker.evaluate( cast("dict[str, str]", environment or {}), context="requirement" ): break else: raise PylockSelectError( "Provided environment does not satisfy any of the " "environments specified in the lock file" )
# #. For each package listed in :ref:`pylock-packages`: selected_packages_by_name: dict[str, tuple[int, Package]] = {} for package_index, package in enumerate(self.packages): # #. If :ref:`pylock-packages-marker` is specified, check if it is # satisfied;if it isn't, skip to the next package. if package.marker and not package.marker.evaluate(env, context="lock_file"): continue
# #. If :ref:`pylock-packages-requires-python` is specified, check if it is # satisfied; an error MUST be raised if it isn't. if package.requires_python and not package.requires_python.contains( env_python_full_version, ): raise PylockSelectError( f"python_full_version {env_python_full_version!r} " f"in provided environment does not satisfy the Python version " f"requirement {str(package.requires_python)!r} for package " f"{package.name!r} at packages[{package_index}]" )
# #. Check that no other conflicting instance of the package has been slated # to be installed; an error about the ambiguity MUST be raised otherwise. if package.name in selected_packages_by_name: raise PylockSelectError( f"Multiple packages with the name {package.name!r} are " f"selected at packages[{package_index}] and " f"packages[{selected_packages_by_name[package.name][0]}]" )
# #. Check that the source of the package is specified appropriately (i.e. # there are no conflicting sources in the package entry); # an error MUST be raised if any issues are found. # Covered by lock.validate() which is a precondition for this method.
# #. Add the package to the set of packages to install. selected_packages_by_name[package.name] = (package_index, package)
# #. For each package to be installed: for package_index, package in selected_packages_by_name.values(): # - If :ref:`pylock-packages-vcs` is set: if package.vcs is not None: yield package, package.vcs
# - Else if :ref:`pylock-packages-directory` is set: elif package.directory is not None: yield package, package.directory
# - Else if :ref:`pylock-packages-archive` is set: elif package.archive is not None: yield package, package.archive
# - Else if source preference selects an available # :ref:`pylock-packages-sdist`: elif ( package.sdist is not None and prefer_sdist_predicate is not None and prefer_sdist_predicate(package.name) ): yield package, package.sdist
# - Else if there are entries for :ref:`pylock-packages-wheels`: elif package.wheels: # #. Look for the appropriate wheel file based on # :ref:`pylock-packages-wheels-name`; if one is not found then move # on to :ref:`pylock-packages-sdist` or an error MUST be raised about # a lack of source for the project. best_wheel = next( compatible_tags_selector( (wheel, parse_wheel_filename(wheel.filename)[-1]) for wheel in package.wheels ), None, ) if best_wheel: yield package, best_wheel elif package.sdist is not None: yield package, package.sdist else: raise PylockSelectError( f"No wheel found matching the provided tags " f"for package {package.name!r} " f"at packages[{package_index}], " f"and no sdist available as a fallback" )
# - Else if no :ref:`pylock-packages-wheels` file is found or # :ref:`pylock-packages-sdist` is solely set: elif package.sdist is not None: yield package, package.sdist
else: # Covered by lock.validate() which is a precondition for this method. raise NotImplementedError # pragma: no cover123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details."""Public :class:`VersionRange` API.
A set-algebra view of the versions accepted by a:class:`~packaging.specifiers.SpecifierSet`. Ranges support intersection,union, complement, and difference; membership and filtering match theoriginating specifier set; and conversion back to a:class:`~packaging.specifiers.SpecifierSet` is available where a PEP 440 formexists.
.. testsetup::
from packaging.ranges import VersionRange from packaging.specifiers import SpecifierSet from packaging.version import Version"""
from __future__ import annotations
import enumimport typingfrom typing import ( TYPE_CHECKING, Any, TypeVar, Union,)
from ._ranges import ( FULL_RANGE, MIN_VERSION, NEG_INF, POS_INF, BoundaryKind, BoundaryVersion, LowerBound, UpperBound, coerce_version, filter_by_ranges, intersect_ranges, least_version_above, matches_bounds_only, range_is_empty, ranges_are_prerelease_only, trim_release,)from .version import Version
if TYPE_CHECKING: from collections.abc import Callable, Iterable, Iterator, Sequence
from ._ranges import Interval from .specifiers import SpecifierSet
__all__ = ["VersionRange"]
T = TypeVar("T")UnparsedVersion = Union[Version, str]UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
#: The most ``!=`` exclusion fragments (``!=V`` points or ``!=P.*`` prefixes)#: that :meth:`VersionRange.to_specifier_set` will materialize to spell a#: single gap or run. Every site that expands a version-number-driven chain#: charges it against this cap, and chains that spell one gap together share#: it (see :func:`_decompose_dev0_gap` and :func:`_encode_gap`),#: so no gap ever materializes more than this many exclusions. Past the cap#: the recovery returns ``None`` rather than emit the unbounded chain a range#: such as ``==5.* | ==1000000.*`` would otherwise drive._MAX_EXCLUSION_RUN = 128
class _SetOp(enum.Enum): """The binary set operation ``_combine_literals`` resolves over ``===`` literals."""
INTERSECTION = enum.auto() UNION = enum.auto() DIFFERENCE = enum.auto()
def __dir__() -> list[str]: return __all__
# Range algebra: intersection and the empty-interval test live in the engine# (``intersect_ranges`` / ``range_is_empty``); union and complement are only# needed here, so they live in this module.
def _union_ranges( left: Sequence[Interval], right: Sequence[Interval],) -> list[Interval]: """Union two sorted, non-overlapping interval lists.
A linear merge over the two pre-sorted inputs followed by a single coalescing pass: adjacent or overlapping intervals collapse so the result is itself sorted and non-overlapping. """ if not left: return list(right) if not right: return list(left)
merged_input: list[Interval] = [] left_index = right_index = 0 while left_index < len(left) and right_index < len(right): if left[left_index][0] <= right[right_index][0]: merged_input.append(left[left_index]) left_index += 1 else: merged_input.append(right[right_index]) right_index += 1 merged_input.extend(left[left_index:]) merged_input.extend(right[right_index:])
merged: list[Interval] = [merged_input[0]] for lower, upper in merged_input[1:]: prev_lower, prev_upper = merged[-1]
if ( prev_upper.version is None or lower.version is None or prev_upper.version > lower.version ): overlaps = True elif prev_upper.version == lower.version: overlaps = prev_upper.inclusive or lower.inclusive else: # An ordering gap may still hold no version when the two bounds # straddle a synthetic boundary; merge across an empty gap to # stay canonical. gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) gap_upper = UpperBound(lower.version, not lower.inclusive) overlaps = range_is_empty(gap_lower, gap_upper)
if overlaps: merged[-1] = (prev_lower, max(prev_upper, upper)) else: merged.append((lower, upper))
return merged
def _complement_ranges(ranges: Sequence[Interval]) -> list[Interval]: """Complement a sorted, non-overlapping interval list.
Yields the gaps between intervals plus a leading gap before the first and a trailing gap after the last. Bound inclusivity flips so that complement-of-complement round-trips back to the input. """ if not ranges: return list(FULL_RANGE)
result: list[Interval] = [] prev_upper: UpperBound | None = None
for lower, upper in ranges: if prev_upper is None: # Leading gap below the first interval. Every range reaching here is # floor-canonical: ``_canonical_floor`` has already folded an # inclusive lower at or below ``0.dev0`` into ``-inf``. So a finite # first lower always leaves a non-empty gap down to ``-inf``, while a # ``-inf`` lower leaves no leading gap at all. if lower.version is not None: gap_upper = UpperBound(lower.version, not lower.inclusive) result.append((NEG_INF, gap_upper)) else: gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) gap_upper = UpperBound(lower.version, not lower.inclusive) # Input intervals are canonical (sorted, disjoint, non-touching), # so the gap between two of them always holds at least one version. result.append((gap_lower, gap_upper)) prev_upper = upper
# The empty-input early return guarantees the loop ran. assert prev_upper is not None if prev_upper.version is not None: gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) result.append((gap_lower, POS_INF))
return result
def _canonical_floor(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: """Collapse the PEP 440 floor in a sorted interval list.
Only the first interval can touch ``0.dev0`` (the minimum version). An inclusive lower at or below it admits everything below, the same as ``-inf``, so ``>=0.dev0`` becomes the one canonical full range. An exclusive upper at or below it leaves the interval empty, so it is dropped. """ if not bounds: return bounds
lower, upper = bounds[0] if range_is_empty(NEG_INF, upper): return bounds[1:]
if ( lower.inclusive and isinstance(lower.version, Version) and lower.version <= MIN_VERSION ): return ((NEG_INF, upper), *bounds[1:])
return bounds
def _predecessor_boundary(version: Version) -> BoundaryVersion | None: """The boundary whose least successor is *version*, or ``None``.
Inverse of :func:`~packaging._ranges.least_version_above`. A plain version that is exactly such a successor (``1.0a2.dev0`` sits just above ``AFTER_POSTS(1.0a1)``) folds back to that boundary, so ``>=1.0a2.dev0`` and ``>1.0a1`` share one form. The proposed boundary is confirmed by round-tripping through ``least_version_above``. """ # Only a least successor carries a dev segment, so nothing else can fold. if version.dev is None: return None
candidate: BoundaryVersion | None = None if version.pre is not None and version.dev == 0 and version.post is None: # 1.0a2.dev0 -> AFTER_POSTS(1.0a1) kind, number = version.pre if number >= 1: candidate = BoundaryVersion( version.__replace__(pre=(kind, number - 1), dev=None), BoundaryKind.AFTER_POSTS, ) elif version.dev >= 1: # 1.0.dev3 -> AFTER_LOCALS(1.0.dev2) candidate = BoundaryVersion( version.__replace__(dev=version.dev - 1), BoundaryKind.AFTER_LOCALS ) elif version.dev == 0 and version.post is not None: # 1.0.post1.dev0 -> AFTER_LOCALS(1.0.post0); 1.0.post0.dev0 -> AFTER_LOCALS(1.0) base = ( version.__replace__(post=None, dev=None) if version.post == 0 else version.__replace__(post=version.post - 1, dev=None) ) candidate = BoundaryVersion(base, BoundaryKind.AFTER_LOCALS)
if candidate is not None and least_version_above(candidate) == version: return candidate return None
def _canonicalize(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: """Fold least-successor bounds to their boundary form.
``>=1.0a2.dev0`` and ``>1.0a1`` denote the same set, so both must reduce to one representation for ``==`` and ``hash`` to agree. An inclusive lower or exclusive upper sitting on a boundary's least successor becomes that boundary; the engine's emptiness check has already dropped the synthetic gaps such intervals would otherwise leave. """ result: list[Interval] = [] for lower, upper in bounds: new_lower, new_upper = lower, upper
if isinstance(lower.version, Version) and lower.inclusive: boundary = _predecessor_boundary(lower.version) if boundary is not None: new_lower = LowerBound(boundary, inclusive=False)
if isinstance(upper.version, Version) and not upper.inclusive: boundary = _predecessor_boundary(upper.version) if boundary is not None: new_upper = UpperBound(boundary, inclusive=True)
result.append((new_lower, new_upper)) return tuple(result)
def _struct_admits( bounds: tuple[Interval, ...], admit_arbitrary: bool, literal: str) -> bool: """True when the bounds (plus arbitrary admission) admit ``literal``.
Skips the explicit admit/reject sets, which the caller layers on top. A non-version string matches via ``admit_arbitrary`` only on full bounds; on narrower bounds the flag is metadata only. """ parsed = coerce_version(literal) if parsed is None: return admit_arbitrary and bounds == FULL_RANGE
return matches_bounds_only(bounds, parsed)
# Repr helpers:
def _bound_version_str(value: BoundaryVersion | Version) -> str: """Printout for a bound's inner value, kind-tagged for boundaries.""" if isinstance(value, BoundaryVersion): return f"{value.version}[{value.kind.name}]" return str(value)
def _format_lower(bound: LowerBound) -> str: if bound.version is None: return "(-inf" bracket = "[" if bound.inclusive else "(" return f"{bracket}{_bound_version_str(bound.version)}"
def _format_upper(bound: UpperBound) -> str: if bound.version is None: return "+inf)" bracket = "]" if bound.inclusive else ")" return f"{_bound_version_str(bound.version)}{bracket}"
def _format_intervals(intervals: Sequence[Interval]) -> str: """Render a sorted interval list as ``lower, upper | lower, upper``.""" return " | ".join( f"{_format_lower(lower)}, {_format_upper(upper)}" for lower, upper in intervals )
# ``to_specifier_set`` recovery: encode a range's interval list back into# specifier fragments. Each helper returns ``None`` when its shape has no# PEP 440 form. The ``keep_dev0`` argument threaded through is a spelling# mode, not a pre-release policy: false emits a prerelease-free form (no# synthetic ``.dev0``, so the recovered range has an empty opt-in region),# true keeps the ``.dev0`` markers (so the range opts its bounds in).# ``to_specifier_set`` encodes in both modes and keeps whichever round-trips.## Bound and interval encoding: turn one interval's bounds into fragments.
def _is_dev0_version(version: Version) -> bool: """True when version is exactly ``X[.Y]*.dev0`` (the shape ``<X`` makes).""" return ( version.dev == 0 and version.pre is None and version.post is None and version.local is None )
def _clean_lower(version: Version) -> list[str] | None: """A prerelease-free spelling for an inclusive ``[version`` lower, or ``None``.
Several ``[V`` lowers come from an operator whose own spelling carries no synthetic ``.dev0``. Recovering that spelling gives the range an empty opt-in region, so it is offered in the prerelease-free spelling mode (see :meth:`VersionRange.to_specifier_set`). """ if version.dev != 0 or version.pre is not None or version.local is not None: return None
# ``[B.post(k).dev0`` is the lower ``>B.post(k-1)`` builds (k >= 1). if version.post is not None: if version.post < 1: return None return [f">{version.__replace__(post=version.post - 1, dev=None)}"]
# ``[F.dev0`` is family F's base. The prefix P just below F has # ``==P.* == [P.dev0, F.dev0)``, so ``>=P,!=P.*`` lands exactly on ``[F.dev0``. family = trim_release(version.release) last = family[-1] if last < 1: return None
below_release = (*family[:-1], last - 1) below = Version.from_parts(epoch=version.epoch, release=below_release)
# At the epoch-0 floor ``==P.*`` already reaches ``0.dev0``, so the ``>=P`` # half is redundant: ``[1.dev0, +inf)`` is plain ``!=0.*``. if version.epoch == 0 and not any(below_release): return [f"!={below}.*"]
return [f">={below}", f"!={below}.*"]
def _epoch_floor_lower( lower: LowerBound, upper: UpperBound) -> tuple[Version, int, bool] | None: """The ``E!0`` family of a lower sitting on an epoch>0 zero-family floor.
An epoch>0 zero-family base such as ``1!0.dev0`` has no ``>=P,!=P.*`` spelling since no version sorts below ``E!0`` within the epoch. While the interval stays within ``==E!0.*`` it is that wildcard, trimmed by the upper and with a leading ``.dev`` run excluded: an ``AFTER_LOCALS(E!0.dev(k))`` lower drops ``E!0.dev0..E!0.dev(k)``, a plain inclusive ``E!0.dev0`` lower drops none. Returns the ``E!0`` family, how many leading ``.dev`` releases to exclude, and whether the upper sits at the family cap (so ``==E!0.*`` needs no upper), else ``None``. """ version = lower.version if isinstance(version, BoundaryVersion): if version.kind != BoundaryKind.AFTER_LOCALS: return None version = version.version if version.dev is None: return None excluded_devs = version.dev + 1 elif isinstance(version, Version) and lower.inclusive: # A plain inclusive lower only reaches the floor as ``>=E!0.dev0``; # higher ``.dev`` would have canonicalized to an AFTER_LOCALS boundary. if version.dev != 0: return None excluded_devs = 0 else: return None
# Only the bare ``E!0`` floor of a non-zero epoch qualifies. if version.epoch == 0: return None if version.pre is not None or version.post is not None or version.local is not None: return None if any(trim_release(version.release)): return None
# ``==E!0.*`` spans ``[E!0.dev0, E!1.dev0)``; it fits only below that cap. next_family = Version.from_parts(epoch=version.epoch, release=(1,), dev=0) cap = UpperBound(next_family, False) if upper > cap: return None
family = Version.from_parts(epoch=version.epoch, release=(0,)) return family, excluded_devs, upper == cap
def _dev_family_anchor(family: Version) -> list[str] | None: """Prerelease-free fragments for ``[family, ..)``, or ``None`` if it has none.
``family`` is an ``X.dev0``. The floor gives ``[]`` (every version); a release base its ``_clean_lower`` family-floor spelling (``!=0.*`` ...); an ``X.post0`` base ``>=X,!=X``. A pre-release base has no prerelease-free spelling. """ if family <= MIN_VERSION: return [] clean = _clean_lower(family) if clean is not None: return clean if family.pre is None and family.post == 0: base = family.__replace__(post=None, dev=None) return [f">={base}", f"!={base}"] return None
def _encode_lower(lower: LowerBound, keep_dev0: bool) -> list[str] | None: """Encode a lower bound as specifier fragments, or ``None``.
``[]`` for ``-inf``. An ``AFTER_POSTS(V)`` lower is ``>V``. An ``AFTER_LOCALS(V)`` lower is the set ``[successor, ..)`` and emits ``>=V,!=V``, except in the prerelease-free spelling mode (``keep_dev0`` false), where it recovers a spelling with no synthetic ``.dev0`` when one exists: ``>3.8.post1`` for a post release, or a dev family's anchor plus the dev run up to V for a ``.dev`` release. """ lower_version = lower.version if lower_version is None: return []
if isinstance(lower_version, BoundaryVersion): if lower_version.kind == BoundaryKind.AFTER_POSTS: # AFTER_POSTS only ever appears as an exclusive ``>V`` lower. return [f">{lower_version.version}"] inner = lower_version.version if inner <= MIN_VERSION: # The ``(-inf, V)`` side was dropped at the floor, so the lone # ``(AFTER_LOCALS(0.dev0), +inf)`` interval is exactly ``!=0.dev0``. return [f"!={inner}"] # An ``(AFTER_LOCALS(V), ..)`` lower is the set ``[successor, ..)``. In # the prerelease-free mode, recover a spelling with no synthetic ``.dev0`` # so the range's opt-in region stays empty. if not keep_dev0: if inner.dev is not None: # A ``.dev`` V makes ``[successor, ..)`` its dev family's # prerelease-free anchor minus the finite dev run up to ``V`` # (e.g. ``>=1.0,!=1.0,!=1.0.post0.dev0``), carrying no synthetic # ``.dev0``. family = inner.__replace__(dev=0) anchor = _dev_family_anchor(family) if anchor is not None: if inner.dev + 1 > _MAX_EXCLUSION_RUN: return None run = [ f"!={family.__replace__(dev=d)}" for d in range(inner.dev + 1) ] return anchor + run else: # A ``.post`` release recovers its prerelease-free ``>`` spelling # from the successor (``>3.8.post1`` for ``AFTER_LOCALS(3.8.post1)``). successor = least_version_above(lower_version) clean = _clean_lower(successor) if successor is not None else None if clean is not None: return clean # Otherwise it is ``[V, ..)`` minus V's local family, i.e. ``>=V,!=V``. # The prerelease-free recoveries above have already returned in that mode; # a residual ``.dev`` V here opts pre-releases in, so this spelling round # trips only for a range whose opt-in region wants it. return [f">={inner}", f"!={inner}"]
if not lower.inclusive: return None
# In the prerelease-free mode a ``.dev0`` lower prefers its clean spelling. if not keep_dev0: clean = _clean_lower(lower_version) if clean is not None: return clean return [f">={lower_version}"]
def _encode_upper(upper: UpperBound, keep_dev0: bool) -> list[str] | None: """Encode an upper bound as specifier fragments, or ``None``.
``[]`` for ``+inf``. In the prerelease-free spelling mode (``keep_dev0`` false) the ``<X`` spelling is used for the ``X.dev0`` upper that ``<X`` builds; otherwise the synthetic ``.dev0`` is kept so the range opts its bounds in. """ upper_version = upper.version if upper_version is None: return []
if isinstance(upper_version, BoundaryVersion): # A boundary upper is always inclusive (a boundary already sits between # versions, so no specifier produces an exclusive one). if upper_version.kind == BoundaryKind.AFTER_LOCALS: inner = upper_version.version if ( not keep_dev0 and inner.pre is None and inner.post is not None and inner.dev is None ): # ``AFTER_LOCALS(post-release)]`` upper is ``<next-post`` (e.g. # ``<3.8.post1`` for ``AFTER_LOCALS(3.8.post0)``), the ``<P`` # spelling a post-release upper builds, with no ``.dev0``. return [f"<{inner.__replace__(post=inner.post + 1)}"] return [f"<={inner}"] # ``AFTER_POSTS(P)`` sits just below the next pre-release's ``.dev0`` # (canonicalization of a ``<P.preN.dev0`` upper), so it is ``<`` that # least successor. A final-release AFTER_POSTS has no successor or form. successor = least_version_above(upper_version) if successor is not None: return [f"<{successor}"] return None
if not upper.inclusive: # ``<X`` builds an exclusive ``X.dev0`` upper (X final or post-release; # never pre/local). ``<X`` and ``<X.dev0`` define the same bound but # differ in the opt-in they imply, so pick by the spelling mode. if ( upper_version.dev == 0 and upper_version.pre is None and upper_version.local is None ): if not keep_dev0: return [f"<{upper_version.__replace__(dev=None)}"] return [f"<{upper_version}"] # ``V`` (exclusive) upper, including V's pre-releases. return [f"<={upper_version}", f"!={upper_version}"] return None
def _detect_equal_wildcard(lower: LowerBound, upper: UpperBound) -> Version | None: """If ``[lower, upper)`` is the ``==V.*`` shape, return ``V``.""" if isinstance(lower.version, BoundaryVersion) or isinstance( upper.version, BoundaryVersion ): return None if lower.version is None or upper.version is None: return None if not lower.inclusive or upper.inclusive: return None if not (_is_dev0_version(lower.version) and _is_dev0_version(upper.version)): return None if lower.version.epoch != upper.version.epoch: return None
lower_release = trim_release(lower.version.release) upper_release = trim_release(upper.version.release) padded_length = max(len(lower_release), len(upper_release)) assert padded_length > 0 lower_release += (0,) * (padded_length - len(lower_release)) upper_release += (0,) * (padded_length - len(upper_release))
if lower_release[:-1] != upper_release[:-1]: return None
# A genuine ``==V.*`` spans one family: the upper is exactly the next prefix. # A wider span like ``[3.8.dev0, 3.14.dev0)`` shares the prefix but is not a # single wildcard, so it falls through to the generic ``>=...,<...`` form. if upper_release[-1] != lower_release[-1] + 1: return None
return lower.version.__replace__(release=lower_release, dev=None)
def _encode_interval( lower: LowerBound, upper: UpperBound, keep_dev0: bool) -> list[str] | None: """Encode one interval as specifier fragments, or ``None``.
Special-cases the ``==V`` singleton (``[V, AFTER_LOCALS(V)]`` for a plain ``V``, and ``[V+local, V+local]`` for a local one) and the ``==V.*`` shape so the fragment is one equality rather than a bound pair. """ # ``[V+local, V+local]`` (an inclusive local point) is the singleton ``==V+local``. if ( lower.version is not None and upper.version is not None and not isinstance(lower.version, BoundaryVersion) and not isinstance(upper.version, BoundaryVersion) and lower.inclusive and upper.inclusive and lower.version == upper.version and lower.version.local is not None ): return [f"=={lower.version}"]
# ``[V, AFTER_LOCALS(V)]`` (V without a local) is the singleton ``==V``, # which also matches V's local family: one equality, not ``>=V,<=V``. if ( isinstance(lower.version, Version) and lower.inclusive and upper.inclusive and isinstance(upper.version, BoundaryVersion) and upper.version.kind == BoundaryKind.AFTER_LOCALS and upper.version.version == lower.version ): return [f"=={lower.version}"]
wildcard = _detect_equal_wildcard(lower, upper) if wildcard is not None: return [f"=={wildcard}.*"]
# A ``[E!0.dev0`` lower has no prerelease-free ``>=`` spelling; within its own # family it is ``==E!0.*`` trimmed by the upper. floor = _epoch_floor_lower(lower, upper) if not keep_dev0 else None if floor is not None: family, excluded_devs, upper_at_cap = floor if excluded_devs > _MAX_EXCLUSION_RUN: return None parts = [f"=={family}.*"] parts.extend(f"!={family.__replace__(dev=d)}" for d in range(excluded_devs))
# ``==E!0.*`` already caps at the next family; add the upper only if tighter. if not upper_at_cap: upper_parts = _encode_upper(upper, keep_dev0) if upper_parts is None: return None parts.extend(upper_parts)
return parts
lower_parts = _encode_lower(lower, keep_dev0) if lower_parts is None: return None
upper_parts = _encode_upper(upper, keep_dev0) if upper_parts is None: return None
return lower_parts + upper_parts
# Gap encoding: spell the gap between two adjacent intervals as exclusions.
def _detect_not_equal( left_upper: UpperBound, right_lower: LowerBound) -> list[Version] | None: """If the gap between two intervals is a ``!=V`` chain, list its points.
A plain exclusive left upper names the first excluded V directly; an inclusive boundary left upper names it via its least successor. Adjacent exclusions (``V`` and its immediate successors) share a single gap spanning a contiguous dev run, so one gap can name a short chain: ``!=1.0,!=1.0.post0.dev0`` is one gap from ``1.0`` up to ``AFTER_LOCALS(1.0.post0.dev0)``. """ if isinstance(left_upper.version, BoundaryVersion): # A boundary upper is always inclusive; its least successor is the first # excluded V (``None`` for a final AFTER_POSTS, which names no point). first = least_version_above(left_upper.version) if first is None: return None elif left_upper.version is None or left_upper.inclusive: return None else: first = left_upper.version
if not isinstance(right_lower.version, BoundaryVersion): if ( right_lower.version is not None and not right_lower.inclusive and right_lower.version == first and first.local is not None ): return [first] return None
if right_lower.version.kind != BoundaryKind.AFTER_LOCALS: return None
# The right interval resumes just above the last excluded V and its locals. last = right_lower.version.version if first == last: return [first]
# Adjacent exclusions: the successor of ``first`` opens a ``.dev`` family and # every later point is a higher ``.dev`` in that same family, so the gap is # exactly ``first`` plus a contiguous dev run up to ``last``. Any other gap # (e.g. ``2.3`` to ``AFTER_LOCALS(2.7)`` from complementing ``>=2.3,<=2.7``) # spans a whole interval and fails this test. second = least_version_above(BoundaryVersion(first, BoundaryKind.AFTER_LOCALS)) if ( second is not None and second.dev is not None and last.dev is not None and last.dev >= second.dev and last.__replace__(dev=second.dev) == second ): # ``first`` and the run spell this gap together, so they share the cap. if last.dev - second.dev + 2 > _MAX_EXCLUSION_RUN: return None run = (second.__replace__(dev=d) for d in range(second.dev, last.dev + 1)) return [first, *run] return None
def _decompose_dev0_gap( lower_trim: tuple[int, ...], upper_trim: tuple[int, ...], epoch: int, budget: int = _MAX_EXCLUSION_RUN,) -> list[Version] | None: """Decompose the gap ``[L.dev0, U.dev0)`` into wildcard prefixes.
``lower_trim``/``upper_trim`` are trimmed release tuples with ``lower_trim < upper_trim`` lexicographically. The chain sweeps at the first differing level. The gap is undecomposable when L has trailing components below that level (the chain cannot escape L's subtree), or when the chain, summed across levels, would exceed ``budget`` prefixes. """ diff = 0 while ( diff < len(lower_trim) and diff < len(upper_trim) and lower_trim[diff] == upper_trim[diff] ): diff += 1
if len(lower_trim) > diff + 1: return None
common = lower_trim[:diff] lower_val = lower_trim[diff] if len(lower_trim) > diff else 0 upper_val = upper_trim[diff]
span = upper_val - lower_val if span > budget: return None
fragments = [ Version.from_parts(epoch=epoch, release=(*common, segment)) for segment in range(lower_val, upper_val) ]
if len(upper_trim) == diff + 1: return fragments
# Recurse into the next release component, charging at least one to the budget # per level (not just the span), so a run of zero-span levels (a release with # many trailing components) exhausts the budget and returns None instead of # recursing past the interpreter's stack limit. tail = _decompose_dev0_gap( (*common, upper_val), upper_trim, epoch, budget - max(span, 1) ) if tail is None: return None return fragments + tail
def _encode_gap(left_upper: UpperBound, right_lower: LowerBound) -> list[str] | None: """Encode the gap between two adjacent intervals as ``!=`` fragments.
A point chain becomes ``!=V`` fragments and a dev0 family span becomes ``!=P.*`` prefixes, followed by a leading dev run in the last family when the gap ends inside it. Any other gap has no exclusion form and returns ``None``. """ # Cheapest first: a plain ``!=V`` chain never pays for the budgeted # wildcard sweep below. points = _detect_not_equal(left_upper, right_lower) if points is not None: return [f"!={point}" for point in points]
# Both wildcard shapes start at an exclusive family base ``L.dev0``. left_v = left_upper.version if ( not isinstance(left_v, Version) or left_upper.inclusive or not _is_dev0_version(left_v) ): return None
right_v = right_lower.version if isinstance(right_v, Version) and right_lower.inclusive: # ``[L.dev0, U.dev0)`` is a pure ``!=P.*`` chain up to U's family. upper_dev0 = right_v run_length = 0 budget = _MAX_EXCLUSION_RUN elif ( isinstance(right_v, BoundaryVersion) and right_v.kind == BoundaryKind.AFTER_LOCALS and not right_lower.inclusive ): # ``[L.dev0, AFTER_LOCALS(U.dev(k))]`` ends inside U's family: the # ``!=P.*`` chain, then the ``U.dev0..U.dev(k)`` run. Both spell the # gap together, so they share one ``_MAX_EXCLUSION_RUN`` budget. upper = right_v.version if upper.dev is None or upper.dev + 1 > _MAX_EXCLUSION_RUN: return None upper_dev0 = upper.__replace__(dev=0) run_length = upper.dev + 1 budget = _MAX_EXCLUSION_RUN - run_length else: return None
# ``U`` must be a plain release base in L's epoch, above L. # ``_is_dev0_version`` on ``U.dev0`` rejects any pre/post/local on ``U``. if not _is_dev0_version(upper_dev0): return None if left_v.epoch != upper_dev0.epoch or left_v >= upper_dev0: return None
prefixes = _decompose_dev0_gap( trim_release(left_v.release), trim_release(upper_dev0.release), left_v.epoch, budget, ) if prefixes is None: return None
exclusions = [f"!={prefix}.*" for prefix in prefixes] exclusions.extend(f"!={upper_dev0.__replace__(dev=d)}" for d in range(run_length)) return exclusions
def _encode_gaps(bounds: Sequence[Interval]) -> list[str] | None: """Encode every between-interval gap as ``!=`` fragments, or ``None``.
When each gap has an exclusion spelling, the intervals fuse into one contiguous span (``==1.* | ==3.*`` is ``!=0.*,!=2.*,<4``): the outer interval across all the bounds plus these exclusions. A gap with no exclusion spelling makes the bounds a disjoint union, which no single set expresses. """ exclusions: list[str] = []
for index in range(1, len(bounds)): gap = _encode_gap(bounds[index - 1][1], bounds[index][0]) if gap is None: return None exclusions.extend(gap)
return exclusions
def _tighten_no_prereleases(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: """Snap the range's final upper out of the pre-release band ``False`` drops.
An exclusive upper at a final ``V`` admits the versions in ``[V.dev0, V)`` at the bounds level, but a ``prereleases=False`` policy filters them all out, so it accepts the same releases as ``<V`` (upper at ``V.dev0``). Snapping it lets :meth:`VersionRange.to_specifier_set` reach the ``<V`` spelling.
Only the last interval's upper is snapped, the one that gives a terser outer bound. Inner uppers are left alone: snapping one turns its gap to the next interval into a ``.dev0`` wildcard gap, which a far-apart neighbour would blow up into an unbounded ``!=N.*`` chain. Those shapes recover as ``None`` here, the same as under ``None`` / ``True``. The snap is conservative (it skips boundary, pre-release, and local uppers); the caller keeps it only when it stays release-equivalent, so an unsnapped shape falls back to the exact form. """ lower, upper = bounds[-1] version = upper.version if ( isinstance(version, Version) and not upper.inclusive and not version.is_prerelease and version.local is None ): upper = UpperBound(version.__replace__(dev=0), inclusive=False) return (*bounds[:-1], (lower, upper)) return bounds
class VersionRange: """A set of :class:`~packaging.version.Version` values accepted by a :class:`~packaging.specifiers.SpecifierSet`.
Construct via :meth:`~packaging.specifiers.SpecifierSet.to_range`, or with the :meth:`full`, :meth:`empty`, and :meth:`singleton` class methods. Compose with :meth:`intersection`, :meth:`union`, :meth:`complement`, and :meth:`difference` (or the ``&`` / ``|`` / ``~`` / ``-`` operators). Test membership with ``in`` or :meth:`contains`, filter an iterable with :meth:`filter`, and convert back to a :class:`~packaging.specifiers.SpecifierSet` with :meth:`to_specifier_set`.
The configured pre-release policy of the originating specifier set carries onto the range and controls whether pre-releases are admitted under ``in``, :meth:`contains`, and :meth:`filter`. With no configured policy, :meth:`filter` also admits pre-releases in the autodetected opt-in region (the versions a pre-release-naming specifier asked for). Set algebra keeps that opt-in scoped to those versions, so unrelated pre-releases are not admitted wholesale.
:meth:`intersection`, :meth:`union`, :meth:`difference`, and the :meth:`is_subset` / :meth:`is_superset` / :meth:`is_disjoint` predicates require both operands to share the same configured policy.
>>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> "1.5" in r True >>> "2.0" in r False >>> SpecifierSet(">=2.0,<1.0").to_range().is_empty True
PEP 440's ``===`` operator matches a candidate string verbatim (case-insensitive) rather than a set of versions. Ranges built from ``===`` specifiers still support membership, set operations, and conversion back to a :class:`~packaging.specifiers.SpecifierSet`; matching follows the literal-equality rule. A ``===`` literal that names a pre-release is admitted under the default policy by both :meth:`contains` and :meth:`filter`, since it was named outright.
.. versionadded:: 26.3 """
__slots__ = ( "_admit", "_admit_arbitrary", "_bounds", "_pre_region", "_prereleases_configured", "_reject", )
#: The disjoint, sorted, non-overlapping interval list. _bounds: tuple[Interval, ...]
#: Whether this range matches non-version strings as well as versions. #: True only by construction on ``SpecifierSet("")`` / :meth:`full`. The flag #: rides set algebra but is inert except at full bounds (see #: :meth:`_arbitrary_active`). An intersection or difference that shrinks #: the bounds drops it (``full() & ~full()`` is plain empty, and #: ``full() - r == full() & ~r``); :meth:`complement` and a union of #: empty-bounds operands keep it, so ``~~full() == full()`` and #: ``~full() | ~full() == ~full()``. Part of equality, since membership #: reads it. _admit_arbitrary: bool
#: Case-folded strings the range admits in addition to its bounds. #: ``===wat`` produces ``_admit = {"wat"}``. _admit: frozenset[str]
#: Case-folded strings the range rejects (overrides ``_admit`` and the #: bounds). Populated by :meth:`complement` of an admit-bearing range and by #: literal resolution in :meth:`_combine_literals`. _reject: frozenset[str]
#: Sorted, disjoint intervals where pre-releases are force-admitted under #: the PEP 440 default policy (a ``None`` ``prereleases`` argument and no #: configured override). The opt-in flows only from the pre-release-naming #: specifiers that built the range. :meth:`_build` clips the region to the #: bounds, so it is always a subset of them: an opt-in that overflowed its #: own cap cannot ride a later union into versions no specifier asked for. #: :meth:`union` and :meth:`intersection` accumulate the operands' clipped #: regions and re-clip to the result bounds; :meth:`difference` keeps only #: the minuend's; and :meth:`complement` drops it, since an exclusion grants #: no opt-in. Equality keys on the clipped region, so it stays a congruence. _pre_region: tuple[Interval, ...]
#: Raw configured pre-release override of the originating specifier set #: (an explicit ``True`` / ``False``, else ``None``). When set, :meth:`_build` #: forces ``_pre_region`` empty since the policy governs globally. #: :meth:`intersection` and :meth:`union` require it to match on both #: operands. Part of equality. _prereleases_configured: bool | None
def __new__(cls, *args: object, **kwargs: object) -> VersionRange: # noqa: PYI034 raise TypeError( "cannot create 'VersionRange' instances directly; use " "SpecifierSet.to_range(), VersionRange.full(), " "VersionRange.empty(), or VersionRange.singleton() instead" )
@classmethod def _build( cls, bounds: tuple[Interval, ...], admit: frozenset[str] = frozenset(), reject: frozenset[str] = frozenset(), admit_arbitrary: bool = False, *, pre_region: tuple[Interval, ...] = (), prereleases_configured: bool | None = None, ) -> VersionRange: """Internal factory; bypasses :meth:`__new__`.
Canonicalizes the bounds so equal version sets share one representation, then drops admit literals the bounds already admit and reject literals the bounds do not match anyway. Reject wins over admit on overlap. The pre-release policy is set here and never reassigned afterwards; ``pre_region`` is canonicalized like the bounds and clipped to them, or dropped when a configured policy makes it inert. """ bounds = _canonicalize(bounds)
if admit and reject: admit = admit - reject if admit: admit = frozenset( literal for literal in admit if not _struct_admits(bounds, admit_arbitrary, literal) ) if reject: reject = frozenset( literal for literal in reject if _struct_admits(bounds, admit_arbitrary, literal) )
instance = object.__new__(cls) instance._bounds = bounds instance._admit = admit instance._reject = reject instance._admit_arbitrary = admit_arbitrary instance._prereleases_configured = prereleases_configured
# A configured policy makes the region inert, so drop it. Otherwise fold # least-successor bounds (_from_specifier_set passes the region unfolded), # so ``>1.0a1`` and ``>=1.0a2.dev0`` carry the same region, then clip it # to the bounds so the opt-in never reaches past the range's own versions. if prereleases_configured is not None or not pre_region: instance._pre_region = () else: instance._pre_region = tuple( intersect_ranges(_canonicalize(pre_region), bounds) )
return instance
def _has_literals(self) -> bool: return bool(self._admit) or bool(self._reject)
def _arbitrary_active(self) -> bool: """True when ``_admit_arbitrary`` actually admits non-version strings.
The flag rides through set algebra but only fires admission on full bounds. Intersection and difference drop it when the bounds shrink, so away from full bounds it survives only on empty-bounds ranges, where it keeps ``~~full() == full()`` and union idempotent. """ return self._admit_arbitrary and self._bounds == FULL_RANGE
def _is_plain(self) -> bool: """True when membership is decided by ``_bounds`` alone, enabling the bounds-only fast paths in :meth:`is_subset` and :meth:`is_disjoint`. """ return ( not self._has_literals() and not self._admit_arbitrary and self._prereleases_configured is not False )
def _check_policy_compat(self, other: VersionRange) -> None: """Refuse combining ranges with different pre-release policies.""" if not isinstance(other, VersionRange): raise TypeError(f"expected VersionRange, got {type(other).__name__}") if self._prereleases_configured != other._prereleases_configured: raise ValueError( "Cannot combine VersionRange operands with different " f"pre-release policies: {self._prereleases_configured!r} " f"and {other._prereleases_configured!r}" )
def _merged_region(self, other: VersionRange) -> tuple[Interval, ...]: """Union of ``self`` and ``other``'s opt-in regions.
Used by :meth:`union` and :meth:`intersection`; :meth:`_build` clips the merge to the result bounds. A configured operand carries an empty region, so it contributes nothing to the merge. """ # Reuse an operand's canonical tuple when only one side has a region; # an empty side contributes nothing to the union. if not other._pre_region: return self._pre_region if not self._pre_region: return other._pre_region
# Both sides carry a region; merge them. _build re-canonicalizes and # clips, so the plain union is fine here. return tuple(_union_ranges(self._pre_region, other._pre_region))
def _with_policy( self, *, pre_region: tuple[Interval, ...], configured: bool | None ) -> VersionRange: """A structural copy of this range carrying the given pre-release policy.""" return self._build( self._bounds, admit=self._admit, reject=self._reject, admit_arbitrary=self._admit_arbitrary, pre_region=pre_region, prereleases_configured=configured, )
@classmethod def empty(cls, *, prereleases: bool | None = None) -> VersionRange: """Return the empty range. No version satisfies it.
>>> VersionRange.empty().is_empty True >>> "1.0" in VersionRange.empty() False """ return cls._build((), prereleases_configured=prereleases)
@classmethod def full( cls, *, admit_arbitrary: bool = True, prereleases: bool | None = None ) -> VersionRange: """Return the full range. Every PEP 440 version satisfies it.
``admit_arbitrary=False`` restricts the range to PEP 440 versions only (matching the same versions as ``SpecifierSet(">=0.dev0").to_range()``); its complement is :meth:`empty`. The flag propagates through set algebra and is part of equality. Default ``True`` so that ``r & full()`` preserves ``r``'s own flag structurally.
>>> "1.0" in VersionRange.full() True >>> "wat" in VersionRange.full() True >>> "wat" in VersionRange.full(admit_arbitrary=False) False """ return cls._build( FULL_RANGE, admit_arbitrary=admit_arbitrary, prereleases_configured=prereleases, )
@classmethod def singleton( cls, version: Version | str, *, prereleases: bool | None = None ) -> VersionRange: """Return the strict singleton range ``{version}``.
Built as the closed interval ``[version, version]`` with strict equality. ``Specifier("==V")`` matches ``V+local`` too, so the strict singleton is narrower:
>>> "1.0+local" in VersionRange.singleton("1.0") False >>> "1.0+local" in SpecifierSet("==1.0").to_range() True
:raises packaging.version.InvalidVersion: if version is a string that does not parse as a PEP 440 version. """ if not isinstance(version, Version): version = Version(version)
lower = LowerBound(version, True) upper = UpperBound(version, True)
# Collapse the floor: nothing sorts below ``MIN_VERSION``, so the # ``0.dev0`` singleton is ``(-inf, 0.dev0]`` in canonical form. return cls._build( _canonical_floor(((lower, upper),)), prereleases_configured=prereleases, )
def intersection(self, other: VersionRange) -> VersionRange: """Range containing exactly the versions in both self and other.
Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised.
>>> a = SpecifierSet(">=1.0").to_range() >>> b = SpecifierSet("<2.0").to_range() >>> a.intersection(b) == SpecifierSet(">=1.0,<2.0").to_range() True """ self._check_policy_compat(other)
configured = self._prereleases_configured new_bounds = tuple(intersect_ranges(self._bounds, other._bounds)) new_region = self._merged_region(other)
# An empty intersection (e.g. ``full() & ~full()``) is the empty range, # so it drops the arbitrary flag, agreeing with difference when the # subtrahend consumes the bounds. combined_arb = ( self._admit_arbitrary and other._admit_arbitrary and bool(new_bounds) )
if not self._has_literals() and not other._has_literals(): return self._build( new_bounds, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, )
return self._combine_literals( other, new_bounds, op=_SetOp.INTERSECTION, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, )
def union(self, other: VersionRange) -> VersionRange: """Range containing every version in self or other.
Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised.
>>> a = VersionRange.singleton("1.0") >>> b = VersionRange.singleton("2.0") >>> "1.0" in a.union(b) and "2.0" in a.union(b) True >>> "1.5" in a.union(b) False """ self._check_policy_compat(other)
configured = self._prereleases_configured new_bounds = tuple(_union_ranges(self._bounds, other._bounds)) new_region = self._merged_region(other)
# An empty-bounds operand (e.g. ``~full()``) carries an inert arbitrary # flag only to keep complement an involution; it admits nothing, so it # must not revive arbitrary admission as the union re-widens the bounds. if new_bounds: combined_arb = (self._admit_arbitrary and bool(self._bounds)) or ( other._admit_arbitrary and bool(other._bounds) ) else: # Nothing widened, so keeping the flags keeps ``r | r == r``. combined_arb = self._admit_arbitrary or other._admit_arbitrary
if not self._has_literals() and not other._has_literals(): return self._build( new_bounds, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, )
return self._combine_literals( other, new_bounds, op=_SetOp.UNION, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, )
def complement(self) -> VersionRange: """Range containing every version not in self.
Preserves the configured pre-release policy. On the version set, double negation holds for a range with no ``===`` literals (the arbitrary-string flag round-trips, so ``~~full() == full()``); for ``===`` ranges complement is one-way. The opt-in region is not restored (see below).
The opt-in region is dropped: a complement is an exclusion, and an exclusion expresses no pre-release preference. This is what lets ``a & ~b`` shed ``b``'s opt-in, so an excluded ``b`` never force-admits a pre-release into the result. Complement stays involutive on the version set, but not on the opt-in region: ``~~r`` covers the same versions as ``r`` yet force-admits none of its pre-releases.
>>> r = SpecifierSet(">=1.0").to_range() >>> "0.5" in r.complement() True >>> "1.5" in r.complement() False >>> r.complement().complement() == r True """ # Complement swaps literal admission: what the range rejects, its # complement admits. return self._build( tuple(_complement_ranges(self._bounds)), admit=self._reject, reject=self._admit, admit_arbitrary=self._admit_arbitrary, pre_region=(), prereleases_configured=self._prereleases_configured, )
def difference(self, other: VersionRange) -> VersionRange: """Range containing the versions in self but not in other.
Matches ``self & ~other`` on the version set and the opt-in region; ``other`` acts as a bounds-only exclusion that grants no opt-in. The arbitrary-string flag survives only when ``other`` removed no versions: a difference that shrinks the bounds forgets it, as ``self & ~other`` would, so no later widening union can revive it. They still part on ``===`` literals, whose complement is one-way: a ``===`` literal stays when ``self`` admits it and ``other`` does not. Both operands must share the same configured pre-release policy (as :meth:`intersection` and :meth:`union` require); otherwise :exc:`ValueError` is raised. ``a - empty()`` returns a range equal to ``a``.
>>> a = SpecifierSet(">=1.0").to_range() >>> b = SpecifierSet(">=2.0").to_range() >>> "1.5" in a.difference(b) True >>> "2.0" in a.difference(b) False >>> a.difference(VersionRange.empty()) == a True """ self._check_policy_compat(other)
# Subtracting a nothing-admitting set is a no-op; return self unchanged. if not other._bounds and not other._admit: return self
# Bound complement is two-way, so subtracting other's versions is an # intersection with its gaps. new_bounds = tuple( intersect_ranges(self._bounds, _complement_ranges(other._bounds)) )
# Match ``self & ~other`` on the opt-in region: a complement carries no # opt-in, so only ``self``'s region survives. ``other`` acts as a # bounds-only exclusion. A configured ``self`` keeps no region. new_region: tuple[Interval, ...] = () if self._prereleases_configured is None: new_region = self._pre_region
# Keep self's arbitrary admission only when subtracting removed no # versions. A difference that shrinks the bounds forgets the flag, as # ``self & ~other`` would, so no later widening union can revive an # admission neither operand had. combined_arb = self._admit_arbitrary and new_bounds == self._bounds
if not self._has_literals() and not other._has_literals(): return self._build( new_bounds, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=self._prereleases_configured, )
return self._combine_literals( other, new_bounds, op=_SetOp.DIFFERENCE, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=self._prereleases_configured, )
def _combine_literals( self, other: VersionRange, new_bounds: tuple[Interval, ...], *, op: _SetOp, admit_arbitrary: bool, pre_region: tuple[Interval, ...], prereleases_configured: bool | None, ) -> VersionRange: """Resolve admit/reject for ``self`` ``op`` ``other`` over their literals.""" admits: set[str] = set() rejects: set[str] = set()
# Each literal is decided independently of the others. for literal in self._admit | self._reject | other._admit | other._reject: self_in = self._matches_literal(literal) other_in = other._matches_literal(literal)
if op is _SetOp.INTERSECTION: want = self_in and other_in elif op is _SetOp.UNION: want = self_in or other_in else: want = self_in and not other_in
if want: admits.add(literal) else: rejects.add(literal)
return self._build( new_bounds, admit=frozenset(admits), reject=frozenset(rejects), admit_arbitrary=admit_arbitrary, pre_region=pre_region, prereleases_configured=prereleases_configured, )
def _matches_literal(self, literal: str) -> bool: """Whether literal (case-folded) matches this range's predicate.""" if literal in self._reject: return False if literal in self._admit: return True
parsed = coerce_version(literal) if parsed is None: return self._arbitrary_active() return matches_bounds_only(self._bounds, parsed)
def __and__(self, other: object) -> VersionRange: """Operator alias for :meth:`intersection`.""" if not isinstance(other, VersionRange): return NotImplemented return self.intersection(other)
def __or__(self, other: object) -> VersionRange: """Operator alias for :meth:`union`.""" if not isinstance(other, VersionRange): return NotImplemented return self.union(other)
def __invert__(self) -> VersionRange: """Operator alias for :meth:`complement`.""" return self.complement()
def __sub__(self, other: object) -> VersionRange: """Operator alias for :meth:`difference`.""" if not isinstance(other, VersionRange): return NotImplemented return self.difference(other)
def is_subset(self, other: VersionRange) -> bool: """Return whether every member of self is also a member of other.
On versions and ``===`` literals this is ``self.difference(other).is_empty``: subtracting other leaves nothing behind. A live arbitrary admission (the flag at full bounds) is only a subset of another live one.
Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised.
>>> inner = SpecifierSet(">=1.5,<1.8").to_range() >>> outer = SpecifierSet(">=1.0,<2.0").to_range() >>> inner.is_subset(outer) True >>> outer.is_subset(inner) False >>> VersionRange.empty().is_subset(outer) True """ self._check_policy_compat(other)
# A live arbitrary admission has non-version strings as members, which # no bounds cover; only another live admission contains them. if self._arbitrary_active() and not other._arbitrary_active(): return False
# Plain ranges: subset reduces to bounds containment, no algebra needed. if self._is_plain() and other._is_plain(): return not intersect_ranges(self._bounds, _complement_ranges(other._bounds))
# difference (unlike intersection with the one-way complement) resolves # ``===`` literals against both operands, so it stays correct for them. return self.difference(other).is_empty
def is_superset(self, other: VersionRange) -> bool: """Return whether every member of other is also a member of self.
The mirror of :meth:`is_subset`: ``a.is_superset(b)`` is ``b.is_subset(a)``.
Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised.
>>> outer = SpecifierSet(">=1.0,<2.0").to_range() >>> outer.is_superset(SpecifierSet(">=1.5,<1.8").to_range()) True """ # Type-guards a non-VersionRange other before delegating to is_subset. self._check_policy_compat(other) return other.is_subset(self)
def is_disjoint(self, other: VersionRange) -> bool: """Return whether self and other share no member.
Equivalent to ``(self & other).is_empty``.
Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised.
>>> a = SpecifierSet(">=1.0,<2.0").to_range() >>> a.is_disjoint(SpecifierSet(">=2.0,<3.0").to_range()) True >>> a.is_disjoint(SpecifierSet(">=1.5,<2.5").to_range()) False """ self._check_policy_compat(other)
# Plain ranges: disjointness is an empty bounds intersection. if self._is_plain() and other._is_plain(): return not intersect_ranges(self._bounds, other._bounds) return self.intersection(other).is_empty
def _same_releases(self, other: VersionRange) -> bool: """Whether self and other admit the same non-pre-release versions.
Used by :meth:`to_specifier_set` under a ``prereleases=False`` policy, where pre-releases are unobservable: the symmetric difference is empty exactly when the two ranges accept the same releases. Both operands carry that policy, so the difference below reads emptiness through it. """ return self.difference(other).is_empty and other.difference(self).is_empty
@typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ...
@typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ...
def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], Version | str] | None = None, ) -> Iterator[Any]: """Yield items from iterable whose version falls inside the range.
With prereleases ``None`` the PEP 440 default applies: pre-releases are buffered and only emitted if no final release in iterable is in range, except that a pre-release inside the autodetected opt-in region, or named outright by a ``===`` literal, is force-admitted in place (as ``prereleases=True`` would yield it). A flushed buffer comes after every in-place yield, so the output is not version-sorted.
The signature mirrors :meth:`~packaging.specifiers.SpecifierSet.filter`.
>>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> list(r.filter(["0.9", "1.5", "2.0"])) ['1.5'] """ region: tuple[Interval, ...] = () if prereleases is None: # The region applies only under the autodetect default; a configured # policy governs instead (and then ``_pre_region`` is already empty). prereleases = self._prereleases_configured region = self._pre_region
arbitrary_active = self._arbitrary_active() if not self._admit and not self._reject and not arbitrary_active: # A region spanning the whole bounds force-admits every in-bounds # pre-release, i.e. ``prereleases=True``; take the cheaper no-buffer # path. (Confined to this branch: the admission path orders arbitrary # strings differently under True than under the region.) if region and region == self._bounds: return filter_by_ranges(self._bounds, iterable, key, True) return filter_by_ranges(self._bounds, iterable, key, prereleases, region) return self._filter_with_admission( iterable, key, prereleases, arbitrary_active, region )
def _filter_with_admission( self, iterable: Iterable[Any], key: Callable[[Any], Version | str] | None, prereleases: bool | None, arbitrary_active: bool, region: tuple[Interval, ...], ) -> Iterator[Any]: """Filter for ranges with admit/reject literals or live arbitrary admission (including the universal ``SpecifierSet("")`` range).""" admit_set = self._admit reject_set = self._reject
def admit(item: Any) -> tuple[bool, Version | None, bool]: # noqa: ANN401 raw: Version | str = item if key is None else key(item) raw_lower = str(raw).lower()
if reject_set and raw_lower in reject_set: return False, None, False if admit_set and raw_lower in admit_set: # An explicit ``===`` literal names this version outright. return True, coerce_version(raw), True
parsed = coerce_version(raw) if parsed is None: return arbitrary_active, None, False if not matches_bounds_only(self._bounds, parsed): return False, None, False return True, parsed, False
if prereleases is True: for item in iterable: ok, _, _ = admit(item) if ok: yield item return
if prereleases is False: for item in iterable: ok, parsed, _ = admit(item) if not ok: continue if parsed is not None and parsed.is_prerelease: continue yield item return
# PEP 440 default: emit finals eagerly and buffer the other pre-releases, # releasing the buffer only if no final ever matches. all_nonfinal: list[Any] = [] arbitrary_strings: list[Any] = [] found_final = False
for item in iterable: ok, parsed, by_literal = admit(item) if not ok: continue
if parsed is None: if found_final: yield item else: arbitrary_strings.append(item) all_nonfinal.append(item) continue
if not parsed.is_prerelease: if not found_final: yield from arbitrary_strings arbitrary_strings.clear() found_final = True yield item continue
# A pre-release is force-admitted when it is named outright by a # ``===`` literal or falls in the opt-in region, as ``prereleases=True`` # would yield it; otherwise the PEP 440 default buffers it. if by_literal or (region and matches_bounds_only(region, parsed)): yield item continue
if not found_final: all_nonfinal.append(item)
if not found_final: yield from all_nonfinal
@classmethod def _from_specifier_set(cls, specifier_set: SpecifierSet) -> VersionRange: """Build the range accepted by ``specifier_set``.
Friend constructor for :meth:`~packaging.specifiers.SpecifierSet.to_range`. The intersection of every specifier in the set: an empty set yields the full range, an unsatisfiable set yields the empty range, and ``===`` specifiers contribute literal-string admission. """ if not specifier_set: result = cls.full() elif not specifier_set._has_arbitrary: result = cls._build( bounds=_canonical_floor(tuple(specifier_set._get_ranges())) ) else: result = cls.full() for spec in specifier_set: if spec.operator == "===": operand = cls._build( bounds=(), admit=frozenset({spec.version.lower()}) ) else: operand = cls._build( bounds=_canonical_floor(tuple(spec._to_ranges())) ) result = result.intersection(operand)
# Each pre-release-naming specifier opts its own versions in; their union, # clipped to the set's bounds by _build, is the region. Clipping refolds # under intersection, so a set built directly equals one built by # intersecting its specifiers one at a time. region: list[Interval] = [] if specifier_set._prereleases is None: # a configured policy has no region for spec in specifier_set: # ``===`` literals are not a range; filter force-admits them. if spec.operator != "===" and spec.prereleases: spec_bounds = _canonical_floor(tuple(spec._to_ranges())) region = _union_ranges(region, spec_bounds)
return result._with_policy( pre_region=tuple(region), configured=specifier_set._prereleases, )
def to_specifier_set(self) -> SpecifierSet | None: """Return a :class:`~packaging.specifiers.SpecifierSet` matching the same versions as self, or ``None`` if no single set expresses it.
PEP 440 has no syntax for the strict singleton ``{V}`` (an exclusive plain-version bound), a disjoint union of two or more intervals, or a partial pre-release opt-in region, so ranges built by set algebra often return ``None``. A gap that takes more than ``_MAX_EXCLUSION_RUN`` contiguous ``!=`` exclusions to spell returns ``None`` too, rather than a pathologically long chain; reaching that cap takes either set algebra or a specifier set that already spells the gap out with over a hundred contiguous ``!=N.*`` exclusions. An empty range maps to ``SpecifierSet("<0")``, unless it still carries the arbitrary-string flag (which no set reproduces), and a full range that admits arbitrary strings maps to ``SpecifierSet("")``.
A range built from a :class:`~packaging.specifiers.SpecifierSet` re-encodes, short of that exclusion cap. The result is the simplest candidate whose own :meth:`~packaging.specifiers.SpecifierSet.to_range` reproduces self exactly (bounds, ``===`` literals, and the opt-in region are all part of equality), so it filters the same versions. Two cases relax that exactness without changing what is filtered: an empty range recovers as the canonical empty range (same versions, none, but not self's bounds), and under a ``prereleases=False`` policy the result need only match self's releases, so ``(-inf, 3.14)`` recovers as the tighter ``<3.14`` rather than ``!=3.14,<=3.14``.
Each call encodes a handful of candidate spellings and keeps the simplest one that verifies, where verifying means parsing the candidate and round-tripping it through :meth:`~packaging.specifiers.SpecifierSet.to_range`. The work grows with the number of intervals and exclusions in the range, and the result is not cached, so convert once and reuse the returned set rather than converting per candidate version in a hot loop.
>>> str(SpecifierSet(">=1.0,<2.0").to_range().to_specifier_set()) '<2.0,>=1.0' >>> str(SpecifierSet("==1.0").to_range().to_specifier_set()) '==1.0' >>> VersionRange.singleton("1.5").to_specifier_set() is None True """ from .specifiers import InvalidSpecifier, SpecifierSet # noqa: PLC0415
configured = self._prereleases_configured
if self._reject: return None if self._admit_arbitrary and self._bounds != FULL_RANGE: return None if self.is_empty: # Every member-free spelling accepts the same versions (none), so the # canonical ``<0`` stands in for all of them; a configured policy # rides along it. return SpecifierSet("<0", prereleases=configured)
if not self._bounds: # Pure ``===`` literals; only a single literal has a single-set form. if len(self._admit) != 1: return None (literal,) = self._admit bases = [f"==={literal}"] elif self._admit: # Bounds plus literals cannot be one set. return None elif self._bounds == FULL_RANGE: bases = ["" if self._admit_arbitrary else ">=0.dev0"] else: # Under ``prereleases=False`` an exclusive final upper admits the same # releases as ``<V`` (the ``[V.dev0, V)`` band is excluded), so offer # the tightened bounds as well; a tightening that is not # release-equivalent is dropped by the acceptance check below. layouts = [self._bounds] if configured is False: tightened = _tighten_no_prereleases(self._bounds) if tightened != self._bounds: layouts.append(tightened)
# Encode each layout in both spelling modes: prerelease-free, then # keeping the synthetic ``.dev0`` markers. Which spelling reproduces # self is settled by the round trip below, not up front. The gap # exclusions do not depend on the mode, so they encode once. bases = [] for layout in layouts: exclusions = _encode_gaps(layout) if exclusions is None: continue
for keep_dev0 in (False, True): outer = _encode_interval(layout[0][0], layout[-1][1], keep_dev0) if outer is None: continue base = ",".join(outer + exclusions) if base not in bases: bases.append(base)
# A trailing no-op ``>=0.dev0`` floor restores a ``True`` opt-in that # rode on a floor the clean encoding dropped (e.g. ``>=0.dev0,!=1.0``). # It always recovers the whole bounds as the opt-in region, so it can # only round-trip when self opts everything in. add_floor = configured is None and self._pre_region == self._bounds
# Keep the simplest candidate that recovers self. ``==`` compares bounds, # literals, and the opt-in region, so a candidate that would filter # differently, or an op-built range with no single-set form, is rejected # below. Under ``prereleases=False`` a candidate need only match self's # releases (policies never mix, so the excluded pre-releases are # unobservable), which admits the tightened spellings above. best: SpecifierSet | None = None best_key = (0, 0)
for base in bases: candidates = [base] if add_floor: candidates.append(f"{base},>=0.dev0" if base else ">=0.dev0")
for spec_str in candidates: # A ``===`` literal can hold a comma (its arbitrary version # excludes only whitespace, ``;`` and ``)``), which the set # string splits on. Such a literal has no single specifier-set # spelling, so drop the unparsable candidate and let the range # fall through to ``None`` rather than raise. try: recovered = SpecifierSet(spec_str, prereleases=configured) except InvalidSpecifier: continue # Fewest fragments, then shortest string. Rank before the round # trip so a candidate that cannot beat the best skips the check # (its ``==`` and, under ``False``, two ``difference`` calls). key = (len(recovered), len(str(recovered))) if best is not None and key >= best_key: continue
# Accept an exact round trip, or (under ``False``) one that only # matches the releases the policy leaves observable. candidate = recovered.to_range() matches = candidate == self or ( configured is False and self._same_releases(candidate) ) if matches: best, best_key = recovered, key
return best
@property def is_empty(self) -> bool: """``True`` if no version or string satisfies this range.
Agrees with :meth:`~packaging.specifiers.SpecifierSet.is_unsatisfiable`, including the pre-release policy: a range whose only members are pre-releases is empty when that policy excludes them.
>>> SpecifierSet(">=2,<1").to_range().is_empty True >>> SpecifierSet(">=1,<2").to_range().is_empty False >>> SpecifierSet("==1.0a1", prereleases=False).to_range().is_empty True """ # An arbitrary-string admission or a surviving ``===`` literal is a # member; a literal that is a pre-release is dropped when the policy is. if self._arbitrary_active(): return False
excludes_prereleases = self._prereleases_configured is False for literal in self._admit: if excludes_prereleases: parsed = coerce_version(literal) if parsed is not None and parsed.is_prerelease: continue return False
if not self._bounds: return True
return excludes_prereleases and ranges_are_prerelease_only(self._bounds)
def contains( self, item: Version | str, prereleases: bool | None = None, installed: bool | None = None, ) -> bool: """Return whether item is contained in this range.
:param item: a version string or :class:`~packaging.version.Version`. :param prereleases: whether to match pre-releases. ``None`` (default) uses the range's own policy. :param installed: when ``True``, accept a pre-release item even if the range would not otherwise allow it.
Unlike :meth:`filter`, this does not consult the autodetected pre-release opt-in region; it reads only the configured policy. This mirrors :meth:`~packaging.specifiers.SpecifierSet.contains` versus :meth:`~packaging.specifiers.SpecifierSet.filter`.
Unparsable strings do not match, except where the full ``SpecifierSet`` would also match: the full range admits any string, and a ``===`` range admits items equal to the literal case-insensitively.
>>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> r.contains("1.5") True >>> r.contains("2.0") False
:raises TypeError: if item is not a str or Version. """ if not isinstance(item, (str, Version)): raise TypeError( f"VersionRange.contains() expected str or Version, " f"got {type(item).__name__}" )
parsed: Version | None = item if isinstance(item, Version) else None if installed and parsed is None: parsed = coerce_version(item) if installed and parsed is not None and parsed.is_prerelease: prereleases = True
effective_pre = ( self._prereleases_configured if prereleases is None else prereleases )
if self._admit or self._reject: item_str = str(item).lower() if item_str in self._reject: return False if item_str in self._admit: if effective_pre is False: literal_parsed = coerce_version(item_str) if literal_parsed is not None and literal_parsed.is_prerelease: return False return True
if not isinstance(item, Version): if parsed is None: parsed = coerce_version(item) if parsed is None: return self._arbitrary_active() item = parsed
if effective_pre is False and item.is_prerelease: return False return matches_bounds_only(self._bounds, item)
def __contains__(self, item: Version | str) -> bool: """Return whether item is contained in this range.
Forwards to :meth:`contains` with default arguments.
>>> "1.5" in SpecifierSet(">=1.0,<2.0").to_range() True """ return self.contains(item)
def __eq__(self, other: object) -> bool: """Structural equality.
Compares the bounds, the ``===`` admit/reject literals, the arbitrary-string flag, the configured pre-release policy, and the opt-in region, not just the version set. Keying on the region makes equality a congruence (equal ranges stay equal under further operations), so equal implies same :meth:`contains` and :meth:`filter`, but not the converse: an empty range keeps the flag it was built with, so two empty ranges need not be equal.
Different specifiers for the same range fold to one canonical form:
>>> SpecifierSet(">1.0a1").to_range() == SpecifierSet(">=1.0a2.dev0").to_range() True
The opt-in region is part of equality, so ``<=1.0`` (no pre-releases) and ``<1.0.post0.dev0`` (autodetects a ``.dev`` opt-in) cover the same versions yet compare unequal:
>>> le, lt = SpecifierSet("<=1.0"), SpecifierSet("<1.0.post0.dev0") >>> le.to_range() == lt.to_range() False
>>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> r == SpecifierSet(">=1.0,<2.0").to_range() True """ if not isinstance(other, VersionRange): return NotImplemented return ( self._bounds == other._bounds and self._admit == other._admit and self._reject == other._reject and self._admit_arbitrary == other._admit_arbitrary and self._prereleases_configured == other._prereleases_configured and self._pre_region == other._pre_region )
def __hash__(self) -> int: return hash( ( self._bounds, self._admit, self._reject, self._admit_arbitrary, self._prereleases_configured, self._pre_region, ) )
def __repr__(self) -> str: """Human-readable representation for debugging.
>>> SpecifierSet(">=1.0,<2.0").to_range() <VersionRange '[1.0, 2.0.dev0)'> >>> SpecifierSet("").to_range() <VersionRange '(-inf, +inf)' arbitrary> >>> SpecifierSet(">=2.0,<1.0").to_range() <VersionRange '(empty)'> """ # Body: the bounds and any ``===``-admitted literals. parts: list[str] = [] if self._bounds: parts.append(_format_intervals(self._bounds)) if self._admit: parts.append("{" + ", ".join(sorted(self._admit)) + "}") body = " | ".join(parts) if parts else "(empty)"
# Rejected literals subtract from the body. if self._reject: body = f"{body} \\ {{{', '.join(sorted(self._reject))}}}"
# Tail: the policy flags carried alongside the version set. tail = "" if self._admit_arbitrary: tail += " arbitrary" if self._prereleases_configured is not None: tail += f" pre={self._prereleases_configured}" if self._pre_region: tail += f" pre-region={_format_intervals(self._pre_region)!r}"
return f"<{self.__class__.__name__} {body!r}{tail}>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.from __future__ import annotations
from typing import TYPE_CHECKING
from ._parser import parse_requirement as _parse_requirementfrom ._tokenizer import ParserSyntaxErrorfrom .markers import Marker, _normalize_extra_valuesfrom .specifiers import InvalidSpecifier, SpecifierSetfrom .utils import canonicalize_name
if TYPE_CHECKING: from collections.abc import Iterator
__all__ = [ "InvalidRequirement", "Requirement",]
def __dir__() -> list[str]: return __all__
class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508.
.. versionadded:: 16.1 """
class Requirement: """Parse a requirement.
Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string.
.. versionadded:: 16.1
.. versionchanged:: 22.0 Added equality (``__eq__``) and hashing (``__hash__``) so requirements can be compared and stored in sets / dicts.
.. versionchanged:: 23.2 Equality and hashing began canonicalizing requirement names, so requirements whose names differ only by normalization (e.g. ``Requirement("Foo")`` vs ``Requirement("foo")``) now compare and hash equal.
Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases.
.. versionchanged:: 26.2
Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release.
.. versionchanged:: 26.3
The dedicated pickle support introduced in 26.2 did not preserve the specifier's explicit :attr:`~packaging.specifiers.SpecifierSet.prereleases` override; it is now included again.
Equality and hashing normalize requirement names, extras, and equivalent specifiers. The string representation still preserves the parsed name and extras spelling. """
# TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name?
__slots__ = ("extras", "marker", "name", "specifier", "url")
def __init__(self, requirement_string: str) -> None: try: parsed = _parse_requirement(requirement_string) except ParserSyntaxError as e: raise InvalidRequirement(str(e)) from e
self.name: str = parsed.name self.url: str | None = parsed.url or None self.extras: set[str] = set(parsed.extras) try: self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) except InvalidSpecifier as e: raise InvalidRequirement(str(e)) from e self.marker: Marker | None = None if parsed.marker is not None: self.marker = Marker.__new__(Marker) self.marker._markers = _normalize_extra_values(parsed.marker)
def _iter_parts(self, name: str) -> Iterator[str]: yield name
if self.extras: formatted_extras = ",".join(sorted(self.extras)) yield f"[{formatted_extras}]"
if self.specifier: yield str(self.specifier)
if self.url: yield f" @ {self.url}" if self.marker: yield " "
if self.marker: yield f"; {self.marker}"
def __getstate__(self) -> tuple[str, bool | None]: # Return the requirement string for compactness and stability, paired # with the specifier's explicit prereleases override, which is not # captured by the string form. Re-parsed on load to reconstruct all # other fields. return (str(self), self.specifier._prereleases)
def __setstate__(self, state: object) -> None: if isinstance(state, str): # Format (26.2): just the requirement string. requirement_string: str = state prereleases: bool | None = None elif ( isinstance(state, tuple) and len(state) == 2 and isinstance(state[0], str) and (state[1] is None or isinstance(state[1], bool)) ): # New format (26.3+): (requirement string, specifier prereleases). requirement_string, prereleases = state elif isinstance(state, dict) and state.keys() >= set(self.__slots__): # Old format (packaging <= 26.1, no __slots__): plain __dict__. for key in self.__slots__: setattr(self, key, state[key]) return else: raise TypeError(f"Cannot restore Requirement from {state!r}")
try: tmp = Requirement(requirement_string) except InvalidRequirement as exc: raise TypeError(f"Cannot restore Requirement from {state!r}") from exc self.name = tmp.name self.url = tmp.url self.extras = tmp.extras self.specifier = tmp.specifier self.specifier._prereleases = prereleases self.marker = tmp.marker
def __str__(self) -> str: return "".join(self._iter_parts(self.name))
def __repr__(self) -> str: return f"<{self.__class__.__name__}({str(self)!r})>"
def __hash__(self) -> int: # Mirror __eq__ by hashing the canonical specifier object rather than # its raw string. ``_iter_parts`` yields ``str(self.specifier)``, which # is non-canonical, so trailing-zero-equivalent requirements such as # ``foo==1.0.0`` and ``foo==1.0.0.0`` (which compare equal) would # otherwise hash differently, breaking the hash/__eq__ invariant. return hash( ( canonicalize_name(self.name), frozenset(canonicalize_name(e) for e in self.extras), self.specifier, self.url, self.marker, ) )
def __eq__(self, other: object) -> bool: if not isinstance(other, Requirement): return NotImplemented
# Extras must be normalized before comparison as per PEP 685. self_extras = frozenset(canonicalize_name(e) for e in self.extras) other_extras = frozenset(canonicalize_name(e) for e in other.extras) return ( canonicalize_name(self.name) == canonicalize_name(other.name) and self_extras == other_extras and self.specifier == other.specifier and self.url == other.url and self.marker == other.marker )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.""".. testsetup::
from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier from packaging.version import Version"""
from __future__ import annotations
import abcimport reimport typingfrom typing import ( TYPE_CHECKING, Any, Callable, Final, TypeVar, Union,)
from ._ranges import ( FULL_RANGE, bounds_for_spec, coerce_version, filter_by_ranges, intersect_specifier_bounds, matches_bounds_only, ranges_are_prerelease_only, resolve_prereleases, trim_release,)from .utils import canonicalize_versionfrom .version import Version
if TYPE_CHECKING: import sys from collections.abc import Iterable, Iterator, Sequence
if sys.version_info >= (3, 10): from typing import TypeGuard else: from typing_extensions import TypeGuard
from . import ranges from ._ranges import Interval
__all__ = [ "BaseSpecifier", "InvalidSpecifier", "Specifier", "SpecifierSet",]
def __dir__() -> list[str]: return __all__
def _validate_spec(spec: object, /) -> TypeGuard[tuple[str, str]]: return ( isinstance(spec, tuple) and len(spec) == 2 and isinstance(spec[0], str) and isinstance(spec[1], str) )
def _validate_pre(pre: object, /) -> TypeGuard[bool | None]: return pre is None or isinstance(pre, bool)
T = TypeVar("T")UnparsedVersion = Union[Version, str]UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion)
# Operators whose result is just a direct Version comparison, given a parsed# item with no local. ``<=``/``==``/``!=`` need that no-local guard because# PEP 440 strips locals on those; ``>=`` works regardless._DIRECT_COMPARE_OPS: dict[str, Callable[[Version, Version], bool]] = { ">=": Version.__ge__, "<=": Version.__le__, "==": Version.__eq__, "!=": Version.__ne__,}
def _fast_match(specifier: Specifier, parsed: Version) -> bool | None: """Match ``parsed`` against ``specifier`` without building a range.
Handles ``>=``, ``<=``, ``==``, ``!=``, ``<``, ``>`` when the spec is not a wildcard and ``parsed`` has no local. Returns ``None`` when the range path must be used. Pre-release policy is left to the caller. """ op_str, ver_str = specifier._spec if ver_str.endswith(".*") or parsed.local is not None: return None
direct_compare = _DIRECT_COMPARE_OPS.get(op_str) if direct_compare is not None: return direct_compare(parsed, specifier._require_spec_version(ver_str))
if op_str in ("<", ">"): spec_v = specifier._require_spec_version(ver_str) # ``<V``/``>V`` carve out V's family (pre/dev/post); that only # matters when parsed shares V's epoch and trimmed release. # Otherwise a direct cmpkey comparison is correct. if parsed.epoch != spec_v.epoch or trim_release(parsed.release) != trim_release( spec_v.release ): return parsed < spec_v if op_str == "<" else parsed > spec_v return None
return None
class InvalidSpecifier(ValueError): """ Raised when attempting to create a :class:`Specifier` with a specifier string that is invalid.
>>> Specifier("lolwat") Traceback (most recent call last): ... packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' """
class BaseSpecifier(metaclass=abc.ABCMeta): """ Abstract base class for :class:`Specifier` and :class:`SpecifierSet`. """
__slots__ = () __match_args__ = ("_str",)
@property def _str(self) -> str: """Internal property for match_args""" return str(self)
@abc.abstractmethod def __str__(self) -> str: """ Returns the str representation of this Specifier-like object. This should be representative of the Specifier itself. """
@abc.abstractmethod def __hash__(self) -> int: """ Returns a hash value for this Specifier-like object. """
@abc.abstractmethod def __eq__(self, other: object) -> bool: """ Returns a boolean representing whether or not the two Specifier-like objects are equal.
:param other: The other object to check against. """
@property @abc.abstractmethod def prereleases(self) -> bool | None: """Whether or not pre-releases as a whole are allowed.
This can be set to either ``True`` or ``False`` to explicitly enable or disable prereleases or it can be set to ``None`` (the default) to use default semantics. """
@prereleases.setter # noqa: B027 def prereleases(self, value: bool) -> None: """Setter for :attr:`prereleases`.
:param value: The value to set. """
@abc.abstractmethod def contains(self, item: str, prereleases: bool | None = None) -> bool: """ Determines if the given item is contained within this specifier. """
@typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ...
@typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ...
@abc.abstractmethod def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """
class Specifier(BaseSpecifier): """This class abstracts handling of version specifiers.
.. tip::
It is generally not required to instantiate this manually. You should instead prefer to work with :class:`SpecifierSet` instead, which can parse comma-separated version specifiers (which is what package metadata contains).
Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases.
.. versionchanged:: 26.2
Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """
__slots__ = ( "_prereleases", "_ranges", "_spec", "_spec_version", )
_specifier_regex_str = r""" (?: (?: # The identity operators allow for an escape hatch that will # do an exact string match of the version you wish to install. # This will not be parsed by PEP 440 and we cannot determine # any semantic meaning from it. This operator is discouraged # but included entirely as an escape hatch. === # Only match for the identity operator \s* [^\s;)]* # The arbitrary version can be just about anything, # we match everything except for whitespace, a # semi-colon for marker support, and a closing paren # since versions can be enclosed in them. ) | (?: # The (non)equality operators allow for wild card and local # versions to be specified so we have to define these two # operators separately to enable that. (?:==|!=) # Only match for equals and not equals
\s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release
# You cannot use a wild card and a pre-release, post-release, a dev or # local version together so group them with a | and make them optional. (?: \.\* # Wild card syntax of .* | (?a: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?a: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release (?a:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local )? ) | (?: # The compatible operator requires at least two digits in the # release segment. (?:~=) # Only match for the compatible operator
\s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) | (?: # All other operators only allow a sub set of what the # (non)equality operators do. Specifically they do not allow # local versions to be specified nor do they allow the prefix # matching wild cards. (?:<=|>=|<|>)
\s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release (?a: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?a: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) ) """
_regex = re.compile( r"\s*" + _specifier_regex_str + r"\s*", re.VERBOSE | re.IGNORECASE )
# Legacy unused attribute, kept for backward compatibility _operators: Final = { "~=": "compatible", "==": "equal", "!=": "not_equal", "<=": "less_than_equal", ">=": "greater_than_equal", "<": "less_than", ">": "greater_than", "===": "arbitrary", }
def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: """Initialize a Specifier instance.
:param spec: The string representation of a specifier which will be parsed and normalized before use. :param prereleases: This tells the specifier if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given specifier is invalid (i.e. bad syntax). """ if not self._regex.fullmatch(spec): raise InvalidSpecifier(f"Invalid specifier: {spec!r}")
spec = spec.strip() if spec.startswith("==="): operator, version = spec[:3], spec[3:].strip() elif spec.startswith(("~=", "==", "!=", "<=", ">=")): operator, version = spec[:2], spec[2:].strip() else: operator, version = spec[:1], spec[1:].strip()
self._spec: tuple[str, str] = (operator, version)
# Store whether or not this Specifier should accept prereleases self._prereleases = prereleases
# Specifier version cache self._spec_version: tuple[str, Version] | None = None
# Version range cache (populated by _to_ranges) self._ranges: Sequence[Interval] | None = None
def _get_spec_version(self, version: str) -> Version | None: """One element cache, as only one spec Version is needed per Specifier.""" if self._spec_version is not None and self._spec_version[0] == version: return self._spec_version[1]
version_specifier = coerce_version(version) if version_specifier is None: return None
self._spec_version = (version, version_specifier) return version_specifier
def _require_spec_version(self, version: str) -> Version: """Get spec version, asserting it's valid (not for === operator).
This method should only be called for operators where version strings are guaranteed to be valid PEP 440 versions (not ===). """ spec_version = self._get_spec_version(version) assert spec_version is not None return spec_version
def _to_ranges(self) -> Sequence[Interval]: """Convert this specifier to sorted, non-overlapping version ranges.
Each standard operator maps to one or two ranges. ``===`` is modeled as full range (actual check done separately). Cached. """ if self._ranges is not None: return self._ranges
op = self.operator ver_str = self.version
if op == "===": result: Sequence[Interval] = FULL_RANGE else: version = self._require_spec_version(ver_str.removesuffix(".*")) result = bounds_for_spec(op, ver_str, version)
self._ranges = result return result
@property def prereleases(self) -> bool | None: # If there is an explicit prereleases set for this, then we'll just # blindly use that. if self._prereleases is not None: return self._prereleases
# Only the "!=" operator does not imply prereleases when # the version in the specifier is a prerelease. operator, version_str = self._spec if operator == "!=": return False
# The == specifier with trailing .* cannot include prereleases # e.g. "==1.0a1.*" is not valid. if operator == "==" and version_str.endswith(".*"): return False
# "===" can have arbitrary string versions, so we cannot parse # those, we take prereleases as unknown (None) for those. version = self._get_spec_version(version_str) if version is None: return None
# For all other operators, use the check if spec Version # object implies pre-releases. return version.is_prerelease
@prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value
def __getstate__(self) -> tuple[tuple[str, str], bool | None]: # Return state as a 2-item tuple for compactness: # ((operator, version), prereleases) # Cache members are excluded and will be recomputed on demand. return (self._spec, self._prereleases)
def __setstate__(self, state: object) -> None: # Always discard cached values - they will be recomputed on demand. self._spec_version = None self._ranges = None
if isinstance(state, tuple): if len(state) == 2: # New format (26.2+): ((operator, version), prereleases) spec, prereleases = state if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return if len(state) == 2 and isinstance(state[1], dict): # Format (packaging 26.0-26.1): (None, {slot: value}). _, slot_dict = state spec = slot_dict.get("_spec") prereleases = slot_dict.get("_prereleases", "invalid") if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return if isinstance(state, dict): # Old format (packaging <= 25.x, no __slots__): state is a plain dict. spec = state.get("_spec") prereleases = state.get("_prereleases", "invalid") if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return
raise TypeError(f"Cannot restore Specifier from {state!r}")
@property def operator(self) -> str: """The operator of this specifier.
>>> Specifier("==1.2.3").operator '==' """ return self._spec[0]
@property def version(self) -> str: """The version of this specifier.
>>> Specifier("==1.2.3").version '1.2.3' """ return self._spec[1]
def __repr__(self) -> str: """A representation of the Specifier that shows all internal state.
>>> Specifier('>=1.0.0') <Specifier('>=1.0.0')> >>> Specifier('>=1.0.0', prereleases=False) <Specifier('>=1.0.0', prereleases=False)> >>> Specifier('>=1.0.0', prereleases=True) <Specifier('>=1.0.0', prereleases=True)> """ pre = ( f", prereleases={self.prereleases!r}" if self._prereleases is not None else "" )
return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
def __str__(self) -> str: """A string representation of the Specifier that can be round-tripped.
>>> str(Specifier('>=1.0.0')) '>=1.0.0' >>> str(Specifier('>=1.0.0', prereleases=False)) '>=1.0.0' """ return "{}{}".format(*self._spec)
@property def _canonical_spec(self) -> tuple[str, str]: operator, version = self._spec if operator == "===" or version.endswith(".*"): return operator, version
spec_version = self._require_spec_version(version)
canonical_version = canonicalize_version( spec_version, strip_trailing_zero=(operator != "~=") )
return operator, canonical_version
def __hash__(self) -> int: return hash(self._canonical_spec)
def __eq__(self, other: object) -> bool: """Whether or not the two Specifier-like objects are equal.
:param other: The other object to check against.
The value of :attr:`prereleases` is ignored.
>>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") True >>> (Specifier("==1.2.3", prereleases=False) == ... Specifier("==1.2.3", prereleases=True)) True >>> Specifier("==1.2.3") == "==1.2.3" True >>> Specifier("==1.2.3") == Specifier("==1.2.4") False >>> Specifier("==1.2.3") == Specifier("~=1.2.3") False """ if isinstance(other, str): try: other = self.__class__(str(other)) except InvalidSpecifier: return NotImplemented elif not isinstance(other, self.__class__): return NotImplemented
return self._canonical_spec == other._canonical_spec
def __contains__(self, item: str | Version) -> bool: """Return whether or not the item is contained in this specifier.
:param item: The item to check for.
This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed.
>>> "1.2.3" in Specifier(">=1.2.3") True >>> Version("1.2.3") in Specifier(">=1.2.3") True >>> "1.0.0" in Specifier(">=1.2.3") False >>> "1.3.0a1" in Specifier(">=1.2.3") True >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) True """ return self.contains(item)
def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: """Return whether or not the item is contained in this specifier.
:param item: The item to check for, which can be a version string or a :class:`~packaging.version.Version` instance. :param prereleases: Whether or not to match prereleases with this Specifier. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases, as there are no other versions.
>>> Specifier(">=1.2.3").contains("1.2.3") True >>> Specifier(">=1.2.3").contains(Version("1.2.3")) True >>> Specifier(">=1.2.3").contains("1.0.0") False >>> Specifier(">=1.2.3").contains("1.3.0a1") True >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1") False >>> Specifier(">=1.2.3").contains("1.3.0a1") True
.. versionchanged:: 26.0
With ``prereleases=None``, a prerelease now matches. A single version has no alternatives, so the :pep:`440` rule to accept prereleases when nothing else satisfies the specifier applies. Earlier versions rejected it. An unparsable version now returns ``False`` instead of raising :exc:`~packaging.version.InvalidVersion`. """ # ``===`` compares the raw string, so a Version parse here would # be wasted. if self._spec[0] == "===": return bool(list(self.filter([item], prereleases=prereleases)))
parsed = coerce_version(item) if parsed is None: # Standard operators never match an unparsable input. return False
if prereleases is None: prereleases = resolve_prereleases(self._prereleases, self.prereleases)
if prereleases is False and parsed.is_prerelease: return False
# ``_fast_match`` answers the simple operators without building a # range; otherwise fall back to the engine's bounds membership. match = _fast_match(self, parsed) if match is not None: return match
return matches_bounds_only(self._to_ranges(), parsed)
@typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ...
@typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ...
def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """Filter items in the given iterable, that match the specifier.
:param iterable: An iterable that can contain version strings and :class:`~packaging.version.Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions. :param key: A callable that takes a single argument (an item from the iterable) and returns a version string or :class:`~packaging.version.Version` instance to be used for filtering.
>>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) ['1.2.3', '1.3', <Version('1.4')>] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3").filter( ... [{"ver": "1.2"}, {"ver": "1.3"}], ... key=lambda x: x["ver"])) [{'ver': '1.3'}]
.. versionchanged:: 26.1
Added the ``key`` parameter. """ if prereleases is None: prereleases = resolve_prereleases(self._prereleases, self.prereleases)
if self.operator == "===": spec_lower = self.version.lower() matches = ( item for item in iterable if str(item if key is None else key(item)).lower() == spec_lower ) return _apply_prereleases_filter(matches, key, prereleases)
return filter_by_ranges(self._to_ranges(), iterable, key, prereleases)
def _apply_prereleases_filter( matches: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None, prereleases: bool | None,) -> Iterator[Any]: """Apply ``prereleases=`` handling to an already-matched iterable.
``None`` means PEP 440 default (buffer pre-releases until a final appears); ``True`` yields everything; ``False`` drops pre-releases. """ if prereleases is None: return _pep440_filter_prereleases(matches, key) if prereleases: return iter(matches) return ( item for item in matches if (parsed := coerce_version(item if key is None else key(item))) is None or not parsed.is_prerelease )
class SpecifierSet(BaseSpecifier): """This class abstracts handling of a set of version specifiers.
It can be passed a single specifier (``>=3.0``), a comma-separated list of specifiers (``>=3.0,!=3.1``), or no specifier at all.
Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases.
.. versionchanged:: 26.2
Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """
__slots__ = ( "_canonicalized", "_has_arbitrary", "_is_unsatisfiable", "_prereleases", "_ranges", "_specs", )
def __init__( self, specifiers: str | Iterable[Specifier] = "", prereleases: bool | None = None, ) -> None: """Initialize a SpecifierSet instance.
:param specifiers: The string representation of a specifier or a comma-separated list of specifiers which will be parsed and normalized before use. May also be an iterable of ``Specifier`` instances, which will be used as is. :param prereleases: This tells the SpecifierSet if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers.
:raises InvalidSpecifier: If the given ``specifiers`` are not parseable than this exception will be raised. """
if isinstance(specifiers, str): # Split on `,` to break each individual specifier into its own item, and # strip each item to remove leading/trailing whitespace. split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]
self._specs: tuple[Specifier, ...] = tuple(map(Specifier, split_specifiers)) # Fast substring check; avoids iterating parsed specs. self._has_arbitrary = "===" in specifiers else: self._specs = tuple(specifiers) # Substring check works for both Specifier objects and plain # strings (setuptools passes lists of strings). self._has_arbitrary = any("===" in str(s) for s in self._specs)
self._canonicalized = len(self._specs) <= 1 self._is_unsatisfiable: bool | None = None self._ranges: Sequence[Interval] | None = None
# Store our prereleases value so we can use it later to determine if # we accept prereleases or not. self._prereleases = prereleases
def _canonical_specs(self) -> tuple[Specifier, ...]: """Deduplicate, sort, and cache specs for order-sensitive operations.""" if not self._canonicalized: self._specs = tuple(dict.fromkeys(sorted(self._specs, key=str))) self._canonicalized = True return self._specs
@property def prereleases(self) -> bool | None: # If we have been given an explicit prerelease modifier, then we'll # pass that through here. if self._prereleases is not None: return self._prereleases
# If we don't have any specifiers, and we don't have a forced value, # then we'll just return None since we don't know if this should have # pre-releases or not. if not self._specs: return None
# Otherwise we'll see if any of the given specifiers accept # prereleases, if any of them do we'll return True, otherwise False. if any(s.prereleases for s in self._specs): return True
return None
@prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value self._is_unsatisfiable = None
def __getstate__(self) -> tuple[tuple[Specifier, ...], bool | None]: # Return state as a 2-item tuple for compactness: # (specs, prereleases) # Cache members are excluded and will be recomputed on demand. return (self._specs, self._prereleases)
def __setstate__(self, state: object) -> None: # Always discard cached values - they will be recomputed on demand. self._ranges = None self._is_unsatisfiable = None
if isinstance(state, tuple): if len(state) == 2: # New format (26.2+): (specs, prereleases) specs, prereleases = state if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in specs) return if len(state) == 2 and isinstance(state[1], dict): # Format (packaging 26.0-26.1): (None, {slot: value}). _, slot_dict = state specs = slot_dict.get("_specs", ()) prereleases = slot_dict.get("_prereleases") # Convert frozenset to tuple (26.0 stored as frozenset) if isinstance(specs, frozenset): specs = tuple(sorted(specs, key=str)) if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(self._specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in self._specs) return if isinstance(state, dict): # Old format (packaging <= 25.x, no __slots__): state is a plain dict. specs = state.get("_specs", ()) prereleases = state.get("_prereleases") # Convert frozenset to tuple (26.0 stored as frozenset) if isinstance(specs, frozenset): specs = tuple(sorted(specs, key=str)) if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(self._specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in self._specs) return
raise TypeError(f"Cannot restore SpecifierSet from {state!r}")
def __repr__(self) -> str: """A representation of the specifier set that shows all internal state.
Note that the ordering of the individual specifiers within the set may not match the input string.
>>> SpecifierSet('>=1.0.0,!=2.0.0') <SpecifierSet('!=2.0.0,>=1.0.0')> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=False)> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) <SpecifierSet('!=2.0.0,>=1.0.0', prereleases=True)> """ pre = ( f", prereleases={self.prereleases!r}" if self._prereleases is not None else "" )
return f"<{self.__class__.__name__}({str(self)!r}{pre})>"
def __str__(self) -> str: """A string representation of the specifier set that can be round-tripped.
Note that the ordering of the individual specifiers within the set may not match the input string.
>>> str(SpecifierSet(">=1.0.0,!=1.0.1")) '!=1.0.1,>=1.0.0' >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) '!=1.0.1,>=1.0.0' """ return ",".join(str(s) for s in self._canonical_specs())
def __hash__(self) -> int: return hash(self._canonical_specs())
def __and__(self, other: SpecifierSet | str) -> SpecifierSet: """Return a SpecifierSet which is a combination of the two sets.
:param other: The other object to combine with.
>>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')> >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') <SpecifierSet('!=1.0.1,!=2.0.1,<=2.0.0,>=1.0.0')> """ if isinstance(other, str): other = SpecifierSet(other) elif not isinstance(other, SpecifierSet): return NotImplemented
specifier = SpecifierSet() specifier._specs = self._specs + other._specs specifier._canonicalized = len(specifier._specs) <= 1 specifier._has_arbitrary = self._has_arbitrary or other._has_arbitrary
# Combine prerelease settings: use common or non-None value if self._prereleases is None or self._prereleases == other._prereleases: specifier._prereleases = other._prereleases elif other._prereleases is None: specifier._prereleases = self._prereleases else: raise ValueError( "Cannot combine SpecifierSets with True and False prerelease overrides." )
return specifier
def __eq__(self, other: object) -> bool: """Whether or not the two SpecifierSet-like objects are equal.
:param other: The other object to check against.
The value of :attr:`prereleases` is ignored.
>>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") True >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) True >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" True >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") False >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") False """ if isinstance(other, (str, Specifier)): other = SpecifierSet(str(other)) elif not isinstance(other, SpecifierSet): return NotImplemented
return self._canonical_specs() == other._canonical_specs()
def __len__(self) -> int: """Returns the number of specifiers in this specifier set.""" return len(self._specs)
def __iter__(self) -> Iterator[Specifier]: """ Returns an iterator over all the underlying :class:`Specifier` instances in this specifier set.
>>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) [<Specifier('!=1.0.1')>, <Specifier('>=1.0.0')>] """ return iter(self._specs)
def _get_ranges(self) -> Sequence[Interval]: """Intersect all specifiers into a single sequence of version ranges.
Empty when unsatisfiable. Callers must ensure ``self._specs`` is non-empty. """ if self._ranges is not None: return self._ranges
self._ranges = intersect_specifier_bounds(s._to_ranges() for s in self._specs) return self._ranges
def is_unsatisfiable(self) -> bool: """Check whether this specifier set can never be satisfied.
Returns True if no version can satisfy all specifiers simultaneously.
>>> SpecifierSet(">=2.0,<1.0").is_unsatisfiable() True >>> SpecifierSet(">=1.0,<2.0").is_unsatisfiable() False >>> SpecifierSet("").is_unsatisfiable() False >>> SpecifierSet("==1.0,!=1.0").is_unsatisfiable() True
.. versionadded:: 26.1 """ cached = self._is_unsatisfiable if cached is not None: return cached
if not self._specs: self._is_unsatisfiable = False return False
result = not self._get_ranges()
if not result: result = self._check_arbitrary_unsatisfiable()
if not result and self.prereleases is False: result = ranges_are_prerelease_only(self._get_ranges())
self._is_unsatisfiable = result return result
def _check_arbitrary_unsatisfiable(self) -> bool: """Check === (arbitrary equality) specs for unsatisfiability.
=== uses case-insensitive string comparison, so the only candidate that can match ``===V`` is the literal string V. This method checks whether that candidate is excluded by other specifiers. """ arbitrary = [s for s in self._specs if s.operator == "==="] if not arbitrary: return False
# Multiple === must agree on the same string (case-insensitive). first = arbitrary[0].version.lower() if any(s.version.lower() != first for s in arbitrary[1:]): return True
# The sole candidate is the === version string. Check whether # it can satisfy every standard spec. candidate = coerce_version(arbitrary[0].version)
# With prereleases=False, a prerelease candidate is excluded # by contains() before the === string check even runs. if ( self.prereleases is False and candidate is not None and candidate.is_prerelease ): return True
standard = [s for s in self._specs if s.operator != "==="] if not standard: return False
if candidate is None: # Unparsable string cannot satisfy any standard spec. return True
return not all(s.contains(candidate) for s in standard)
def to_range(self) -> ranges.VersionRange: """Return the :class:`~packaging.ranges.VersionRange` this set accepts.
An empty set yields the full range; an unsatisfiable set yields the empty range. ``===`` specifiers contribute literal-string admission.
>>> SpecifierSet(">=1.0,<2.0").to_range() <VersionRange '[1.0, 2.0.dev0)'>
.. versionadded:: 26.3 """ from .ranges import VersionRange # noqa: PLC0415
return VersionRange._from_specifier_set(self)
def _check_relation_operand(self, other: object) -> None: if not isinstance(other, SpecifierSet): raise TypeError("expected a SpecifierSet") if self._has_arbitrary or other._has_arbitrary: raise ValueError("set relations do not support === specifiers")
def is_subset(self, other: SpecifierSet) -> bool: """Return whether every version matching this set also matches other.
:raises ValueError: If either set uses ``===`` specifiers, or the two sets were given different ``prereleases`` arguments (unset on one side counts as different). :raises TypeError: If other is not a :class:`SpecifierSet`.
>>> SpecifierSet(">=3.12,<3.13").is_subset(SpecifierSet(">=3.12")) True >>> SpecifierSet(">=3.12").is_subset(SpecifierSet(">=3.12,<3.13")) False
.. versionadded:: 26.3 """ self._check_relation_operand(other) return self.to_range().is_subset(other.to_range())
def is_superset(self, other: SpecifierSet) -> bool: """Return whether every version matching other also matches this set.
:raises ValueError: If either set uses ``===`` specifiers, or the two sets were given different ``prereleases`` arguments (unset on one side counts as different). :raises TypeError: If other is not a :class:`SpecifierSet`.
>>> SpecifierSet(">=3.12").is_superset(SpecifierSet(">=3.12,<3.13")) True
.. versionadded:: 26.3 """ self._check_relation_operand(other) return self.to_range().is_superset(other.to_range())
def is_disjoint(self, other: SpecifierSet) -> bool: """Return whether this set and other share no matching versions.
:raises ValueError: If either set uses ``===`` specifiers, or the two sets were given different ``prereleases`` arguments (unset on one side counts as different). :raises TypeError: If other is not a :class:`SpecifierSet`.
>>> SpecifierSet("<3.12").is_disjoint(SpecifierSet(">=3.12")) True >>> SpecifierSet("<3.12").is_disjoint(SpecifierSet(">=3.11")) False
.. versionadded:: 26.3 """ self._check_relation_operand(other) return self.to_range().is_disjoint(other.to_range())
def __contains__(self, item: UnparsedVersion) -> bool: """Return whether or not the item is contained in this specifier.
:param item: The item to check for.
This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed.
>>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") True >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") True >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") False >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") True >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) True """ return self.contains(item)
def contains( self, item: UnparsedVersion, prereleases: bool | None = None, installed: bool | None = None, ) -> bool: """Return whether or not the item is contained in this SpecifierSet.
:param item: The item to check for, which can be a version string or a :class:`~packaging.version.Version` instance. :param prereleases: Whether or not to match prereleases with this SpecifierSet. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases, as there are no other versions. :param installed: Whether or not the item is installed. If set to ``True``, it will accept prerelease versions even if the specifier does not allow them.
>>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") False >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") True >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1") False >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) True
.. versionchanged:: 26.0
With ``prereleases=None``, a prerelease now matches. A single version has no alternatives, so the :pep:`440` rule to accept prereleases when nothing else satisfies the specifiers applies. Earlier versions rejected it. An unparsable version now returns ``False`` instead of raising :exc:`~packaging.version.InvalidVersion`. """ version = coerce_version(item)
if version is not None and installed and version.is_prerelease: prereleases = True
# When item is a string and === is involved, keep it as-is # so the comparison isn't done against the normalized form. if version is None or (self._has_arbitrary and not isinstance(item, Version)): check_item = item else: check_item = version
# Fast path: a parseable, local-free version against a rangelike set. # A local on ``version`` needs PEP 440 stripping that the range path # applies. if ( version is not None and not self._has_arbitrary and version.local is None and self._specs ): if version.is_prerelease and ( prereleases is False or (prereleases is None and self._prereleases is False) ): return False
bounds = self._ranges if bounds is None: # Per-spec ``_fast_match`` answers a set of simple specifiers # without folding anything. If a spec needs the range path, # fold the intersected bounds once and cache them so repeated # checks on the same set stay cheap. for spec in self._specs: match = _fast_match(spec, version) if match is None: break if not match: return False else: return True
bounds = self._ranges = self._get_ranges()
return matches_bounds_only(bounds, version)
return bool(list(self.filter([check_item], prereleases=prereleases)))
@typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ...
@typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ...
def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """Filter items in the given iterable, that match the specifiers in this set.
:param iterable: An iterable that can contain version strings and :class:`~packaging.version.Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions. :param key: A callable that takes a single argument (an item from the iterable) and returns a version string or :class:`~packaging.version.Version` instance to be used for filtering.
>>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) ['1.3', <Version('1.4')>] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3").filter( ... [{"ver": "1.2"}, {"ver": "1.3"}], ... key=lambda x: x["ver"])) [{'ver': '1.3'}]
An "empty" SpecifierSet will filter items based on the presence of prerelease versions in the set.
>>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet("").filter(["1.5a1"])) ['1.5a1'] >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1']
.. versionchanged:: 26.0
Prerelease filtering now follows the PEP 440 recommendation of yielding prereleases only when no final release is present.
.. versionchanged:: 26.1
Added the ``key`` parameter. """ # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None and self.prereleases is not None: prereleases = self.prereleases
if self._specs: if self._has_arbitrary: # Slow path for === specs = self._specs matches = ( item for item in iterable if all( s.contains(item if key is None else key(item), prereleases=True) for s in specs ) ) return _apply_prereleases_filter(matches, key, prereleases)
ranges = self._ranges if ranges is None: ranges = self._get_ranges() return filter_by_ranges(ranges, iterable, key, prereleases)
# Empty SpecifierSet. return _apply_prereleases_filter(iterable, key, prereleases)
def _pep440_filter_prereleases( iterable: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None) -> Iterator[Any]: """Filter per PEP 440: exclude prereleases unless no finals exist.""" # Two lists used: # * all_nonfinal to preserve order if no finals exist # * arbitrary_strings for streaming when first final found all_nonfinal: list[Any] = [] arbitrary_strings: list[Any] = []
found_final = False for item in iterable: parsed = coerce_version(item if key is None else key(item))
if parsed is None: # Arbitrary strings are always included as it is not # possible to determine if they are prereleases, # and they have already passed all specifiers. if found_final: yield item else: arbitrary_strings.append(item) all_nonfinal.append(item) continue
if not parsed.is_prerelease: # Final release found - flush arbitrary strings, then yield if not found_final: yield from arbitrary_strings found_final = True yield item continue
# Prerelease - buffer if no finals yet, otherwise skip if not found_final: all_nonfinal.append(item)
# No finals found - yield all buffered items if not found_final: yield from all_nonfinal123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
from __future__ import annotations
import loggingimport operatorimport platformimport reimport structimport subprocessimport sysimport sysconfigfrom collections.abc import Iterable, Iterator, Sequencefrom importlib.machinery import EXTENSION_SUFFIXESfrom typing import ( TYPE_CHECKING, TypeVar, cast,)
from . import _manylinux, _musllinux
if TYPE_CHECKING: from collections.abc import Callable from collections.abc import Set as AbstractSet
__all__ = [ "INTERPRETER_SHORT_NAMES", "AppleVersion", "InvalidTag", "PythonVersion", "Tag", "TooManyTagsError", "UnsortedTagsError", "android_platforms", "compatible_tags", "cpython_tags", "create_compatible_tags_selector", "generic_tags", "interpreter_name", "interpreter_version", "ios_platforms", "mac_platforms", "parse_tag", "platform_tags", "pure_python_tags", "sys_tags",]
def __dir__() -> list[str]: return __all__
logger = logging.getLogger(__name__)
PythonVersion = Sequence[int]"""A sequence of integers describing a Python version, e.g. ``(3, 13)``.
.. versionadded:: 20.0"""
AppleVersion = tuple[int, int]"""A ``(major, minor)`` integer pair describing an Apple OS version.
.. versionadded:: 24.2"""_T = TypeVar("_T")
INTERPRETER_SHORT_NAMES: dict[str, str] = { "python": "py", # Generic. "cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy",}
# This function can be unit tested without reloading the module# (Unlike _32_BIT_INTERPRETER)def _compute_32_bit_interpreter() -> bool: return struct.calcsize("P") == 4
_32_BIT_INTERPRETER = _compute_32_bit_interpreter()
class UnsortedTagsError(ValueError): """ Raised when a tag component is not in sorted order per PEP 425.
.. versionadded:: 26.1 """
class InvalidTag(ValueError): """ Raised when an interpreter component is not an identifier, a tag component is empty, or a tag does not have exactly three components.
.. versionadded:: 26.3 """
class TooManyTagsError(ValueError): """ Raised when a compressed tag set exceeds the configured limit.
.. versionadded:: 26.3 """
class Tag: """ A representation of the tag triple for a wheel.
Instances are considered immutable and thus are hashable. Equality checking is also supported.
Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases.
.. versionchanged:: 26.2
Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """
__slots__ = ["_abi", "_hash", "_interpreter", "_platform"]
def __init__(self, interpreter: str, abi: str, platform: str) -> None: """ :param str interpreter: The interpreter name, e.g. ``"py"`` (see :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter names to their short names). :param str abi: The ABI that a wheel supports, e.g. ``"cp37m"``. :param str platform: The OS/platform the wheel supports, e.g. ``"win_amd64"``. """ self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() # The __hash__ of every single element in a Set[Tag] will be evaluated each time # that a set calls its `.disjoint()` method, which may be called hundreds of # times when scanning a page of links for packages with tags matching that # Set[Tag]. Pre-computing the value here produces significant speedups for # downstream consumers. self._hash = hash((self._interpreter, self._abi, self._platform))
@property def interpreter(self) -> str: """ The interpreter name, e.g. ``"py"`` (see :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter names to their short names). """ return self._interpreter
@property def abi(self) -> str: """ The supported ABI. """ return self._abi
@property def platform(self) -> str: """ The OS/platform. """ return self._platform
def __eq__(self, other: object) -> bool: if not isinstance(other, Tag): return NotImplemented
return ( (self._hash == other._hash) # Short-circuit ASAP for perf reasons. and (self._platform == other._platform) and (self._abi == other._abi) and (self._interpreter == other._interpreter) )
def __hash__(self) -> int: return self._hash
def __str__(self) -> str: return f"{self._interpreter}-{self._abi}-{self._platform}"
def __repr__(self) -> str: return f"<{self} @ {id(self)}>"
def __getstate__(self) -> tuple[str, str, str]: # Return state as a 3-item tuple: (interpreter, abi, platform). # Cache member _hash is excluded and will be recomputed. return (self._interpreter, self._abi, self._platform)
def __setstate__(self, state: object) -> None: if isinstance(state, tuple): if len(state) == 3 and all(isinstance(s, str) for s in state): # New format (26.2+): (interpreter, abi, platform) self._interpreter, self._abi, self._platform = state self._hash = hash((self._interpreter, self._abi, self._platform)) return if len(state) == 2 and isinstance(state[1], dict): # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). _, slots = state try: interpreter = slots["_interpreter"] abi = slots["_abi"] platform = slots["_platform"] except KeyError: raise TypeError(f"Cannot restore Tag from {state!r}") from None if not all( isinstance(value, str) for value in (interpreter, abi, platform) ): raise TypeError(f"Cannot restore Tag from {state!r}") self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() self._hash = hash((self._interpreter, self._abi, self._platform)) return raise TypeError(f"Cannot restore Tag from {state!r}")
def parse_tag( tag: str, *, validate_order: bool = False, limit: int | None = None) -> frozenset[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of :class:`Tag` instances.
Returning a set is required due to the possibility that the tag is a `compressed tag set`_, e.g. ``"py2.py3-none-any"`` which supports both Python 2 and Python 3.
If **validate_order** is true, compressed tag set components are checked to be in sorted order as required by PEP 425.
If **limit** is not ``None``, the compressed tag set can generate at most that many tags.
:param str tag: The tag to parse, e.g. ``"py3-none-any"``. :param bool validate_order: Check whether compressed tag set components are in sorted order. :param int | None limit: The maximum number of tags to parse. :raises UnsortedTagsError: If **validate_order** is true and any compressed tag set component is not in sorted order. :raises InvalidTag: If the interpreter field is not an identifier; if the interpreter, ABI, or platform field (or any member of a compressed tag set) is empty; or if the tag does not have exactly three components. :raises TooManyTagsError: If **limit** is not ``None`` and the compressed tag set would generate more than **limit** tags. :raises ValueError: If **limit** is negative.
.. versionadded:: 26.1 The *validate_order* parameter.
.. versionadded:: 26.3 Raises :class:`InvalidTag` when an interpreter component is not an identifier, a tag component is empty, or a tag does not have exactly three components. Added the *limit* parameter. Raises :class:`TooManyTagsError` if the compressed tag set would generate more than *limit* tags. """
if limit is not None and limit < 0: raise ValueError("limit must be non-negative")
component_parts = [component.split(".") for component in tag.split("-")] for parts in component_parts: if "" in parts: component = ".".join(parts) raise InvalidTag(f"Tag {tag!r} has an empty component: {component!r}") if validate_order and parts != sorted(parts): component = ".".join(parts) raise UnsortedTagsError( f"Tag component {component!r} is not in sorted order per PEP 425" )
tag_count = 1 for parts in component_parts: tag_count *= len(parts)
if limit is not None and tag_count > limit: raise TooManyTagsError( f"Compressed tag set would generate {tag_count} tags, exceeding " f"limit {limit}" )
try: interpreters, abis, platforms = component_parts except ValueError as exc: raise InvalidTag(f"Tag {tag!r} must have exactly three components") from exc for interpreter in interpreters: if not interpreter.isidentifier(): raise InvalidTag(f"Tag {tag!r} has an invalid interpreter: {interpreter!r}") return frozenset( Tag(interpreter, abi, platform_) for interpreter in interpreters for abi in abis for platform_ in platforms )
def _get_config_var(name: str, warn: bool = False) -> int | str | None: value: int | str | None = sysconfig.get_config_var(name) if value is None and warn: logger.debug( "Config variable '%s' is unset, Python ABI tag may be incorrect", name ) return value
def _normalize_string(string: str) -> str: return string.replace(".", "_").replace("-", "_").replace(" ", "_")
def _is_threaded_cpython(abis: list[str]) -> bool: """ Determine if the ABI corresponds to a threaded (`--disable-gil`) build.
The threaded builds are indicated by a "t" in the abiflags. """ if len(abis) == 0: return False # expect e.g., cp313 m = re.match(r"cp\d+(.*)", abis[0]) if not m: return False abiflags = m.group(1) return "t" in abiflags
def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: """ Determine if the Python version supports abi3.
PEP 384 was first implemented in Python 3.2. The free-threaded builds do not support abi3. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading
def _abi3t_applies(python_version: PythonVersion, threading: bool) -> bool: """ Determine if the Python version supports abi3t.
PEP 803 was first implemented in Python 3.15 but, per PEP 803, this returns tags going back to Python 3.2 to mirror the abi3 implementation and leave open the possibility of abi3t wheels supporting older Python versions.
""" return len(python_version) > 1 and tuple(python_version) >= (3, 2) and threading
def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: py_version = tuple(py_version) # To allow for version comparison. abis = [] version = _version_nodot(py_version[:2]) threading = debug = pymalloc = ucs4 = "" with_debug = _get_config_var("Py_DEBUG", warn) has_refcount = hasattr(sys, "gettotalrefcount") # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled # extension modules is the best option. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 has_ext = "_d.pyd" in EXTENSION_SUFFIXES if with_debug or (with_debug is None and (has_refcount or has_ext)): debug = "d" if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): threading = "t" if py_version < (3, 8): with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) if with_pymalloc or with_pymalloc is None: pymalloc = "m" if py_version < (3, 3): unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) if unicode_size == 4 or ( unicode_size is None and sys.maxunicode == 0x10FFFF ): ucs4 = "u" elif debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}{threading}") abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") return abis
def cpython_tags( python_version: PythonVersion | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False,) -> Iterator[Tag]: """ Yields the tags for the CPython interpreter.
The specific tags generated are:
- ``cp<python_version>-<abi>-<platform>`` - ``cp<python_version>-<stable_abi>-<platform>`` - ``cp<python_version>-none-<platform>`` - ``cp<older version>-<stable_abi>-<platform>`` where "older version" is all older minor versions down to Python 3.2 (when ``abi3`` was introduced)
If ``python_version`` only provides a major-only version then only user-provided ABIs via ``abis`` and the ``none`` ABI will be used.
The ``stable_abi`` will be either ``abi3`` or ``abi3t`` if `abi` is a GIL-enabled ABI like `"cp315"` or a free-threaded ABI like `"cp315t"`, respectively.
:param Sequence python_version: A one- or two-item sequence representing the targeted Python version. Defaults to ``sys.version_info[:2]``. :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs compatible with the current system. :param Iterable platforms: Iterable of compatible platforms. Defaults to the platforms compatible with the current system. :param bool warn: Whether warnings should be logged. Defaults to ``False``.
.. versionadded:: 20.0 """ if not python_version: python_version = sys.version_info[:2]
interpreter = f"cp{_version_nodot(python_version[:2])}"
if abis is None: abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else [] abis = list(abis) threading = _is_threaded_cpython(abis) # Stable ABIs and 'none' are explicitly handled later. explicit_abis = ("abi3", "abi3t", "none") if threading else ("abi3", "none") for explicit_abi in explicit_abis: try: abis.remove(explicit_abi) except ValueError: # noqa: PERF203 pass
platforms = list(platforms or platform_tags()) for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_)
use_abi3 = _abi3_applies(python_version, threading) use_abi3t = _abi3t_applies(python_version, threading) if use_abi3: yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) if use_abi3t: yield from (Tag(interpreter, "abi3t", platform_) for platform_ in platforms)
yield from (Tag(interpreter, "none", platform_) for platform_ in platforms)
if use_abi3 or use_abi3t: for minor_version in range(python_version[1] - 1, 1, -1): for platform_ in platforms: version = _version_nodot((python_version[0], minor_version)) interpreter = f"cp{version}" if use_abi3: yield Tag(interpreter, "abi3", platform_) if use_abi3t: # Support for abi3t was introduced in Python 3.15, but in # principle abi3t wheels are possible for older limited API # versions, so allow things like ("cp37", "abi3t", "platform") yield Tag(interpreter, "abi3t", platform_)
def _generic_abi() -> list[str]: """ Return the ABI tag based on EXT_SUFFIX. """ # The following are examples of `EXT_SUFFIX`. # We want to keep the parts which are related to the ABI and remove the # parts which are related to the platform: # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 # - mac: '.cpython-310-darwin.so' => cp310 # - win: '.cp310-win_amd64.pyd' => cp310 # - win: '.pyd' => cp37 (uses _cpython_abis()) # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' # => graalpy_38_native
ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) if not isinstance(ext_suffix, str) or not ext_suffix.startswith("."): raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") parts = ext_suffix.split(".") if len(parts) < 3: # CPython3.7 and earlier uses ".pyd" on Windows. return _cpython_abis(sys.version_info[:2]) soabi = parts[1] if soabi.startswith("cpython"): # non-windows cpython_parts = soabi.split("-") if len(cpython_parts) < 2 or not cpython_parts[1]: raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") abi = "cp" + cpython_parts[1] elif soabi.startswith("cp"): # windows abi = soabi.split("-")[0] elif soabi.startswith("pypy"): abi = "-".join(soabi.split("-")[:2]) elif soabi.startswith("graalpy"): abi = "-".join(soabi.split("-")[:3]) elif soabi: # pyston, ironpython, others? abi = soabi else: return [] return [_normalize_string(abi)]
def generic_tags( interpreter: str | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False,) -> Iterator[Tag]: """ Yields the tags for an interpreter which requires no specialization.
This function should be used if one of the other interpreter-specific functions provided by this module is not appropriate (i.e. not calculating tags for a CPython interpreter).
The specific tags generated are:
- ``<interpreter>-<abi>-<platform>``
The ``"none"`` ABI will be added if it was not explicitly provided.
:param str interpreter: The name of the interpreter. Defaults to being calculated. :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs compatible with the current system. :param Iterable platforms: Iterable of compatible platforms. Defaults to the platforms compatible with the current system. :param bool warn: Whether warnings should be logged. Defaults to ``False``.
.. versionadded:: 20.0 """ if not interpreter: interp_name = interpreter_name() interp_version = interpreter_version(warn=warn) interpreter = f"{interp_name}{interp_version}" abis = _generic_abi() if abis is None else list(abis) platforms = list(platforms or platform_tags()) if "none" not in abis: abis.append("none") for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_)
def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: """ Yields Python versions in descending order.
After the latest version, the major-only version will be yielded, and then all previous versions of that major version. """ if len(py_version) > 1: yield f"py{_version_nodot(py_version[:2])}" yield f"py{py_version[0]}" if len(py_version) > 1: for minor in range(py_version[1] - 1, -1, -1): yield f"py{_version_nodot((py_version[0], minor))}"
def pure_python_tags( python_version: PythonVersion | None = None,) -> Iterator[Tag]: """ Yields the pure-Python tags compatible with ``python_version``.
The tags use the ``"none"`` ABI and ``"any"`` platform, so their generation does not depend on the running platform.
.. versionadded:: 26.3
:param Sequence python_version: A one- or two-item sequence representing the compatible version of Python. Defaults to ``sys.version_info[:2]``. :raises ValueError: If ``python_version`` is an empty sequence. """ if python_version is None: python_version = sys.version_info[:2] elif not python_version: raise ValueError("python_version must contain at least one item") for version in _py_interpreter_range(python_version): yield Tag(version, "none", "any")
def compatible_tags( python_version: PythonVersion | None = None, interpreter: str | None = None, platforms: Iterable[str] | None = None,) -> Iterator[Tag]: """ Yields the tags for an interpreter compatible with the Python version specified by ``python_version``.
The specific tags generated are:
- ``py*-none-<platform>`` - ``<interpreter>-none-any`` if ``interpreter`` is provided - ``py*-none-any``
:param Sequence python_version: A one- or two-item sequence representing the compatible version of Python. Defaults to ``sys.version_info[:2]``. :param str interpreter: The name of the interpreter (if known), e.g. ``"cp38"``. Defaults to the current interpreter. :param Iterable platforms: Iterable of compatible platforms. Defaults to the platforms compatible with the current system.
.. versionadded:: 20.0 """ if not python_version: python_version = sys.version_info[:2] platforms = list(platforms or platform_tags()) for version in _py_interpreter_range(python_version): for platform_ in platforms: yield Tag(version, "none", platform_) if interpreter: yield Tag(interpreter, "none", "any") yield from pure_python_tags(python_version)
def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: if not is_32bit: return arch
if arch.startswith("ppc"): return "ppc"
return "i386"
def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: formats = [cpu_arch] if cpu_arch == "x86_64": if version < (10, 4): return [] formats.extend(["intel", "fat64", "fat3"])
elif cpu_arch == "i386": if version < (10, 4): return [] formats.extend(["intel", "fat3", "fat"])
elif cpu_arch == "ppc64": # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? if version > (10, 5) or version < (10, 4): return [] formats.append("fat64")
elif cpu_arch == "ppc": if version > (10, 6): return [] formats.extend(["fat3", "fat"])
if cpu_arch in {"arm64", "x86_64"}: formats.append("universal2")
if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: formats.append("universal")
return formats
def mac_platforms( version: AppleVersion | None = None, arch: str | None = None) -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for macOS.
The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system.
:param tuple version: A two-item tuple representing the version of macOS. Defaults to the current system's version. :param str arch: The CPU architecture. Defaults to the architecture of the current system, e.g. ``"x86_64"``.
.. note:: Equivalent support for the other major platforms is purposefully not provided:
- On Windows, platform compatibility is statically specified - On Linux, code must be run on the system itself to determine compatibility
.. versionadded:: 20.0 """ if version is None or arch is None: version_str, _, cpu_arch = platform.mac_ver() if version is None: version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) if version == (10, 16): # When built against an older macOS SDK, Python will report macOS 10.16 # instead of the real version. version_str = subprocess.run( [ sys.executable, "-sS", "-c", "import platform; print(platform.mac_ver()[0])", ], check=True, env={"SYSTEM_VERSION_COMPAT": "0"}, stdout=subprocess.PIPE, text=True, ).stdout version = cast( "AppleVersion", tuple(map(int, version_str.split(".")[:2])) ) if arch is None: arch = _mac_arch(cpu_arch)
if (10, 0) <= version < (11, 0): # Prior to Mac OS 11, each yearly release of Mac OS bumped the # "minor" version number. The major version was always 10. major_version = 10 for minor_version in range(version[1], -1, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}"
if version >= (11, 0): # Starting with Mac OS 11, each yearly release bumps the major version # number. The minor versions are now the midyear updates. minor_version = 0 for major_version in range(version[0], 10, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}"
# Mac OS 11 on x86_64 is compatible with binaries from previous releases. # Arm64 support was introduced in 11.0, so no Arm binaries from previous # releases exist. # # However, the "universal2" binary format can have a # macOS version earlier than 11.0 when the x86_64 part of the binary supports # that version of macOS. major_version = 10 if arch == "x86_64": for minor_version in range(16, 3, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}" else: for minor_version in range(16, 3, -1): compat_version = major_version, minor_version binary_format = "universal2" yield f"macosx_{major_version}_{minor_version}_{binary_format}"
def ios_platforms( version: AppleVersion | None = None, multiarch: str | None = None) -> Iterator[str]: """
Yields the :attr:`~Tag.platform` tags for iOS.
:param tuple version: A two-item tuple representing the version of iOS. Defaults to the current system's version. :param str multiarch: The CPU architecture+ABI to be used. This should be in the format by ``sys.implementation._multiarch`` (e.g., ``arm64_iphoneos`` or ``x86_64_iphonesimulator``). Defaults to the current system's multiarch value.
.. note:: Behavior of this method is undefined if invoked on non-iOS platforms without providing explicit version and multiarch arguments.
.. versionadded:: 24.2 """ if version is None: # if iOS is the current platform, ios_ver *must* be defined. However, # it won't exist for CPython versions before 3.13, which causes a mypy # error. _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] version = cast("AppleVersion", tuple(map(int, release.split(".")[:2])))
if multiarch is None: multiarch = sys.implementation._multiarch multiarch = multiarch.replace("-", "_")
ios_platform_template = "ios_{major}_{minor}_{multiarch}"
# Consider any iOS major.minor version from the version requested, down to # 12.0. 12.0 is the first iOS version that is known to have enough features # to support CPython. Consider every possible minor release up to X.9. There # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra # candidates that won't ever match doesn't really hurt, and it saves us from # having to keep an explicit list of known iOS versions in the code. Return # the results descending order of version number.
# If the requested major version is less than 12, there won't be any matches. if version[0] < 12: return
# Consider the actual X.Y version that was requested. yield ios_platform_template.format( major=version[0], minor=version[1], multiarch=multiarch )
# Consider every minor version from X.0 to the minor version prior to the # version requested by the platform. for minor in range(version[1] - 1, -1, -1): yield ios_platform_template.format( major=version[0], minor=minor, multiarch=multiarch )
for major in range(version[0] - 1, 11, -1): for minor in range(9, -1, -1): yield ios_platform_template.format( major=major, minor=minor, multiarch=multiarch )
def android_platforms( api_level: int | None = None, abi: str | None = None) -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on non-Android platforms, the ``api_level`` and ``abi`` arguments are required.
:param int api_level: The maximum `API level <https://developer.android.com/tools/releases/platforms>`__ to return. Defaults to the current system's version, as returned by ``platform.android_ver``. :param str abi: The `Android ABI <https://developer.android.com/ndk/guides/abis>`__, e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by ``sysconfig.get_platform``. Hyphens and periods will be replaced with underscores.
.. versionadded:: 25.0 """ if platform.system() != "Android" and (api_level is None or abi is None): raise TypeError( "on non-Android platforms, the api_level and abi arguments are required" )
if api_level is None: # Python 3.13 was the first version to return platform.system() == "Android", # and also the first version to define platform.android_ver(). api_level = platform.android_ver().api_level # type: ignore[attr-defined]
if abi is None: abi = sysconfig.get_platform().split("-")[-1] abi = _normalize_string(abi)
# 16 is the minimum API level known to have enough features to support CPython # without major patching. Yield every API level from the maximum down to the # minimum, inclusive. min_api_level = 16 for ver in range(api_level, min_api_level - 1, -1): yield f"android_{ver}_{abi}"
def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: linux = _normalize_string(sysconfig.get_platform()) if not linux.startswith("linux_"): # we should never be here, just yield the sysconfig one and return yield linux return if is_32bit: if linux == "linux_x86_64": linux = "linux_i686" elif linux == "linux_aarch64": linux = "linux_armv8l" _, arch = linux.split("_", 1) archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) for arch in archs: yield f"linux_{arch}" yield from _manylinux.platform_tags(archs) yield from _musllinux.platform_tags(archs)
def _emscripten_platforms() -> Iterator[str]: pyemscripten_platform_version = sysconfig.get_config_var( "PYEMSCRIPTEN_PLATFORM_VERSION" ) if pyemscripten_platform_version: yield f"pyemscripten_{pyemscripten_platform_version}_wasm32" yield from _generic_platforms()
def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform())
def platform_tags() -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for the running interpreter.
.. versionadded:: 21.1 """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "iOS": return ios_platforms() elif platform.system() == "Android": return android_platforms() elif platform.system() == "Linux": return _linux_platforms() elif platform.system() == "Emscripten": return _emscripten_platforms() else: return _generic_platforms()
def interpreter_name() -> str: """ Returns the name of the running interpreter.
Some implementations have a reserved, two-letter abbreviation which will be returned when appropriate.
This typically acts as the prefix to the :attr:`~Tag.interpreter` tag.
.. versionadded:: 20.0 """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name
def interpreter_version(*, warn: bool = False) -> str: """ Returns the running interpreter's version.
This typically acts as the suffix to the :attr:`~Tag.interpreter` tag.
:param bool warn: Whether warnings should be logged. Defaults to ``False``.
.. versionadded:: 20.0 """ version = _get_config_var("py_version_nodot", warn=warn) return str(version) if version else _version_nodot(sys.version_info[:2])
def _version_nodot(version: PythonVersion) -> str: return "".join(map(str, version))
def sys_tags(*, warn: bool = False) -> Iterator[Tag]: """ Yields the sequence of tag triples that the running interpreter supports.
The iterable is ordered so that the best-matching tag is first in the sequence. The exact preferential order to tags is interpreter-specific, but in general the tag importance is in the order of:
1. Interpreter 2. Platform 3. ABI
This order is due to the fact that an ABI is inherently tied to the platform, but platform-specific code is not necessarily tied to the ABI. The interpreter is the most important tag as it dictates basic support for any wheel.
The function returns an iterable in order to allow for the possible short-circuiting of tag generation if the entire sequence is not necessary and tag calculation happens to be expensive.
:param bool warn: Whether warnings should be logged. Defaults to ``False``.
.. versionchanged:: 21.3 Added the `pp3-none-any` tag (:issue:`311`). .. versionchanged:: 26.1 Added the `abi3t` tag (:issue:`1099`). .. versionchanged:: 26.3 Native ``linux_*`` platform tags are now ordered before ``manylinux`` and ``musllinux`` tags (:issue:`160`). """
interp_name = interpreter_name() if interp_name == "cp": yield from cpython_tags(warn=warn) else: yield from generic_tags(warn=warn)
if interp_name == "pp": interp = "pp3" elif interp_name == "cp": interp = "cp" + interpreter_version(warn=warn) else: interp = None yield from compatible_tags(interpreter=interp)
def create_compatible_tags_selector( tags: Iterable[Tag],) -> Callable[[Iterable[tuple[_T, AbstractSet[Tag]]]], Iterator[_T]]: """Create a callable to select things compatible with supported tags.
This function accepts an ordered sequence of tags, with the preferred tags first.
The returned callable accepts an iterable of tuples (thing, set[Tag]), and returns an iterator of things, with the things with the best matching tags first.
Example to select compatible wheel filenames:
>>> from packaging import tags >>> from packaging.utils import parse_wheel_filename >>> selector = tags.create_compatible_tags_selector(tags.sys_tags()) >>> filenames = ["foo-1.0-py3-none-any.whl", "foo-1.0-py2-none-any.whl"] >>> list(selector([ ... (filename, parse_wheel_filename(filename)[-1]) for filename in filenames ... ])) ['foo-1.0-py3-none-any.whl']
.. versionadded:: 26.1 """ tag_ranks: dict[Tag, int] = {} for rank, tag in enumerate(tags): tag_ranks.setdefault(tag, rank) # ignore duplicate tags, keep first supported_tags = tag_ranks.keys()
def selector( tagged_things: Iterable[tuple[_T, AbstractSet[Tag]]], ) -> Iterator[_T]: ranked_things: list[tuple[_T, int]] = [] for thing, thing_tags in tagged_things: supported_thing_tags = thing_tags & supported_tags if supported_thing_tags: thing_rank = min(tag_ranks[t] for t in supported_thing_tags) ranked_things.append((thing, thing_rank)) return iter( thing for thing, _ in sorted(ranked_things, key=operator.itemgetter(1)) )
return selector123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
from __future__ import annotations
import refrom typing import NewType, Union, cast
from .tags import InvalidTag, Tag, UnsortedTagsError, parse_tagfrom .version import InvalidVersion, Version, _TrimmedRelease
__all__ = [ "BuildTag", "InvalidName", "InvalidSdistFilename", "InvalidWheelFilename", "NormalizedName", "canonicalize_name", "canonicalize_version", "is_normalized_name", "parse_sdist_filename", "parse_wheel_filename",]
def __dir__() -> list[str]: return __all__
BuildTag = Union[tuple[()], tuple[int, str]]"""A wheel build tag: an empty tuple, or a ``(build number, build tag suffix)`` pair.
.. versionadded:: 20.9"""
NormalizedName = NewType("NormalizedName", str)"""A :class:`typing.NewType` of :class:`str`, representing a normalized name.
.. versionadded:: 20.4"""
class InvalidName(ValueError): """ An invalid distribution name; users should refer to the packaging user guide.
.. versionadded:: 23.2 """
class InvalidWheelFilename(ValueError): """ An invalid wheel filename was found, users should refer to PEP 427.
.. versionadded:: 20.9 """
class InvalidSdistFilename(ValueError): """ An invalid sdist filename was found, users should refer to the packaging user guide.
.. versionadded:: 20.9 """
# Core metadata spec for `Name`_validate_regex = re.compile( r"[a-z0-9]|[a-z0-9][a-z0-9._-]*[a-z0-9]", re.IGNORECASE | re.ASCII)_normalized_regex = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*", re.ASCII)# PEP 427: The build number must start with a digit._build_tag_regex = re.compile(r"(\d+)(.*)", re.ASCII)# PEP 427: Valid characters for an escaped project name in a wheel filename.# Requires at least one character so an empty project name is rejected._wheel_name_regex = re.compile(r"^[\w._]+\Z", re.UNICODE)
def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: """ This function takes a valid Python package or extra name, and returns the normalized form of it.
The return type is typed as :class:`NormalizedName`. This allows type checkers to help require that a string has passed through this function before use.
If **validate** is true, then the function will check if **name** is a valid distribution name before normalizing.
:param str name: The name to normalize. :param bool validate: Check whether the name is a valid distribution name. :raises InvalidName: If **validate** is true and the name is not an acceptable distribution name.
>>> from packaging.utils import canonicalize_name >>> canonicalize_name("Django") 'django' >>> canonicalize_name("oslo.concurrency") 'oslo-concurrency' >>> canonicalize_name("requests") 'requests'
.. versionadded:: 16.2
.. versionchanged:: 20.4 The return type was changed to :class:`NormalizedName`.
.. versionchanged:: 23.2 Added the *validate* keyword parameter. """ if validate and not _validate_regex.fullmatch(name): raise InvalidName(f"name is invalid: {name!r}") # Ensure all ``.`` and ``_`` are ``-`` # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 # Much faster than re, and even faster than str.translate value = name.lower().replace("_", "-").replace(".", "-") # Condense repeats (faster than regex) while "--" in value: value = value.replace("--", "-") return cast("NormalizedName", value)
def is_normalized_name(name: str) -> bool: """ Check if a name is a normalized project name (i.e. a valid name that :func:`canonicalize_name` would roundtrip to the same value).
The roundtrip only characterizes normalized names for *valid* names. A name must start and end with an ASCII letter or digit, which :func:`canonicalize_name` does not enforce: it leaves a leading or trailing hyphen in place, so such a name roundtrips without being normalized.
:param str name: The name to check.
>>> from packaging.utils import canonicalize_name, is_normalized_name >>> is_normalized_name("requests") True >>> is_normalized_name("Django") False >>> canonicalize_name("_not_legal") '-not-legal' >>> is_normalized_name("-not-legal") # roundtrips, but not a valid name False
.. versionadded:: 23.2 """ return _normalized_regex.fullmatch(name) is not None
def canonicalize_version( version: Version | str, *, strip_trailing_zero: bool = True) -> str: """Return a canonical form of a version as a string.
This function takes a string representing a package version (or a :class:`~packaging.version.Version` instance), and returns the normalized form of it. By default, it strips trailing zeros from the release segment.
>>> from packaging.utils import canonicalize_version >>> canonicalize_version('1.0.1') '1.0.1'
Per PEP 625, versions may have multiple canonical forms, differing only by trailing zeros.
>>> canonicalize_version('1.0.0') '1' >>> canonicalize_version('1.0.0', strip_trailing_zero=False) '1.0.0'
Invalid versions are returned unaltered.
>>> canonicalize_version('foo bar baz') 'foo bar baz'
>>> canonicalize_version('1.4.0.0.0') '1.4'
.. versionadded:: 17.1
.. versionchanged:: 21.0 The return type was narrowed to :class:`str`.
.. versionchanged:: 22.0 Added the *strip_trailing_zero* keyword parameter. """ if isinstance(version, str): try: version = Version(version) except InvalidVersion: return str(version) return str(_TrimmedRelease(version) if strip_trailing_zero else version)
def parse_wheel_filename( filename: str, *, validate_order: bool = False,) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: """ This function takes the filename of a wheel file, and parses it, returning a tuple of name, version, build number, and tags.
The name part of the tuple is normalized and typed as :class:`NormalizedName`. The version portion is an instance of :class:`~packaging.version.Version`. The build number is ``()`` if there is no build number in the wheel filename, otherwise a two-item tuple of an integer for the leading digits and a string for the rest of the build number. The tags portion is a frozen set of :class:`~packaging.tags.Tag` instances (as the tag string format allows multiple tags to be combined into a single string).
If **validate_order** is true, compressed tag set components are checked to be in sorted order as required by PEP 425.
:param str filename: The name of the wheel file. :param bool validate_order: Check whether compressed tag set components are in sorted order. :raises InvalidWheelFilename: If the filename in question does not follow the :ref:`wheel specification <pypug:binary-distribution-format>`.
>>> from packaging.utils import parse_wheel_filename >>> from packaging.tags import Tag >>> from packaging.version import Version >>> name, ver, build, tags = parse_wheel_filename("foo-1.0-py3-none-any.whl") >>> name 'foo' >>> ver == Version('1.0') True >>> tags == {Tag("py3", "none", "any")} True >>> not build True
.. versionadded:: 20.9
.. versionchanged:: 23.2 Raises :class:`InvalidWheelFilename` when the version component is invalid.
.. versionadded:: 26.1 The *validate_order* parameter.
.. versionchanged:: 26.3 Raises :class:`InvalidWheelFilename` when an interpreter component is not an identifier, a tag set component is empty, or the project name is empty. """ if not filename.endswith(".whl"): raise InvalidWheelFilename( f"Invalid wheel filename (extension must be '.whl'): {filename!r}" )
filename = filename[:-4] dashes = filename.count("-") if dashes not in (4, 5): raise InvalidWheelFilename( f"Invalid wheel filename (wrong number of parts): {filename!r}" )
parts = filename.split("-", dashes - 2) name_part = parts[0] # See PEP 427 for the rules on escaping the project name. if "__" in name_part or _wheel_name_regex.match(name_part) is None: raise InvalidWheelFilename(f"Invalid project name: {filename!r}") name = canonicalize_name(name_part)
try: version = Version(parts[1]) except InvalidVersion as e: raise InvalidWheelFilename( f"Invalid wheel filename (invalid version): {filename!r}" ) from e
if dashes == 5: build_part = parts[2] build_match = _build_tag_regex.match(build_part) if build_match is None: raise InvalidWheelFilename( f"Invalid build number: {build_part} in {filename!r}" ) build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2))) else: build = () tag_str = parts[-1] try: tags = parse_tag(tag_str, validate_order=validate_order) except UnsortedTagsError: raise InvalidWheelFilename( f"Invalid wheel filename (compressed tag set components must be in " f"sorted order per PEP 425): {filename!r}" ) from None except InvalidTag: raise InvalidWheelFilename( f"Invalid wheel filename (invalid tag component): {filename!r}" ) from None return (name, version, build, tags)
def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: """ This function takes the filename of a sdist file (as specified in the `Source distribution format`_ documentation), and parses it, returning a tuple of the normalized name and version as represented by an instance of :class:`~packaging.version.Version`.
:param str filename: The name of the sdist file. :raises InvalidSdistFilename: If the filename does not end with an sdist extension (``.zip`` or ``.tar.gz``), if it does not contain a dash separating the name and the version of the distribution, if the project name is empty, or if the version portion is not a valid version.
>>> from packaging.utils import parse_sdist_filename >>> from packaging.version import Version >>> name, ver = parse_sdist_filename("foo-1.0.tar.gz") >>> name 'foo' >>> ver == Version('1.0') True
.. versionadded:: 20.9
.. versionchanged:: 21.0 Added support for ``.zip`` source distributions.
.. versionchanged:: 23.2 Raises :class:`InvalidSdistFilename` when the version component is invalid.
.. versionchanged:: 26.3 Raises :class:`InvalidSdistFilename` on an empty project name.
.. _Source distribution format: https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-name """ if filename.endswith(".tar.gz"): file_stem = filename[: -len(".tar.gz")] elif filename.endswith(".zip"): file_stem = filename[: -len(".zip")] else: raise InvalidSdistFilename( f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" f" {filename!r}" )
# We are requiring a PEP 440 version, which cannot contain dashes, # so we split on the last dash. name_part, sep, version_part = file_stem.rpartition("-") if not sep: raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") if not name_part: raise InvalidSdistFilename( f"Invalid sdist filename (empty project name): {filename!r}" )
name = canonicalize_name(name_part)
try: version = Version(version_part) except InvalidVersion as e: raise InvalidSdistFilename( f"Invalid sdist filename (invalid version): {filename!r}" ) from e
return (name, version)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.""".. testsetup::
from packaging.version import parse, normalize_pre, Version, _cmpkey"""
from __future__ import annotations
import reimport sysimport typingfrom typing import ( Any, Callable, Literal, NamedTuple, SupportsInt, TypedDict, Union,)
if typing.TYPE_CHECKING: from typing_extensions import Self, Unpack
if sys.version_info >= (3, 13): # pragma: no cover from warnings import deprecated as _deprecatedelif typing.TYPE_CHECKING: from typing_extensions import deprecated as _deprecatedelse: # pragma: no cover import functools import warnings
def _deprecated(message: str) -> object: def decorator(func: Callable[[...], object]) -> object: @functools.wraps(func) def wrapper(*args: object, **kwargs: object) -> object: warnings.warn( message, category=DeprecationWarning, stacklevel=2, ) return func(*args, **kwargs)
return wrapper
return decorator
_LETTER_NORMALIZATION = { "alpha": "a", "beta": "b", "c": "rc", "pre": "rc", "preview": "rc", "rev": "post", "r": "post",}
__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "normalize_pre", "parse"]
def __dir__() -> list[str]: return __all__
LocalType = tuple[Union[int, str], ...]
CmpLocalType = tuple[tuple[int, str], ...]CmpSuffix = tuple[int, int, int, int, int, int]CmpKey = Union[ tuple[int, tuple[int, ...], CmpSuffix], tuple[int, tuple[int, ...], CmpSuffix, CmpLocalType],]VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]
class _VersionReplace(TypedDict, total=False): epoch: int | None release: tuple[int, ...] | None pre: tuple[str, int] | None post: int | None dev: int | None local: str | None
def normalize_pre(letter: str, /) -> str: """Normalize the pre-release segment of a version string.
Returns a lowercase version of the string if not a known pre-release identifier.
>>> normalize_pre('alpha') 'a' >>> normalize_pre('BETA') 'b' >>> normalize_pre('rc') 'rc'
:param letter:
.. versionadded:: 26.1 """ letter = letter.lower() return _LETTER_NORMALIZATION.get(letter, letter)
def parse(version: str) -> Version: """Parse the given version string.
This is identical to the :class:`Version` constructor.
>>> parse('1.0.dev1') <Version('1.0.dev1')>
:param version: The version string to parse. :raises InvalidVersion: When the version string is not a valid version. """ return Version(version)
class InvalidVersion(ValueError): """Raised when a version string is not a valid version.
>>> Version("invalid") Traceback (most recent call last): ... packaging.version.InvalidVersion: Invalid version: 'invalid' """
class _BaseVersion: __slots__ = ()
# This can also be a normal member (see the packaging_legacy package); # we are just requiring it to be readable. Actually defining a property # has runtime effect on subclasses, so it's typing only. if typing.TYPE_CHECKING:
@property def _key(self) -> tuple[Any, ...]: ...
def __hash__(self) -> int: return hash(self._key)
# Please keep the duplicated `isinstance` check # in the six comparisons hereunder # unless you find a way to avoid adding overhead function calls. def __lt__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key < other._key
def __le__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key <= other._key
def __eq__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key == other._key
def __ge__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key >= other._key
def __gt__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key > other._key
def __ne__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented
return self._key != other._key
# Deliberately not anchored to the start and end of the string, to make it# easier for 3rd party code to reuse
# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here_VERSION_PATTERN = r""" v?+ # optional leading v (?a: (?:(?P<epoch>[0-9]+)!)?+ # epoch (?P<release>[0-9]+(?:\.[0-9]+)*+) # release segment (?P<pre> # pre-release [._-]?+ (?P<pre_l>alpha|a|beta|b|preview|pre|c|rc) [._-]?+ (?P<pre_n>[0-9]+)? )?+ (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [._-]? (?P<post_l>post|rev|r) [._-]? (?P<post_n2>[0-9]+)? ) )?+ (?P<dev> # dev release [._-]?+ (?P<dev_l>dev) [._-]?+ (?P<dev_n>[0-9]+)? )?+ ) (?a:\+ (?P<local> # local version [a-z0-9]+ (?:[._-][a-z0-9]+)*+ ) )?+"""
_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
# Possessive qualifiers were added in Python 3.11.# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795# Older PyPy also had a bug.VERSION_PATTERN = ( _VERSION_PATTERN_OLD if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5)) or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13)) or sys.version_info < (3, 11) else _VERSION_PATTERN)"""A string containing the regular expression used to match a valid version.
The pattern is not anchored at either end, and is intended for embedding in largerexpressions (for example, matching a version number as part of a file name). Theregular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``flags set.
.. versionchanged:: 26.0
The regex now uses possessive qualifiers on Python 3.11 if they are supported (CPython 3.11.5+, PyPy 3.11.13+).
:meta hide-value:"""
# Validation pattern for local version in replace()_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE | re.ASCII)
# Fast path: If a version has only digits and dots then we# can skip the regex and parse it as a release segment_SIMPLE_VERSION_INDICATORS = frozenset(".0123456789")
def _validate_epoch(value: object, /) -> int: epoch = value or 0 if isinstance(epoch, int) and epoch >= 0: return epoch msg = f"epoch must be non-negative integer, got {epoch}" raise InvalidVersion(msg)
def _validate_release(value: object, /) -> tuple[int, ...]: release = (0,) if value is None else value if ( isinstance(release, tuple) and len(release) > 0 and all(isinstance(i, int) and i >= 0 for i in release) ): return release msg = f"release must be a non-empty tuple of non-negative integers, got {release}" raise InvalidVersion(msg)
def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None: if value is None: return value if isinstance(value, tuple) and len(value) == 2: letter, number = value # The letter must be a string before it can be normalized. if ( isinstance(letter, str) and (normalized := normalize_pre(letter)) in {"a", "b", "rc"} and isinstance(number, int) and number >= 0 ): # type checkers can't infer the Literal type here on letter return (normalized, number) # type: ignore[return-value] msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}" raise InvalidVersion(msg)
def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None: if value is None: return value if isinstance(value, int) and value >= 0: return ("post", value) msg = f"post must be non-negative integer, got {value}" raise InvalidVersion(msg)
def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None: if value is None: return value if isinstance(value, int) and value >= 0: return ("dev", value) msg = f"dev must be non-negative integer, got {value}" raise InvalidVersion(msg)
def _validate_local(value: object, /) -> LocalType | None: if value is None: return value if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value): return _parse_local_version(value) msg = f"local must be a valid version string, got {value!r}" raise InvalidVersion(msg)
# Backward compatibility for internals before 26.0. Do not use.class _Version(NamedTuple): epoch: int release: tuple[int, ...] dev: tuple[Literal["dev"], int] | None pre: tuple[Literal["a", "b", "rc"], int] | None post: tuple[Literal["post"], int] | None local: LocalType | None
class Version(_BaseVersion): """This class abstracts handling of a project's versions.
A :class:`Version` instance is comparison aware and can be compared and sorted using the standard Python interfaces.
>>> v1 = Version("1.0a5") >>> v2 = Version("1.0") >>> v1 <Version('1.0a5')> >>> v2 <Version('1.0')> >>> v1 < v2 True >>> v1 == v2 False >>> v1 > v2 False >>> v1 >= v2 False >>> v1 <= v2 True
:class:`Version` is immutable; use :meth:`__replace__` to change part of a version.
Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases.
.. versionchanged:: 26.2
Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """
__slots__ = ( "_dev", "_epoch", "_hash_cache", "_key_cache", "_local", "_post", "_pre", "_release", ) __match_args__ = ("_str",) """ Pattern matching is supported on Python 3.10+.
.. versionadded:: 26.0
:meta hide-value: """
_regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
_epoch: int _release: tuple[int, ...] _dev: tuple[Literal["dev"], int] | None _pre: tuple[Literal["a", "b", "rc"], int] | None _post: tuple[Literal["post"], int] | None _local: LocalType | None
_hash_cache: int | None _key_cache: CmpKey | None
def __init__(self, version: str) -> None: """Initialize a Version object.
:param version: The string representation of a version which will be parsed and normalized before use. :raises InvalidVersion: If the ``version`` does not conform to PEP 440 in any way then this exception will be raised. """ try: is_simple = _SIMPLE_VERSION_INDICATORS.issuperset(version) except TypeError: raise InvalidVersion(f"Invalid version: {version!r}") from None
if is_simple: try: self._release = tuple(map(int, version.split("."))) except AttributeError: raise InvalidVersion(f"Invalid version: {version!r}") from None except ValueError: # Empty parts (from "1..2", ".1", etc.) are invalid versions. # Any other ValueError (e.g. int str-digits limit) should # propagate to the caller. if "" in version.split("."): raise InvalidVersion(f"Invalid version: {version!r}") from None # TODO: remove "no cover" when Python 3.9 is dropped. raise # pragma: no cover
self._epoch = 0 self._pre = None self._post = None self._dev = None self._local = None self._key_cache = None self._hash_cache = None return
# Validate the version and parse it into pieces try: match = self._regex.fullmatch(version) except TypeError: raise InvalidVersion(f"Invalid version: {version!r}") from None if not match: raise InvalidVersion(f"Invalid version: {version!r}") self._epoch = int(match.group("epoch")) if match.group("epoch") else 0 self._release = tuple(map(int, match.group("release").split("."))) # We can type ignore the assignments below because the regex guarantees # the correct strings self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n")) # type: ignore[assignment] self._post = _parse_letter_version( # type: ignore[assignment] match.group("post_l"), match.group("post_n1") or match.group("post_n2") ) self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n")) # type: ignore[assignment] self._local = _parse_local_version(match.group("local"))
# Key which will be used for sorting self._key_cache = None self._hash_cache = None
@classmethod def from_parts( cls, *, epoch: int = 0, release: tuple[int, ...], pre: tuple[str, int] | None = None, post: int | None = None, dev: int | None = None, local: str | None = None, ) -> Self: """ Return a new version composed of the various parts.
This allows you to build a version without going though a string and running a regular expression. It normalizes pre-release strings. The ``release=`` keyword argument is required.
>>> Version.from_parts(release=(1,2,3)) <Version('1.2.3')> >>> Version.from_parts(release=(0,1,0), pre=("b", 1)) <Version('0.1.0b1')>
:param epoch: :param release: This version tuple is required
.. versionadded:: 26.1 """ _epoch = _validate_epoch(epoch) _release = _validate_release(release) _pre = _validate_pre(pre) if pre is not None else None _post = _validate_post(post) if post is not None else None _dev = _validate_dev(dev) if dev is not None else None _local = _validate_local(local) if local is not None else None
new_version = cls.__new__(cls) new_version._key_cache = None new_version._hash_cache = None new_version._epoch = _epoch new_version._release = _release new_version._pre = _pre new_version._post = _post new_version._dev = _dev new_version._local = _local
return new_version
def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self: """ __replace__(*, epoch=..., release=..., pre=..., post=..., dev=..., local=...)
Return a new version with parts replaced.
This returns a new version (unless no parts were changed). The pre-release is normalized. Setting a value to ``None`` clears it.
>>> v = Version("1.2.3") >>> v.__replace__(pre=("a", 1)) <Version('1.2.3a1')>
:param int | None epoch: :param tuple[int, ...] | None release: :param tuple[str, int] | None pre: :param int | None post: :param int | None dev: :param str | None local:
.. versionadded:: 26.0 .. versionchanged:: 26.1
The pre-release portion is now normalized. """ epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch release = ( _validate_release(kwargs["release"]) if "release" in kwargs else self._release ) pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
if ( epoch == self._epoch and release == self._release and pre == self._pre and post == self._post and dev == self._dev and local == self._local ): return self
new_version = self.__class__.__new__(self.__class__) new_version._key_cache = None new_version._hash_cache = None new_version._epoch = epoch new_version._release = release new_version._pre = pre new_version._post = post new_version._dev = dev new_version._local = local
return new_version
@property def _key(self) -> CmpKey: if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) return self._key_cache
# __hash__ must be defined when __eq__ is overridden, # otherwise Python sets __hash__ to None. def __hash__(self) -> int: if (cached_hash := self._hash_cache) is not None: return cached_hash
if (key := self._key_cache) is None: self._key_cache = key = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) self._hash_cache = cached_hash = hash(key) return cached_hash
# Override comparison methods to use direct _key_cache access # This is faster than property access, especially before Python 3.12 def __lt__(self, other: _BaseVersion) -> bool: if isinstance(other, Version): if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) if other._key_cache is None: other._key_cache = _cmpkey( other._epoch, other._release, other._pre, other._post, other._dev, other._local, ) return self._key_cache < other._key_cache
if not isinstance(other, _BaseVersion): return NotImplemented
return super().__lt__(other)
def __le__(self, other: _BaseVersion) -> bool: if isinstance(other, Version): if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) if other._key_cache is None: other._key_cache = _cmpkey( other._epoch, other._release, other._pre, other._post, other._dev, other._local, ) return self._key_cache <= other._key_cache
if not isinstance(other, _BaseVersion): return NotImplemented
return super().__le__(other)
def __eq__(self, other: object) -> bool: if isinstance(other, Version): if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) if other._key_cache is None: other._key_cache = _cmpkey( other._epoch, other._release, other._pre, other._post, other._dev, other._local, ) return self._key_cache == other._key_cache
if not isinstance(other, _BaseVersion): return NotImplemented
return super().__eq__(other)
def __ge__(self, other: _BaseVersion) -> bool: if isinstance(other, Version): if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) if other._key_cache is None: other._key_cache = _cmpkey( other._epoch, other._release, other._pre, other._post, other._dev, other._local, ) return self._key_cache >= other._key_cache
if not isinstance(other, _BaseVersion): return NotImplemented
return super().__ge__(other)
def __gt__(self, other: _BaseVersion) -> bool: if isinstance(other, Version): if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) if other._key_cache is None: other._key_cache = _cmpkey( other._epoch, other._release, other._pre, other._post, other._dev, other._local, ) return self._key_cache > other._key_cache
if not isinstance(other, _BaseVersion): return NotImplemented
return super().__gt__(other)
def __ne__(self, other: object) -> bool: if isinstance(other, Version): if self._key_cache is None: self._key_cache = _cmpkey( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) if other._key_cache is None: other._key_cache = _cmpkey( other._epoch, other._release, other._pre, other._post, other._dev, other._local, ) return self._key_cache != other._key_cache
if not isinstance(other, _BaseVersion): return NotImplemented
return super().__ne__(other)
def __getstate__( self, ) -> tuple[ int, tuple[int, ...], tuple[str, int] | None, tuple[str, int] | None, tuple[str, int] | None, LocalType | None, ]: # Return state as a 6-item tuple for compactness: # (epoch, release, pre, post, dev, local) # Cache members are excluded and will be recomputed on demand return ( self._epoch, self._release, self._pre, self._post, self._dev, self._local, )
def __setstate__(self, state: object) -> None: # Always discard cached values — they may contain stale references # (e.g. packaging._structures.InfinityType from pre-26.1 pickles) # and will be recomputed on demand from the core fields above. self._key_cache = None self._hash_cache = None
if isinstance(state, tuple): if len(state) == 6: # New format (26.2+): (epoch, release, pre, post, dev, local) ( self._epoch, self._release, self._pre, self._post, self._dev, self._local, ) = state return if len(state) == 2: # Format (packaging 26.0-26.1): (None, {slot: value}). _, slot_dict = state if isinstance(slot_dict, dict): self._epoch = slot_dict["_epoch"] self._release = slot_dict["_release"] self._pre = slot_dict.get("_pre") self._post = slot_dict.get("_post") self._dev = slot_dict.get("_dev") self._local = slot_dict.get("_local") return if isinstance(state, dict): # Old format (packaging <= 25.x, no __slots__): state is a plain # dict with "_version" (_Version NamedTuple) and "_key" entries. version_nt = state.get("_version") if version_nt is not None: self._epoch = version_nt.epoch self._release = version_nt.release self._pre = version_nt.pre self._post = version_nt.post self._dev = version_nt.dev self._local = version_nt.local return
raise TypeError(f"Cannot restore Version from {state!r}")
@property @_deprecated("Version._version is private and will be removed soon") def _version(self) -> _Version: return _Version( self._epoch, self._release, self._dev, self._pre, self._post, self._local )
@_version.setter @_deprecated("Version._version is private and will be removed soon") def _version(self, value: _Version) -> None: self._epoch = value.epoch self._release = value.release self._dev = value.dev self._pre = value.pre self._post = value.post self._local = value.local self._key_cache = None self._hash_cache = None
def __repr__(self) -> str: """A representation of the Version that shows all internal state.
>>> Version('1.0.0') <Version('1.0.0')> """ return f"<{self.__class__.__name__}({str(self)!r})>"
def __str__(self) -> str: """A string representation of the version that can be round-tripped.
>>> str(Version("1.0a5")) '1.0a5' """ # This is a hot function, so not calling self.base_version version = ".".join(map(str, self.release))
# Epoch if self.epoch: version = f"{self.epoch}!{version}"
# Pre-release if self.pre is not None: version += "".join(map(str, self.pre))
# Post-release if self.post is not None: version += f".post{self.post}"
# Development release if self.dev is not None: version += f".dev{self.dev}"
# Local version segment if self.local is not None: version += f"+{self.local}"
return version
@property def _str(self) -> str: """Internal property for match_args""" return str(self)
@property def epoch(self) -> int: """The epoch of the version.
>>> Version("2.0.0").epoch 0 >>> Version("1!2.0.0").epoch 1 """ return self._epoch
@property def release(self) -> tuple[int, ...]: """The components of the "release" segment of the version.
>>> Version("1.2.3").release (1, 2, 3) >>> Version("2.0.0").release (2, 0, 0) >>> Version("1!2.0.0.post0").release (2, 0, 0)
Includes trailing zeroes but not the epoch or any pre-release / development / post-release suffixes. """ return self._release
@property def pre(self) -> tuple[Literal["a", "b", "rc"], int] | None: """The pre-release segment of the version.
>>> print(Version("1.2.3").pre) None >>> Version("1.2.3a1").pre ('a', 1) >>> Version("1.2.3b1").pre ('b', 1) >>> Version("1.2.3rc1").pre ('rc', 1) """ return self._pre
@property def post(self) -> int | None: """The post-release number of the version.
>>> print(Version("1.2.3").post) None >>> Version("1.2.3.post1").post 1 """ return self._post[1] if self._post else None
@property def dev(self) -> int | None: """The development number of the version.
>>> print(Version("1.2.3").dev) None >>> Version("1.2.3.dev1").dev 1 """ return self._dev[1] if self._dev else None
@property def local(self) -> str | None: """The local version segment of the version.
>>> print(Version("1.2.3").local) None >>> Version("1.2.3+abc").local 'abc' """ if self._local: return ".".join(str(x) for x in self._local) else: return None
@property def public(self) -> str: """The public portion of the version.
This returns a string. If you want a :class:`Version` again and care about performance, use ``v.__replace__(local=None)`` instead.
>>> Version("1.2.3").public '1.2.3' >>> Version("1.2.3+abc").public '1.2.3' >>> Version("1!1.2.3dev1+abc").public '1!1.2.3.dev1' """ return str(self).split("+", 1)[0]
@property def base_version(self) -> str: """The "base version" of the version.
This returns a string. If you want a :class:`Version` again and care about performance, use ``v.__replace__(pre=None, post=None, dev=None, local=None)`` instead.
>>> Version("1.2.3").base_version '1.2.3' >>> Version("1.2.3+abc").base_version '1.2.3' >>> Version("1!1.2.3dev1+abc").base_version '1!1.2.3'
The "base version" is the public version of the project without any pre or post release markers. """ release_segment = ".".join(map(str, self.release)) return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
@property def is_prerelease(self) -> bool: """Whether this version is a pre-release.
>>> Version("1.2.3").is_prerelease False >>> Version("1.2.3a1").is_prerelease True >>> Version("1.2.3b1").is_prerelease True >>> Version("1.2.3rc1").is_prerelease True >>> Version("1.2.3dev1").is_prerelease True """ return self.dev is not None or self.pre is not None
@property def is_postrelease(self) -> bool: """Whether this version is a post-release.
>>> Version("1.2.3").is_postrelease False >>> Version("1.2.3.post1").is_postrelease True """ return self.post is not None
@property def is_devrelease(self) -> bool: """Whether this version is a development release.
>>> Version("1.2.3").is_devrelease False >>> Version("1.2.3.dev1").is_devrelease True """ return self.dev is not None
@property def major(self) -> int: """The first item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").major 1
.. versionadded:: 20.0 """ return self.release[0] if len(self.release) >= 1 else 0
@property def minor(self) -> int: """The second item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").minor 2 >>> Version("1").minor 0
.. versionadded:: 20.0 """ return self.release[1] if len(self.release) >= 2 else 0
@property def micro(self) -> int: """The third item of :attr:`release` or ``0`` if unavailable.
>>> Version("1.2.3").micro 3 >>> Version("1").micro 0
.. versionadded:: 20.0 """ return self.release[2] if len(self.release) >= 3 else 0
class _TrimmedRelease(Version): __slots__ = ()
def __init__(self, version: str | Version) -> None: if isinstance(version, Version): self._epoch = version._epoch self._release = version._release self._dev = version._dev self._pre = version._pre self._post = version._post self._local = version._local self._key_cache = version._key_cache self._hash_cache = version._hash_cache return super().__init__(version) # pragma: no cover
@property def release(self) -> tuple[int, ...]: """ Release segment without any trailing zeros.
>>> _TrimmedRelease('1.0.0').release (1,) >>> _TrimmedRelease('0.0').release (0,) """ # This leaves one 0. rel = super().release len_release = len(rel) i = len_release while i > 1 and rel[i - 1] == 0: i -= 1 return rel if i == len_release else rel[:i]
def _parse_letter_version( letter: str | None, number: str | bytes | SupportsInt | None) -> tuple[str, int] | None: if letter: # We normalize any letters to their lower case form letter = letter.lower()
# We consider some words to be alternate spellings of other words and # in those cases we want to normalize the spellings to our preferred # spelling. letter = _LETTER_NORMALIZATION.get(letter, letter)
# We consider there to be an implicit 0 in a pre-release if there is # not a numeral associated with it. return letter, int(number or 0)
if number: # We assume if we are given a number, but we are not given a letter # then this is using the implicit post release syntax (e.g. 1.0-1) return "post", int(number)
return None
_local_version_separators = re.compile(r"[\._-]")
def _parse_local_version(local: str | None) -> LocalType | None: """ Takes a string like ``"abc.1.twelve"`` and turns it into ``("abc", 1, "twelve")``. """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) ) return None
# Sort ranks for pre-release: dev-only < a < b < rc < stable (no pre-release)._PRE_RANK = {"a": 0, "b": 1, "rc": 2}_PRE_RANK_DEV_ONLY = -1 # sorts before a(0)_PRE_RANK_STABLE = 3 # sorts after rc(2)
# In local version segments, strings sort before ints per PEP 440._LOCAL_STR_RANK = -1 # sorts before all non-negative ints
# Pre-computed suffix for stable releases (no pre, post, or dev segments).# See _cmpkey() for the suffix layout._STABLE_SUFFIX = (_PRE_RANK_STABLE, 0, 0, 0, 1, 0)
def _cmpkey( epoch: int, release: tuple[int, ...], pre: tuple[str, int] | None, post: tuple[str, int] | None, dev: tuple[str, int] | None, local: LocalType | None,) -> CmpKey: """Build a comparison key for PEP 440 ordering.
Returns ``(epoch, release, suffix)`` or ``(epoch, release, suffix, local)`` so that plain tuple comparison gives the correct order.
Trailing zeros are stripped from the release so that ``1.0.0 == 1``.
The suffix is a flat 6-int tuple that encodes pre/post/dev: ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``
pre_rank: dev-only=-1, a=0, b=1, rc=2, no-pre=3 Dev-only releases (no pre or post) get -1 so they sort before any alpha/beta/rc. Releases without a pre-release tag get 3 so they sort after rc. post_rank: no-post=0, post=1 Releases without a post segment sort before those with one. dev_rank: dev=0, no-dev=1 Releases without a dev segment sort after those with one.
Local segments use ``(n, "")`` for ints and ``(-1, s)`` for strings, following PEP 440: strings sort before ints, strings compare lexicographically, ints compare numerically, and shorter segments sort before longer when prefixes match. Versions without a local segment sort before those with one (3-tuple < 4-tuple).
>>> _cmpkey(0, (1, 0, 0), None, None, None, None) (0, (1,), (3, 0, 0, 0, 1, 0)) >>> _cmpkey(0, (1,), ("a", 1), None, None, None) (0, (1,), (0, 1, 0, 0, 1, 0)) >>> _cmpkey(0, (1,), None, None, None, ("ubuntu", 1)) (0, (1,), (3, 0, 0, 0, 1, 0), ((-1, 'ubuntu'), (1, ''))) """ # Strip trailing zeros: 1.0.0 compares equal to 1. len_release = len(release) i = len_release while i and release[i - 1] == 0: i -= 1 trimmed = release if i == len_release else release[:i]
# Fast path: stable release with no local segment. if pre is None and post is None and dev is None and local is None: return epoch, trimmed, _STABLE_SUFFIX
if pre is None and post is None and dev is not None: # dev-only (e.g. 1.0.dev1) sorts before all pre-releases. pre_rank, pre_n = _PRE_RANK_DEV_ONLY, 0 elif pre is None: pre_rank, pre_n = _PRE_RANK_STABLE, 0 else: pre_rank, pre_n = _PRE_RANK[pre[0]], pre[1]
post_rank = 0 if post is None else 1 post_n = 0 if post is None else post[1]
dev_rank = 1 if dev is None else 0 dev_n = 0 if dev is None else dev[1]
suffix = (pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)
if local is None: return epoch, trimmed, suffix
cmp_local: CmpLocalType = tuple( (seg, "") if isinstance(seg, int) else (_LOCAL_STR_RANK, seg) for seg in local ) return epoch, trimmed, suffix, cmp_local12345678910111213from __future__ import annotations
__version__ = "26.1.1"
def main(args: list[str] | None = None) -> int: """This is an internal API only meant for use by pip's own console scripts.
For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)123456789101112131415161718192021222324import osimport sys
# Remove '' and current working directory from the first entry# of sys.path, if present to avoid using current directory# in pip commands check, freeze, install, list and show,# when invoked as python -m pip <command>if sys.path[0] in ("", os.getcwd()): sys.path.pop(0)
# If we are running from a wheel, add the wheel to sys.path# This allows the usage python pip-*.whl/pip install pip-*.whlif not __spec__ or __spec__.parent == "": # __file__ is pip-*.whl/pip/__main__.py # first dirname call strips of '/__main__.py', second strips off '/pip' # Resulting path is the name of the wheel itself # Add that to sys.path so we can import pip path = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, path)
if __name__ == "__main__": from pip._internal.cli.main import main as _main
sys.exit(_main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Execute exactly this copy of pip, within a different environment.
This file is named as it is, to ensure that this module can't be imported viaan import statement."""
# /!\ This version compatibility check section must be Python 2 compatible. /!\
import sys
# Copied from pyproject.tomlPYTHON_REQUIRES = (3, 10)
def version_str(version): # type: ignore return ".".join(str(v) for v in version)
if sys.version_info[:2] < PYTHON_REQUIRES: raise SystemExit( "This version of pip does not support python {} (requires >={}).".format( version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES) ) )
# From here on, we can use Python 3 features, but the syntax must remain# Python 2 compatible.
import runpy # noqa: E402from importlib.machinery import PathFinder # noqa: E402from os.path import dirname # noqa: E402
PIP_SOURCES_ROOT = dirname(dirname(__file__))
class PipImportRedirectingFinder: @classmethod def find_spec(self, fullname, path=None, target=None): # type: ignore if fullname != "pip": return None
spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) assert spec, (PIP_SOURCES_ROOT, fullname) return spec
sys.meta_path.insert(0, PipImportRedirectingFinder())
assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module"runpy.run_module("pip", run_name="__main__", alter_sys=True)123456789101112131415161718from __future__ import annotations
from pip._internal.utils import _log
# init_logging() must be called before any call to logging.getLogger()# which happens at import of most modules._log.init_logging()
def main(args: list[str] | None = None) -> int: """This is preserved for old console scripts that may still be referencing it.
For additional details, see https://github.com/pypa/pip/issues/7498. """ from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606"""Build Environment used for isolation during sdist building"""
from __future__ import annotations
import loggingimport osimport pathlibimport siteimport sysimport textwrapfrom collections import OrderedDictfrom collections.abc import Iterable, Sequencefrom contextlib import AbstractContextManager as ContextManagerfrom contextlib import nullcontextfrom io import StringIOfrom types import TracebackTypefrom typing import TYPE_CHECKING, Protocol, TypedDict
from pip._vendor.packaging.version import Version
from pip import __file__ as pip_locationfrom pip._internal.cli.spinners import open_rich_spinner, open_spinnerfrom pip._internal.exceptions import ( BuildDependencyInstallError, DiagnosticPipError, InstallWheelBuildError, PipError,)from pip._internal.locations import get_platlib, get_purelib, get_schemefrom pip._internal.metadata import get_default_environment, get_environmentfrom pip._internal.utils.deprecation import deprecatedfrom pip._internal.utils.logging import VERBOSE, capture_loggingfrom pip._internal.utils.packaging import get_requirementfrom pip._internal.utils.subprocess import call_subprocessfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
if TYPE_CHECKING: from pip._internal.cache import WheelCache from pip._internal.index.package_finder import PackageFinder from pip._internal.operations.build.build_tracker import BuildTracker from pip._internal.req.req_install import InstallRequirement from pip._internal.resolution.base import BaseResolver
class ExtraEnviron(TypedDict, total=False): extra_environ: dict[str, str]
logger = logging.getLogger(__name__)
def _dedup(a: str, b: str) -> tuple[str] | tuple[str, str]: return (a, b) if a != b else (a,)
class _Prefix: def __init__(self, path: str) -> None: self.path = path self.setup = False scheme = get_scheme("", prefix=path) self.bin_dir = scheme.scripts self.lib_dirs = _dedup(scheme.purelib, scheme.platlib)
def get_runnable_pip() -> str: """Get a file to pass to a Python executable, to run the currently-running pip.
This is used to run a pip subprocess, for installing requirements into the build environment. """ source = pathlib.Path(pip_location).resolve().parent
if not source.is_dir(): # This would happen if someone is using pip from inside a zip file. In that # case, we can use that directly. return str(source)
return os.fsdecode(source / "__pip-runner__.py")
def _get_system_sitepackages() -> set[str]: """Get system site packages
Usually from site.getsitepackages, but fallback on `get_purelib()/get_platlib()` if unavailable (e.g. in a virtualenv created by virtualenv<20)
Returns normalized set of strings. """ if hasattr(site, "getsitepackages"): system_sites = site.getsitepackages() else: # virtualenv < 20 overwrites site.py without getsitepackages # fallback on get_purelib/get_platlib. # this is known to miss things, but shouldn't in the cases # where getsitepackages() has been removed (inside a virtualenv) system_sites = [get_purelib(), get_platlib()] return {os.path.normcase(path) for path in system_sites}
class BuildEnvironmentInstaller(Protocol): """ Interface for installing build dependencies into an isolated build environment. """
def install( self, requirements: Iterable[str], prefix: _Prefix, *, kind: str, for_req: InstallRequirement | None, ) -> None: ...
class SubprocessBuildEnvironmentInstaller: """ Install build dependencies by calling pip in a subprocess. """
def __init__( self, finder: PackageFinder, build_constraints: list[str] | None = None, build_constraint_feature_enabled: bool = False, ) -> None: self.finder = finder self._build_constraints = build_constraints or [] self._build_constraint_feature_enabled = build_constraint_feature_enabled
def _deprecation_constraint_check(self) -> None: """ Check for deprecation warning: PIP_CONSTRAINT affecting build environments.
This warns when build-constraint feature is NOT enabled and PIP_CONSTRAINT is not empty. """ if self._build_constraint_feature_enabled or self._build_constraints: return
pip_constraint = os.environ.get("PIP_CONSTRAINT") if not pip_constraint or not pip_constraint.strip(): return
deprecated( reason=( "Setting PIP_CONSTRAINT will not affect " "build constraints in the future," ), replacement=( "to specify build constraints using --build-constraint or " "PIP_BUILD_CONSTRAINT. To disable this warning without " "any build constraints set --use-feature=build-constraint or " 'PIP_USE_FEATURE="build-constraint"' ), gone_in="26.2", issue=None, )
def install( self, requirements: Iterable[str], prefix: _Prefix, *, kind: str, for_req: InstallRequirement | None, ) -> None: self._deprecation_constraint_check()
finder = self.finder args: list[str] = [ sys.executable, get_runnable_pip(), "install", "--ignore-installed", "--no-user", "--prefix", prefix.path, "--no-warn-script-location", "--disable-pip-version-check", # As the build environment is ephemeral, it's wasteful to # pre-compile everything, especially as not every Python # module will be used/compiled in most cases. "--no-compile", # The prefix specified two lines above, thus # target from config file or env var should be ignored "--target", "", ] if logger.getEffectiveLevel() <= logging.DEBUG: args.append("-vv") elif logger.getEffectiveLevel() <= VERBOSE: args.append("-v") for format_control in ("no_binary", "only_binary"): formats = getattr(finder.format_control, format_control) args.extend( ( "--" + format_control.replace("_", "-"), ",".join(sorted(formats or {":none:"})), ) )
if finder.release_control is not None: # Use ordered args to preserve the user's original command-line order # This is important because later flags can override earlier ones for attr_name, value in finder.release_control.get_ordered_args(): args.extend(("--" + attr_name.replace("_", "-"), value))
index_urls = finder.index_urls if index_urls: args.extend(["-i", index_urls[0]]) for extra_index in index_urls[1:]: args.extend(["--extra-index-url", extra_index]) else: args.append("--no-index") for link in finder.find_links: args.extend(["--find-links", link])
if finder.proxy: args.extend(["--proxy", finder.proxy]) for host in finder.trusted_hosts: args.extend(["--trusted-host", host]) if finder.custom_cert: args.extend(["--cert", finder.custom_cert]) if finder.client_cert: args.extend(["--client-cert", finder.client_cert]) if finder.prefer_binary: args.append("--prefer-binary")
# Handle build constraints if self._build_constraint_feature_enabled: args.extend(["--use-feature", "build-constraint"])
if self._build_constraints: # Build constraints must be passed as both constraints # and build constraints, so that nested builds receive # build constraints for constraint_file in self._build_constraints: args.extend(["--constraint", constraint_file]) args.extend(["--build-constraint", constraint_file])
extra_environ: ExtraEnviron = {} if self._build_constraint_feature_enabled and not self._build_constraints: # If there are no build constraints but the build constraints # feature is enabled then we must ignore regular constraints # in the isolated build environment extra_environ = {"extra_environ": {"_PIP_IN_BUILD_IGNORE_CONSTRAINTS": "1"}}
if finder.uploaded_prior_to: args.extend(["--uploaded-prior-to", finder.uploaded_prior_to.isoformat()]) args.append("--") args.extend(requirements)
identify_requirement = ( f" for {for_req.name}" if for_req and for_req.name else "" ) with open_spinner(f"Installing {kind}") as spinner: call_subprocess( args, command_desc=f"installing {kind}{identify_requirement}", spinner=spinner, **extra_environ, )
class InprocessBuildEnvironmentInstaller: """ Build dependency installer that runs in the same pip process.
This contains a stripped down version of the install command with only the logic necessary for installing build dependencies. The finder, session, build tracker, and wheel cache are reused, but new instances of everything else are created as needed.
Options are inherited from the parent install command unless they don't make sense for build dependencies (in which case, they are hard-coded, see comments below). """
def __init__( self, *, finder: PackageFinder, build_tracker: BuildTracker, wheel_cache: WheelCache, build_constraints: Sequence[InstallRequirement] = (), verbosity: int = 0, ) -> None: from pip._internal.operations.prepare import RequirementPreparer
self._finder = finder self._build_constraints = build_constraints self._wheel_cache = wheel_cache self._level = 0
build_dir = TempDirectory(kind="build-env-install", globally_managed=True) self._preparer = RequirementPreparer( build_isolation_installer=self, # Inherited options or state. finder=finder, session=finder._link_collector.session, build_dir=build_dir.path, build_tracker=build_tracker, verbosity=verbosity, # This is irrelevant as it only applies to editable requirements. src_dir="", # Hard-coded options (that should NOT be inherited). download_dir=None, build_isolation=True, check_build_deps=False, progress_bar="off", # TODO: hash-checking should be extended to build deps, but that is # deferred for later as it'd be a breaking change. require_hashes=False, use_user_site=False, lazy_wheel=False, legacy_resolver=False, )
def install( self, requirements: Iterable[str], prefix: _Prefix, *, kind: str, for_req: InstallRequirement | None, ) -> None: """Install entrypoint. Manages output capturing and error handling.""" capture_logs = not logger.isEnabledFor(VERBOSE) and self._level == 0 if capture_logs: # Hide the logs from the installation of build dependencies. # They will be shown only if an error occurs. capture_ctx: ContextManager[StringIO] = capture_logging() spinner: ContextManager[None] = open_rich_spinner(f"Installing {kind}") else: # Otherwise, pass-through all logs (with a header). capture_ctx, spinner = nullcontext(StringIO()), nullcontext() logger.info("Installing %s ...", kind)
try: self._level += 1 with spinner, capture_ctx as stream: self._install_impl(requirements, prefix)
except DiagnosticPipError as exc: # Format similar to a nested subprocess error, where the # causing error is shown first, followed by the build error. logger.info(textwrap.dedent(stream.getvalue())) logger.error("%s", exc, extra={"rich": True}) logger.info("") raise BuildDependencyInstallError( for_req, requirements, cause=exc, log_lines=None )
except Exception as exc: logs: list[str] | None = textwrap.dedent(stream.getvalue()).splitlines() if not capture_logs: # If logs aren't being captured, then display the error inline # with the rest of the logs. logs = None if isinstance(exc, PipError): logger.error("%s", exc) else: logger.exception("pip crashed unexpectedly") raise BuildDependencyInstallError( for_req, requirements, cause=exc, log_lines=logs )
finally: self._level -= 1
def _install_impl(self, requirements: Iterable[str], prefix: _Prefix) -> None: """Core build dependency install logic.""" from pip._internal.commands.install import installed_packages_summary from pip._internal.req import install_given_reqs from pip._internal.req.constructors import install_req_from_line from pip._internal.wheel_builder import build
ireqs = [install_req_from_line(req, user_supplied=True) for req in requirements] ireqs.extend(self._build_constraints)
resolver = self._make_resolver() resolved_set = resolver.resolve(ireqs, check_supported_wheels=True) self._preparer.prepare_linked_requirements_more( resolved_set.requirements.values() )
reqs_to_build = [ r for r in resolved_set.requirements_to_install if not r.is_wheel ] _, build_failures = build(reqs_to_build, self._wheel_cache, verify=True) if build_failures: raise InstallWheelBuildError(build_failures)
installed = install_given_reqs( resolver.get_installation_order(resolved_set), prefix=prefix.path, # Hard-coded options (that should NOT be inherited). root=None, home=None, warn_script_location=False, use_user_site=False, # As the build environment is ephemeral, it's wasteful to # pre-compile everything since not all modules will be used. pycompile=False, progress_bar="off", )
env = get_environment(list(prefix.lib_dirs)) if summary := installed_packages_summary(installed, env): logger.info(summary)
def _make_resolver(self) -> BaseResolver: """Create a new resolver for one time use.""" # Legacy installer never used the legacy resolver so create a # resolvelib resolver directly. Yuck. from pip._internal.req.constructors import install_req_from_req_string from pip._internal.resolution.resolvelib.resolver import Resolver
return Resolver( make_install_req=install_req_from_req_string, # Inherited state. preparer=self._preparer, finder=self._finder, wheel_cache=self._wheel_cache, # Hard-coded options (that should NOT be inherited). ignore_requires_python=False, use_user_site=False, ignore_dependencies=False, ignore_installed=True, force_reinstall=False, upgrade_strategy="to-satisfy-only", py_version_info=None, )
class BuildEnvironment: """Creates and manages an isolated environment to install build deps"""
def __init__(self, installer: BuildEnvironmentInstaller) -> None: self.installer = installer temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
self._prefixes = OrderedDict( (name, _Prefix(os.path.join(temp_dir.path, name))) for name in ("normal", "overlay") )
self._bin_dirs: list[str] = [] self._lib_dirs: list[str] = [] for prefix in reversed(list(self._prefixes.values())): self._bin_dirs.append(prefix.bin_dir) self._lib_dirs.extend(prefix.lib_dirs)
# Customize site to: # - ensure .pth files are honored # - prevent access to system site packages system_sites = _get_system_sitepackages()
self._site_dir = os.path.join(temp_dir.path, "site") if not os.path.exists(self._site_dir): os.mkdir(self._site_dir) with open( os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8" ) as fp: fp.write( textwrap.dedent( """ import os, site, sys
# First, drop system-sites related paths. original_sys_path = sys.path[:] known_paths = set() for path in {system_sites!r}: site.addsitedir(path, known_paths=known_paths) system_paths = set( os.path.normcase(path) for path in sys.path[len(original_sys_path):] ) original_sys_path = [ path for path in original_sys_path if os.path.normcase(path) not in system_paths ] sys.path = original_sys_path
# Second, add lib directories. # ensuring .pth file are processed. for path in {lib_dirs!r}: assert not path in sys.path site.addsitedir(path) """ ).format(system_sites=system_sites, lib_dirs=self._lib_dirs) )
def __enter__(self) -> None: self._save_env = { name: os.environ.get(name, None) for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH") }
path = self._bin_dirs[:] old_path = self._save_env["PATH"] if old_path: path.extend(old_path.split(os.pathsep))
pythonpath = [self._site_dir]
os.environ.update( { "PATH": os.pathsep.join(path), "PYTHONNOUSERSITE": "1", "PYTHONPATH": os.pathsep.join(pythonpath), } )
def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: for varname, old_value in self._save_env.items(): if old_value is None: os.environ.pop(varname, None) else: os.environ[varname] = old_value
def check_requirements( self, reqs: Iterable[str] ) -> tuple[set[tuple[str, str]], set[str]]: """Return 2 sets: - conflicting requirements: set of (installed, wanted) reqs tuples - missing requirements: set of reqs """ missing = set() conflicting = set() if reqs: env = ( get_environment(self._lib_dirs) if hasattr(self, "_lib_dirs") else get_default_environment() ) for req_str in reqs: req = get_requirement(req_str) # We're explicitly evaluating with an empty extra value, since build # environments are not provided any mechanism to select specific extras. if req.marker is not None and not req.marker.evaluate({"extra": ""}): continue dist = env.get_distribution(req.name) if not dist: missing.add(req_str) continue if isinstance(dist.version, Version): installed_req_str = f"{req.name}=={dist.version}" else: installed_req_str = f"{req.name}==={dist.version}" if not req.specifier.contains(dist.version, prereleases=True): conflicting.add((installed_req_str, req_str)) # FIXME: Consider direct URL? return conflicting, missing
def install_requirements( self, requirements: Iterable[str], prefix_as_string: str, *, kind: str, for_req: InstallRequirement | None = None, ) -> None: prefix = self._prefixes[prefix_as_string] assert not prefix.setup prefix.setup = True if not requirements: return self.installer.install(requirements, prefix, kind=kind, for_req=for_req)
class NoOpBuildEnvironment(BuildEnvironment): """A no-op drop-in replacement for BuildEnvironment"""
def __init__(self) -> None: pass
def __enter__(self) -> None: pass
def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: pass
def cleanup(self) -> None: pass
def install_requirements( self, requirements: Iterable[str], prefix_as_string: str, *, kind: str, for_req: InstallRequirement | None = None, ) -> None: raise NotImplementedError()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291"""Cache Management"""
from __future__ import annotations
import hashlibimport jsonimport loggingimport osfrom pathlib import Pathfrom typing import Any
from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_versionfrom pip._vendor.packaging.utils import canonicalize_name
from pip._internal.exceptions import InvalidWheelFilenamefrom pip._internal.models.direct_url import DirectUrlfrom pip._internal.models.link import Linkfrom pip._internal.models.wheel import Wheelfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kindsfrom pip._internal.utils.urls import path_to_url
logger = logging.getLogger(__name__)
ORIGIN_JSON_NAME = "origin.json"
def _hash_dict(d: dict[str, str]) -> str: """Return a stable sha224 of a dictionary.""" s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True) return hashlib.sha224(s.encode("ascii")).hexdigest()
class Cache: """An abstract class - provides cache directories for data from links
:param cache_dir: The root of the cache. """
def __init__(self, cache_dir: str) -> None: super().__init__() assert not cache_dir or os.path.isabs(cache_dir) self.cache_dir = cache_dir or None
def _get_cache_path_parts(self, link: Link) -> list[str]: """Get parts of part that must be os.path.joined with cache_dir"""
# We want to generate an url to use as our cache key, we don't want to # just reuse the URL because it might have other items in the fragment # and we don't care about those. key_parts = {"url": link.url_without_fragment} if link.hash_name is not None and link.hash is not None: key_parts[link.hash_name] = link.hash if link.subdirectory_fragment: key_parts["subdirectory"] = link.subdirectory_fragment
# Include interpreter name, major and minor version in cache key # to cope with ill-behaved sdists that build a different wheel # depending on the python version their setup.py is being run on, # and don't encode the difference in compatibility tags. # https://github.com/pypa/pip/issues/7296 key_parts["interpreter_name"] = interpreter_name() key_parts["interpreter_version"] = interpreter_version()
# Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and # thus less secure). However the differences don't make a lot of # difference for our use case here. hashed = _hash_dict(key_parts)
# We want to nest the directories some to prevent having a ton of top # level directories where we might run out of sub directories on some # FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts
def _get_candidates(self, link: Link, canonical_package_name: str) -> list[Any]: can_not_cache = not self.cache_dir or not canonical_package_name or not link if can_not_cache: return []
path = self.get_path_for_link(link) if os.path.isdir(path): return [(candidate, path) for candidate in os.listdir(path)] return []
def get_path_for_link(self, link: Link) -> str: """Return a directory to store cached items in for link.""" raise NotImplementedError()
def get( self, link: Link, package_name: str | None, supported_tags: list[Tag], ) -> Link: """Returns a link to a cached item if it exists, otherwise returns the passed link. """ raise NotImplementedError()
class SimpleWheelCache(Cache): """A cache of wheels for future installs."""
def __init__(self, cache_dir: str) -> None: super().__init__(cache_dir)
def get_path_for_link(self, link: Link) -> str: """Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits.
We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels. """ parts = self._get_cache_path_parts(link) assert self.cache_dir # Store wheels within the root cache_dir return os.path.join(self.cache_dir, "wheels", *parts)
def get( self, link: Link, package_name: str | None, supported_tags: list[Tag], ) -> Link: candidates = []
if not package_name: return link
canonical_package_name = canonicalize_name(package_name) for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name): try: wheel = Wheel(wheel_name) except InvalidWheelFilename: continue if wheel.name != canonical_package_name: logger.debug( "Ignoring cached wheel %s for %s as it " "does not match the expected distribution name %s.", wheel_name, link, package_name, ) continue if not wheel.supported(supported_tags): # Built for a different python/arch/etc continue candidates.append( ( wheel.support_index_min(supported_tags), wheel_name, wheel_dir, ) )
if not candidates: return link
_, wheel_name, wheel_dir = min(candidates) return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
class EphemWheelCache(SimpleWheelCache): """A SimpleWheelCache that creates it's own temporary cache directory"""
def __init__(self) -> None: self._temp_dir = TempDirectory( kind=tempdir_kinds.EPHEM_WHEEL_CACHE, globally_managed=True, )
super().__init__(self._temp_dir.path)
class CacheEntry: def __init__( self, link: Link, persistent: bool, ): self.link = link self.persistent = persistent self.origin: DirectUrl | None = None origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME if origin_direct_url_path.exists(): try: self.origin = DirectUrl.from_json( origin_direct_url_path.read_text(encoding="utf-8") ) except Exception as e: logger.warning( "Ignoring invalid cache entry origin file %s for %s (%s)", origin_direct_url_path, link.filename, e, )
class WheelCache(Cache): """Wraps EphemWheelCache and SimpleWheelCache into a single Cache
This Cache allows for gracefully degradation, using the ephem wheel cache when a certain link is not found in the simple wheel cache first. """
def __init__(self, cache_dir: str) -> None: super().__init__(cache_dir) self._wheel_cache = SimpleWheelCache(cache_dir) self._ephem_cache = EphemWheelCache()
def get_path_for_link(self, link: Link) -> str: return self._wheel_cache.get_path_for_link(link)
def get_ephem_path_for_link(self, link: Link) -> str: return self._ephem_cache.get_path_for_link(link)
def get( self, link: Link, package_name: str | None, supported_tags: list[Tag], ) -> Link: cache_entry = self.get_cache_entry(link, package_name, supported_tags) if cache_entry is None: return link return cache_entry.link
def get_cache_entry( self, link: Link, package_name: str | None, supported_tags: list[Tag], ) -> CacheEntry | None: """Returns a CacheEntry with a link to a cached item if it exists or None. The cache entry indicates if the item was found in the persistent or ephemeral cache. """ retval = self._wheel_cache.get( link=link, package_name=package_name, supported_tags=supported_tags, ) if retval is not link: return CacheEntry(retval, persistent=True)
retval = self._ephem_cache.get( link=link, package_name=package_name, supported_tags=supported_tags, ) if retval is not link: return CacheEntry(retval, persistent=False)
return None
@staticmethod def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None: origin_path = Path(cache_dir) / ORIGIN_JSON_NAME if origin_path.exists(): try: origin = DirectUrl.from_json(origin_path.read_text(encoding="utf-8")) except Exception as e: logger.warning( "Could not read origin file %s in cache entry (%s). " "Will attempt to overwrite it.", origin_path, e, ) else: # TODO: use DirectUrl.equivalent when # https://github.com/pypa/pip/pull/10564 is merged. if origin.url != download_info.url: logger.warning( "Origin URL %s in cache entry %s does not match download URL " "%s. This is likely a pip bug or a cache corruption issue. " "Will overwrite it with the new value.", origin.url, cache_dir, download_info.url, ) origin_path.write_text(download_info.to_json(), encoding="utf-8")123"""Subpackage containing all of pip's command line interface related code"""
# This file intentionally does not import submodules123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""Logic that powers autocompletion installed by ``pip completion``."""
from __future__ import annotations
import optparseimport osimport sysfrom collections.abc import Iterablefrom itertools import chainfrom typing import Any
from pip._internal.cli.main_parser import create_main_parserfrom pip._internal.commands import commands_dict, create_commandfrom pip._internal.metadata import get_default_environment
def autocomplete() -> None: """Entry Point for completion of main and subcommand options.""" # Don't complete if user hasn't sourced bash_completion file. if "PIP_AUTO_COMPLETE" not in os.environ: return # Don't complete if autocompletion environment variables # are not present if not os.environ.get("COMP_WORDS") or not os.environ.get("COMP_CWORD"): return cwords = os.environ["COMP_WORDS"].split()[1:] cword = int(os.environ["COMP_CWORD"]) try: current = cwords[cword - 1] except IndexError: current = ""
parser = create_main_parser() subcommands = list(commands_dict) options = []
# subcommand subcommand_name: str | None = None for word in cwords: if word in subcommands: subcommand_name = word break # subcommand options if subcommand_name is not None: # special case: 'help' subcommand has no options if subcommand_name == "help": sys.exit(1) # special case: list locally installed dists for show and uninstall should_list_installed = not current.startswith("-") and subcommand_name in [ "show", "uninstall", ] if should_list_installed: env = get_default_environment() lc = current.lower() installed = [ dist.canonical_name for dist in env.iter_installed_distributions(local_only=True) if dist.canonical_name.startswith(lc) and dist.canonical_name not in cwords[1:] ] # if there are no dists installed, fall back to option completion if installed: for dist in installed: print(dist) sys.exit(1)
should_list_installables = ( not current.startswith("-") and subcommand_name == "install" ) if should_list_installables: for path in auto_complete_paths(current, "path"): print(path) sys.exit(1)
subcommand = create_command(subcommand_name)
for opt in subcommand.parser.option_list_all: if opt.help != optparse.SUPPRESS_HELP: options += [ (opt_str, opt.nargs) for opt_str in opt._long_opts + opt._short_opts ]
# filter out previously specified options from available options prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]] options = [(x, v) for (x, v) in options if x not in prev_opts] # filter options by current input options = [(k, v) for k, v in options if k.startswith(current)] # get completion type given cwords and available subcommand options completion_type = get_path_completion_type( cwords, cword, subcommand.parser.option_list_all, ) # get completion files and directories if ``completion_type`` is # ``<file>``, ``<dir>`` or ``<path>`` if completion_type: paths = auto_complete_paths(current, completion_type) options = [(path, 0) for path in paths] for option in options: opt_label = option[0] # append '=' to options which require args if option[1] and option[0][:2] == "--": opt_label += "=" print(opt_label)
# Complete sub-commands (unless one is already given). if not any(name in cwords for name in subcommand.handler_map()): for handler_name in subcommand.handler_map(): if handler_name.startswith(current): print(handler_name) else: # show main parser options only when necessary
opts = [i.option_list for i in parser.option_groups] opts.append(parser.option_list) flattened_opts = chain.from_iterable(opts) if current.startswith("-"): for opt in flattened_opts: if opt.help != optparse.SUPPRESS_HELP: subcommands += opt._long_opts + opt._short_opts else: # get completion type given cwords and all available options completion_type = get_path_completion_type(cwords, cword, flattened_opts) if completion_type: subcommands = list(auto_complete_paths(current, completion_type))
print(" ".join([x for x in subcommands if x.startswith(current)])) sys.exit(1)
def get_path_completion_type( cwords: list[str], cword: int, opts: Iterable[Any]) -> str | None: """Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS`` :param cword: same as the environmental variable ``COMP_CWORD`` :param opts: The available options to check :return: path completion type (``file``, ``dir``, ``path`` or None) """ if cword < 2 or not cwords[cword - 2].startswith("-"): return None for opt in opts: if opt.help == optparse.SUPPRESS_HELP: continue for o in str(opt).split("/"): if cwords[cword - 2].split("=")[0] == o: if not opt.metavar or any( x in ("path", "file", "dir") for x in opt.metavar.split("/") ): return opt.metavar return None
def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]: """If ``completion_type`` is ``file`` or ``path``, list all regular files and directories starting with ``current``; otherwise only list directories starting with ``current``.
:param current: The word to be completed :param completion_type: path completion type(``file``, ``path`` or ``dir``) :return: A generator of regular files and/or directories """ directory, filename = os.path.split(current) current_path = os.path.abspath(directory) # Don't complete paths if they can't be accessed if not os.access(current_path, os.R_OK): return filename = os.path.normcase(filename) # list all files that start with ``filename`` file_list = ( x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename) ) for f in file_list: opt = os.path.join(current_path, f) comp_file = os.path.normcase(os.path.join(directory, f)) # complete regular files when there is not ``<dir>`` after option # complete directories when there is ``<file>``, ``<path>`` or # ``<dir>``after option if completion_type != "dir" and os.path.isfile(opt): yield comp_file elif os.path.isdir(opt): yield os.path.join(comp_file, "")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264"""Base Command class, and related routines"""
from __future__ import annotations
import contextlibimport loggingimport logging.configimport optparseimport osimport sysimport tracebackfrom collections.abc import Iteratorfrom optparse import Valuesfrom typing import Callable
from pip._vendor.rich import reconfigurefrom pip._vendor.rich import traceback as rich_traceback
from pip._internal.cli import cmdoptionsfrom pip._internal.cli.command_context import CommandContextMixInfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatterfrom pip._internal.cli.status_codes import ( ERROR, PREVIOUS_BUILD_DIR_ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND,)from pip._internal.exceptions import ( BadCommand, CommandError, DiagnosticPipError, InstallationError, NetworkConnectionError, PreviousBuildDirError,)from pip._internal.utils.filesystem import check_path_ownerfrom pip._internal.utils.logging import BrokenStdoutLoggingError, setup_loggingfrom pip._internal.utils.misc import get_prog, normalize_pathfrom pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistryfrom pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registryfrom pip._internal.utils.virtualenv import running_under_virtualenv
__all__ = ["Command"]
logger = logging.getLogger(__name__)
class Command(CommandContextMixIn): usage: str = "" ignore_require_venv: bool = False
def __init__(self, name: str, summary: str, isolated: bool = False) -> None: super().__init__()
self.name = name self.summary = summary self.parser = ConfigOptionParser( usage=self.usage, prog=f"{get_prog()} {name}", formatter=UpdatingDefaultsHelpFormatter(), add_help_option=False, name=name, description=self.__doc__, isolated=isolated, )
self.tempdir_registry: TempDirRegistry | None = None
# Commands should add options to this option group optgroup_name = f"{self.name.capitalize()} Options" self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
# Add the general options gen_opts = cmdoptions.make_option_group( cmdoptions.general_group, self.parser, ) self.parser.add_option_group(gen_opts)
self.add_options()
def add_options(self) -> None: pass
@contextlib.contextmanager def pip_version_check(self, options: Values, args: list[str]) -> Iterator[None]: """ This is a no-op so that commands by default do not do the pip version check. """ # Make sure we do the pip version check if the index_group options # are present. assert not hasattr(options, "no_index") yield
def run(self, options: Values, args: list[str]) -> int: raise NotImplementedError
def _run_wrapper(self, level_number: int, options: Values, args: list[str]) -> int: def _inner_run() -> int: with self.pip_version_check(options, args): return self.run(options, args)
if options.debug_mode: rich_traceback.install(show_locals=True) return _inner_run()
try: status = _inner_run() assert isinstance(status, int) return status except DiagnosticPipError as exc: logger.error("%s", exc, extra={"rich": True}) logger.debug("Exception information:", exc_info=True)
return ERROR except PreviousBuildDirError as exc: logger.critical(str(exc)) logger.debug("Exception information:", exc_info=True)
return PREVIOUS_BUILD_DIR_ERROR except ( InstallationError, BadCommand, NetworkConnectionError, ) as exc: logger.critical(str(exc)) logger.debug("Exception information:", exc_info=True)
return ERROR except CommandError as exc: logger.critical("%s", exc) logger.debug("Exception information:", exc_info=True)
return ERROR except BrokenStdoutLoggingError: # stdout is broken; write to stderr directly. Use os.write, not # sys.stderr.write, so a full pipe buffer returns EPIPE instead # of deadlocking (Windows anonymous pipes are ~4KB). try: os.write(2, b"ERROR: Pipe to stdout was broken\n") if level_number <= logging.DEBUG: encoding = getattr(sys.stderr, "encoding", None) or "utf-8" os.write( 2, traceback.format_exc().encode(encoding, "backslashreplace") ) except OSError: pass
return ERROR except KeyboardInterrupt: logger.critical("Operation cancelled by user") logger.debug("Exception information:", exc_info=True)
return ERROR except BaseException: logger.critical("Exception:", exc_info=True)
return UNKNOWN_ERROR
def parse_args(self, args: list[str]) -> tuple[Values, list[str]]: # factored out for testability return self.parser.parse_args(args)
def main(self, args: list[str]) -> int: try: with self.main_context(): return self._main(args) finally: logging.shutdown()
def _main(self, args: list[str]) -> int: # We must initialize this before the tempdir manager, otherwise the # configuration would not be accessible by the time we clean up the # tempdir manager. self.tempdir_registry = self.enter_context(tempdir_registry()) # Intentionally set as early as possible so globally-managed temporary # directories are available to the rest of the code. self.enter_context(global_tempdir_manager())
options, args = self.parse_args(args)
# Set verbosity so that it can be used elsewhere. self.verbosity = options.verbose - options.quiet if options.debug_mode: self.verbosity = 2
if hasattr(options, "progress_bar") and options.progress_bar == "auto": options.progress_bar = "on" if self.verbosity >= 0 else "off"
reconfigure(no_color=options.no_color) level_number = setup_logging( verbosity=self.verbosity, no_color=options.no_color, user_log_file=options.log, )
always_enabled_features = set(options.features_enabled) & set( cmdoptions.ALWAYS_ENABLED_FEATURES ) if always_enabled_features: logger.warning( "The following features are always enabled: %s. ", ", ".join(sorted(always_enabled_features)), )
# Make sure that the --python argument isn't specified after the # subcommand. We can tell, because if --python was specified, # we should only reach this point if we're running in the created # subprocess, which has the _PIP_RUNNING_IN_SUBPROCESS environment # variable set. if options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ: logger.critical( "The --python option must be placed before the pip subcommand name" ) sys.exit(ERROR)
# TODO: Try to get these passing down from the command? # without resorting to os.environ to hold these. # This also affects isolated builds and it should.
if options.no_input: os.environ["PIP_NO_INPUT"] = "1"
if options.exists_action: os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
if options.require_venv and not self.ignore_require_venv: # If a venv is required check if it can really be found if not running_under_virtualenv(): logger.critical("Could not find an activated virtualenv (required).") sys.exit(VIRTUALENV_NOT_FOUND)
if options.cache_dir: options.cache_dir = normalize_path(options.cache_dir) if not check_path_owner(options.cache_dir): logger.warning( "The directory '%s' or its parent directory is not owned " "or is not writable by the current user. The cache " "has been disabled. Check the permissions and owner of " "that directory. If executing pip with sudo, you should " "use sudo's -H flag.", options.cache_dir, ) options.cache_dir = None
if ( "inprocess-build-deps" in options.features_enabled and os.environ.get("PIP_CONSTRAINT", "") and "build-constraint" not in options.features_enabled ): logger.warning( "In-process build dependencies are enabled, " "PIP_CONSTRAINT will have no effect for build dependencies" ) options.features_enabled.append("build-constraint")
return self._run_wrapper(level_number, options, args)
def handler_map(self) -> dict[str, Callable[[Values, list[str]], None]]: """ map of names to handler actions for commands with sub-actions """ return {}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298"""shared options and groups
The principle here is to define options once, but *not* instantiate themglobally. One reason being that options with action='append' can carry statebetween parses. pip parses general options twice internally, and shouldn'tpass on state. To be consistent, all options will follow this design."""
# The following comment should be removed at some point in the future.# mypy: strict-optional=Falsefrom __future__ import annotations
import loggingimport osimport pathlibimport reimport textwrapfrom datetime import datetime, timedelta, timezonefrom functools import partialfrom optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Valuesfrom textwrap import dedentfrom typing import Any, Callable
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.cli.parser import ConfigOptionParserfrom pip._internal.exceptions import CommandErrorfrom pip._internal.locations import USER_CACHE_DIR, get_src_prefixfrom pip._internal.models.format_control import FormatControlfrom pip._internal.models.index import PyPIfrom pip._internal.models.release_control import ReleaseControlfrom pip._internal.models.target_python import TargetPythonfrom pip._internal.utils import pylock as pylock_utilsfrom pip._internal.utils.datetime import parse_iso_datetimefrom pip._internal.utils.hashes import STRONG_HASHESfrom pip._internal.utils.misc import strtobool
logger = logging.getLogger(__name__)
def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None: """ Raise an option parsing error using parser.error().
Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. """ msg = f"{option} error: {msg}" msg = textwrap.fill(" ".join(msg.split())) parser.error(msg)
def make_option_group(group: dict[str, Any], parser: ConfigOptionParser) -> OptionGroup: """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group["name"]) for option in group["options"]: option_group.add_option(option()) return option_group
def check_dist_restriction(options: Values, check_target: bool = False) -> None: """Function for determining if custom platform options are allowed.
:param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. """ dist_restriction_set = any( [ options.python_version, options.platforms, options.abis, options.implementation, ] )
binary_only = FormatControl(set(), {":all:"}) sdist_dependencies_allowed = ( options.format_control != binary_only and not options.ignore_dependencies )
# Installations or downloads using dist restrictions must not combine # source distributions and dist-specific wheels, as they are not # guaranteed to be locally compatible. if dist_restriction_set and sdist_dependencies_allowed: raise CommandError( "When restricting platform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " "either --no-deps must be set, or --only-binary=:all: must be " "set and --no-binary must not be set (or must be set to " ":none:)." )
if check_target: if not options.dry_run and dist_restriction_set and not options.target_dir: raise CommandError( "Can not use any platform or abi specific options unless " "installing via '--target' or using '--dry-run'" )
for filename in options.requirements: if dist_restriction_set and pylock_utils.is_valid_pylock_filename(filename): raise CommandError( "Patform and interpreter constraints using " "--python-version, --platform, --abi, or --implementation, " f"are not supported when selecting requirements from {filename!r}" )
def check_build_constraints(options: Values) -> None: """Function for validating build constraints options.
:param options: The OptionParser options. """ if hasattr(options, "build_constraints") and options.build_constraints: if not options.build_isolation: raise CommandError( "--build-constraint cannot be used with --no-build-isolation." )
# Import here to avoid circular imports from pip._internal.network.session import PipSession from pip._internal.req.req_file import get_file_content
# Eagerly check build constraints file contents # is valid so that we don't fail in when trying # to check constraints in isolated build process with PipSession() as session: for constraint_file in options.build_constraints: get_file_content(constraint_file, session)
def _path_option_check(option: Option, opt: str, value: str) -> str: return os.path.expanduser(value)
def _package_name_option_check(option: Option, opt: str, value: str) -> str: return canonicalize_name(value)
class PipOption(Option): TYPES = Option.TYPES + ("path", "package_name") TYPE_CHECKER = Option.TYPE_CHECKER.copy() TYPE_CHECKER["package_name"] = _package_name_option_check TYPE_CHECKER["path"] = _path_option_check
############ options ############
help_: Callable[..., Option] = partial( Option, "-h", "--help", dest="help", action="help", help="Show help.",)
debug_mode: Callable[..., Option] = partial( Option, "--debug", dest="debug_mode", action="store_true", default=False, help=( "Let unhandled exceptions propagate outside the main subroutine, " "instead of logging them to stderr." ),)
isolated_mode: Callable[..., Option] = partial( Option, "--isolated", dest="isolated_mode", action="store_true", default=False, help=( "Run pip in an isolated mode, ignoring environment variables and user " "configuration." ),)
require_virtualenv: Callable[..., Option] = partial( Option, "--require-virtualenv", "--require-venv", dest="require_venv", action="store_true", default=False, help=( "Allow pip to only run in a virtual environment; exit with an error otherwise." ),)
override_externally_managed: Callable[..., Option] = partial( Option, "--break-system-packages", dest="override_externally_managed", action="store_true", help="Allow pip to modify an EXTERNALLY-MANAGED Python installation",)
python: Callable[..., Option] = partial( Option, "--python", dest="python", help="Run pip with the specified Python interpreter.",)
verbose: Callable[..., Option] = partial( Option, "-v", "--verbose", dest="verbose", action="count", default=0, help="Give more output. Option is additive, and can be used up to 3 times.",)
no_color: Callable[..., Option] = partial( Option, "--no-color", dest="no_color", action="store_true", default=False, help="Suppress colored output.",)
version: Callable[..., Option] = partial( Option, "-V", "--version", dest="version", action="store_true", help="Show version and exit.",)
quiet: Callable[..., Option] = partial( Option, "-q", "--quiet", dest="quiet", action="count", default=0, help=( "Give less output. Option is additive, and can be used up to 3" " times (corresponding to WARNING, ERROR, and CRITICAL logging" " levels)." ),)
progress_bar: Callable[..., Option] = partial( Option, "--progress-bar", dest="progress_bar", type="choice", choices=["auto", "on", "off", "raw"], default="auto", help=( "Specify whether the progress bar should be used. In 'auto'" " mode, --quiet will suppress all progress bars." " [auto, on, off, raw] (default: auto)" ),)
log: Callable[..., Option] = partial( PipOption, "--log", "--log-file", "--local-log", dest="log", metavar="path", type="path", help="Path to a verbose appending log.",)
no_input: Callable[..., Option] = partial( Option, # Don't ask for input "--no-input", dest="no_input", action="store_true", default=False, help="Disable prompting for input.",)
keyring_provider: Callable[..., Option] = partial( Option, "--keyring-provider", dest="keyring_provider", choices=["auto", "disabled", "import", "subprocess"], default="auto", help=( "Enable the credential lookup via the keyring library if user input is allowed." " Specify which mechanism to use [auto, disabled, import, subprocess]." " (default: %default)" ),)
proxy: Callable[..., Option] = partial( Option, "--proxy", dest="proxy", type="str", default="", help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.",)
retries: Callable[..., Option] = partial( Option, "--retries", dest="retries", type="int", default=5, help="Maximum attempts to establish a new HTTP connection. (default: %default)",)
resume_retries: Callable[..., Option] = partial( Option, "--resume-retries", dest="resume_retries", type="int", default=5, help="Maximum attempts to resume or restart an incomplete download. " "(default: %default)",)
timeout: Callable[..., Option] = partial( Option, "--timeout", "--default-timeout", metavar="sec", dest="timeout", type="float", default=15, help="Set the socket timeout (default %default seconds).",)
def exists_action() -> Option: return Option( # Option when path already exist "--exists-action", dest="exists_action", type="choice", choices=["s", "i", "w", "b", "a"], default=[], action="append", metavar="action", help="Default action when a path already exists: " "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.", )
cert: Callable[..., Option] = partial( PipOption, "--cert", dest="cert", type="path", metavar="path", help=( "Path to PEM-encoded CA certificate bundle. " "If provided, overrides the default. " "See 'SSL Certificate Verification' in pip documentation " "for more information." ),)
client_cert: Callable[..., Option] = partial( PipOption, "--client-cert", dest="client_cert", type="path", default=None, metavar="path", help="Path to SSL client certificate, a single file containing the " "private key and the certificate in PEM format.",)
index_url: Callable[..., Option] = partial( Option, "-i", "--index-url", "--pypi-url", dest="index_url", metavar="URL", default=PyPI.simple_url, help="Base URL of the Python Package Index (default %default). " "This should point to a repository compliant with PEP 503 " "(the simple repository API) or a local directory laid out " "in the same format.",)
def extra_index_url() -> Option: return Option( "--extra-index-url", dest="extra_index_urls", metavar="URL", action="append", default=[], help="Extra URLs of package indexes to use in addition to " "--index-url. Should follow the same rules as " "--index-url.", )
no_index: Callable[..., Option] = partial( Option, "--no-index", dest="no_index", action="store_true", default=False, help="Ignore package index (only looking at --find-links URLs instead).",)
def find_links() -> Option: return Option( "-f", "--find-links", dest="find_links", action="append", default=[], metavar="url", help="If a URL or path to an html file, then parse for links to " "archives such as sdist (.tar.gz) or wheel (.whl) files. " "If a local path or file:// URL that's a directory, " "then look for archives in the directory listing. " "Links to VCS project URLs are not supported.", )
def _handle_uploaded_prior_to( option: Option, opt: str, value: str, parser: OptionParser) -> None: """ This is an optparse.Option callback for the --uploaded-prior-to option.
Accepts either an ISO 8601 datetime string (e.g., '2023-01-01T00:00:00Z') or a strict subset of ISO 8601 durations: PnD where n is a number of days (e.g., 'P7D' for 7 days ago).
Note: This option only works with indexes that provide upload-time metadata as specified in the simple repository API: https://packaging.python.org/en/latest/specifications/simple-repository-api/ """ if value is None: return None
# Try ISO 8601 duration in PnD format. The leading 'P' disambiguates # from absolute datetimes. Only whole days are supported; the format may # be extended to more of the ISO 8601 duration syntax in the future if # a real need is presented. match = re.match(r"^P(\d+)D$", value, re.ASCII) if match: days = int(match.group(1)) parser.values.uploaded_prior_to = datetime.now(timezone.utc) - timedelta( days=days ) return
try: uploaded_prior_to = parse_iso_datetime(value) # Use local timezone if no offset is given in the ISO string. if uploaded_prior_to.tzinfo is None: uploaded_prior_to = uploaded_prior_to.astimezone() parser.values.uploaded_prior_to = uploaded_prior_to except ValueError as exc: msg = ( f"invalid value: {value!r}: {exc}. " f"Expected an ISO 8601 datetime string " f"(e.g., '2023-01-01' or '2023-01-01T00:00:00Z') " f"or a duration in days (e.g., 'P3D')" ) raise_option_error(parser, option=option, msg=msg)
def uploaded_prior_to() -> Option: return Option( "--uploaded-prior-to", dest="uploaded_prior_to", metavar="datetime_or_duration", action="callback", callback=_handle_uploaded_prior_to, type="str", help=( "Only consider packages uploaded prior to the given value. " "Accepts an ISO 8601 datetime (e.g., '2023-01-01T00:00:00Z', " "uses local timezone if none specified) or a duration in days " "(e.g., 'P3D' for packages uploaded at least 3 days ago). " "Only effective when installing from indexes that provide " "upload-time metadata." ), )
def trusted_host() -> Option: return Option( "--trusted-host", dest="trusted_hosts", action="append", metavar="HOSTNAME", default=[], help="Mark this host or host:port pair as trusted, even though it " "does not have valid or any HTTPS.", )
def constraints() -> Option: return Option( "-c", "--constraint", dest="constraints", action="append", default=[], metavar="file", help="Constrain versions using the given constraints file. " "This option can be used multiple times.", )
def build_constraints() -> Option: return Option( "--build-constraint", dest="build_constraints", action="append", type="str", default=[], metavar="file", help=( "Constrain build dependencies using the given constraints file. " "This option can be used multiple times." ), )
def requirements() -> Option: return Option( "-r", "--requirement", dest="requirements", action="append", default=[], metavar="file", help=( "Install from the given requirements file. " "The file or URL can be in pip's requirements.txt format, " "or pylock.toml format. pylock.toml support is experimental. " "This option can be used multiple times." ), )
def requirements_from_scripts() -> Option: return Option( "--requirements-from-script", action="append", default=[], dest="requirements_from_scripts", metavar="file", help="Install dependencies of the given script file" "as defined by PEP 723 inline metadata. ", )
def editable() -> Option: return Option( "-e", "--editable", dest="editables", action="append", default=[], metavar="path/url", help=( "Install a project in editable mode (i.e. setuptools " '"develop mode") from a local project path or a VCS url.' ), )
def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None: value = os.path.abspath(value) setattr(parser.values, option.dest, value)
src: Callable[..., Option] = partial( PipOption, "--src", "--source", "--source-dir", "--source-directory", dest="src_dir", type="path", metavar="dir", default=get_src_prefix(), action="callback", callback=_handle_src, help="Directory to check out editable projects into. " 'The default in a virtualenv is "<venv path>/src". ' 'The default for global installs is "<current dir>/src".',)
def _get_format_control(values: Values, option: Option) -> Any: """Get a format_control object.""" return getattr(values, option.dest)
def _handle_no_binary( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: existing = _get_format_control(parser.values, option) FormatControl.handle_mutual_excludes( value, existing.no_binary, existing.only_binary, )
def _handle_only_binary( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: existing = _get_format_control(parser.values, option) FormatControl.handle_mutual_excludes( value, existing.only_binary, existing.no_binary, )
def no_binary() -> Option: format_control = FormatControl(set(), set()) return Option( "--no-binary", dest="format_control", action="callback", callback=_handle_no_binary, type="str", default=format_control, help="Do not use binary packages. Can be supplied multiple times, and " 'each time adds to the existing value. Accepts either ":all:" to ' 'disable all binary packages, ":none:" to empty the set (notice ' "the colons), or one or more package names with commas between " "them (no colons). Note that some packages are tricky to compile " "and may fail to install when this option is used on them.", )
def only_binary() -> Option: format_control = FormatControl(set(), set()) return Option( "--only-binary", dest="format_control", action="callback", callback=_handle_only_binary, type="str", default=format_control, help="Do not use source packages. Can be supplied multiple times, and " 'each time adds to the existing value. Accepts either ":all:" to ' 'disable all source packages, ":none:" to empty the set, or one ' "or more package names with commas between them. Packages " "without binary distributions will fail to install when this " "option is used on them.", )
def _get_release_control(values: Values, option: Option) -> Any: """Get a release_control object.""" return getattr(values, option.dest)
def _handle_all_releases( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: existing = _get_release_control(parser.values, option) existing.handle_mutual_excludes( value, existing.all_releases, existing.only_final, "all_releases", )
def _handle_only_final( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: existing = _get_release_control(parser.values, option) existing.handle_mutual_excludes( value, existing.only_final, existing.all_releases, "only_final", )
def all_releases() -> Option: release_control = ReleaseControl(set(), set()) return Option( "--all-releases", dest="release_control", action="callback", callback=_handle_all_releases, type="str", default=release_control, help="Allow all release types (including pre-releases) for a package. " "Can be supplied multiple times, and each time adds to the existing " 'value. Accepts either ":all:" to allow pre-releases for all ' 'packages, ":none:" to empty the set (notice the colons), or one or ' "more package names with commas between them (no colons). Cannot be " "used with --pre.", )
def only_final() -> Option: release_control = ReleaseControl(set(), set()) return Option( "--only-final", dest="release_control", action="callback", callback=_handle_only_final, type="str", default=release_control, help="Only allow final releases (no pre-releases) for a package. Can be " "supplied multiple times, and each time adds to the existing value. " 'Accepts either ":all:" to disable pre-releases for all packages, ' '":none:" to empty the set, or one or more package names with commas ' "between them. Cannot be used with --pre.", )
def check_release_control_exclusive(options: Values) -> None: """ Raise an error if --pre is used with --all-releases or --only-final, and transform --pre into --all-releases :all: if used alone. """ if not hasattr(options, "pre") or not options.pre: return
release_control = options.release_control if release_control.all_releases or release_control.only_final: raise CommandError("--pre cannot be used with --all-releases or --only-final.")
# Transform --pre into --all-releases :all: release_control.all_releases.add(":all:")
platforms: Callable[..., Option] = partial( Option, "--platform", dest="platforms", metavar="platform", action="append", default=None, help=( "Only use wheels compatible with <platform>. Defaults to the " "platform of the running system. Use this option multiple times to " "specify multiple platforms supported by the target interpreter." ),)
# This was made a separate function for unit-testing purposes.def _convert_python_version(value: str) -> tuple[tuple[int, ...], str | None]: """ Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
:return: A 2-tuple (version_info, error_msg), where `error_msg` is non-None if and only if there was a parsing error. """ if not value: # The empty string is the same as not providing a value. return (None, None)
parts = value.split(".") if len(parts) > 3: return ((), "at most three version parts are allowed")
if len(parts) == 1: # Then we are in the case of "3" or "37". value = parts[0] if len(value) > 1: parts = [value[0], value[1:]]
try: version_info = tuple(int(part) for part in parts) except ValueError: return ((), "each version part must be an integer")
return (version_info, None)
def _handle_python_version( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: """ Handle a provided --python-version value. """ version_info, error_msg = _convert_python_version(value) if error_msg is not None: msg = f"invalid --python-version value: {value!r}: {error_msg}" raise_option_error(parser, option=option, msg=msg)
parser.values.python_version = version_info
python_version: Callable[..., Option] = partial( Option, "--python-version", dest="python_version", metavar="python_version", action="callback", callback=_handle_python_version, type="str", default=None, help=dedent( """\ The Python interpreter version to use for wheel and "Requires-Python" compatibility checks. Defaults to a version derived from the running interpreter. The version can be specified using up to three dot-separated integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor version can also be given as a string without dots (e.g. "37" for 3.7.0). """ ),)
implementation: Callable[..., Option] = partial( Option, "--implementation", dest="implementation", metavar="implementation", default=None, help=( "Only use wheels compatible with Python " "implementation <implementation>, e.g. 'pp', 'jy', 'cp', " " or 'ip'. If not specified, then the current " "interpreter implementation is used. Use 'py' to force " "implementation-agnostic wheels." ),)
abis: Callable[..., Option] = partial( Option, "--abi", dest="abis", metavar="abi", action="append", default=None, help=( "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. " "If not specified, then the current interpreter abi tag is used. " "Use this option multiple times to specify multiple abis supported " "by the target interpreter. Generally you will need to specify " "--implementation, --platform, and --python-version when using this " "option." ),)
def add_target_python_options(cmd_opts: OptionGroup) -> None: cmd_opts.add_option(platforms()) cmd_opts.add_option(python_version()) cmd_opts.add_option(implementation()) cmd_opts.add_option(abis())
def make_target_python(options: Values) -> TargetPython: target_python = TargetPython( platforms=options.platforms, py_version_info=options.python_version, abis=options.abis, implementation=options.implementation, )
return target_python
def prefer_binary() -> Option: return Option( "--prefer-binary", dest="prefer_binary", action="store_true", default=False, help=( "Prefer binary packages over source packages, even if the " "source packages are newer." ), )
cache_dir: Callable[..., Option] = partial( PipOption, "--cache-dir", dest="cache_dir", default=USER_CACHE_DIR, metavar="dir", type="path", help="Store the cache data in <dir>.",)
def _handle_no_cache_dir( option: Option, opt: str, value: str, parser: OptionParser) -> None: """ Process a value provided for the --no-cache-dir option.
This is an optparse.Option callback for the --no-cache-dir option. """ # The value argument will be None if --no-cache-dir is passed via the # command-line, since the option doesn't accept arguments. However, # the value can be non-None if the option is triggered e.g. by an # environment variable, like PIP_NO_CACHE_DIR=true. if value is not None: # Then parse the string value to get argument error-checking. try: strtobool(value) except ValueError as exc: raise_option_error(parser, option=option, msg=str(exc))
# Originally, setting PIP_NO_CACHE_DIR to a value that strtobool() # converted to 0 (like "false" or "no") caused cache_dir to be disabled # rather than enabled (logic would say the latter). Thus, we disable # the cache directory not just on values that parse to True, but (for # backwards compatibility reasons) also on values that parse to False. # In other words, always set it to False if the option is provided in # some (valid) form. parser.values.cache_dir = False
no_cache: Callable[..., Option] = partial( Option, "--no-cache-dir", dest="cache_dir", action="callback", callback=_handle_no_cache_dir, help="Disable the cache.",)
no_deps: Callable[..., Option] = partial( Option, "--no-deps", "--no-dependencies", dest="ignore_dependencies", action="store_true", default=False, help="Don't install package dependencies.",)
def _handle_dependency_group( option: Option, opt: str, value: str, parser: OptionParser) -> None: """ Process a value provided for the --group option.
Splits on the rightmost ":", and validates that the path (if present) ends in `pyproject.toml`. Defaults the path to `pyproject.toml` when one is not given.
`:` cannot appear in dependency group names, so this is a safe and simple parse.
This is an optparse.Option callback for the dependency_groups option. """ path, sep, groupname = value.rpartition(":") if not sep: path = "pyproject.toml" else: # check for 'pyproject.toml' filenames using pathlib if pathlib.PurePath(path).name != "pyproject.toml": msg = "group paths use 'pyproject.toml' filenames" raise_option_error(parser, option=option, msg=msg)
parser.values.dependency_groups.append((path, groupname))
dependency_groups: Callable[..., Option] = partial( Option, "--group", dest="dependency_groups", default=[], type=str, action="callback", callback=_handle_dependency_group, metavar="[path:]group", help='Install a named dependency-group from a "pyproject.toml" file. ' 'If a path is given, the name of the file must be "pyproject.toml". ' 'Defaults to using "pyproject.toml" in the current directory.',)
ignore_requires_python: Callable[..., Option] = partial( Option, "--ignore-requires-python", dest="ignore_requires_python", action="store_true", help="Ignore the Requires-Python information.",)
no_build_isolation: Callable[..., Option] = partial( Option, "--no-build-isolation", dest="build_isolation", action="store_false", default=True, help="Disable isolation when building a modern source distribution. " "Build dependencies specified by PEP 518 must be already installed " "if this option is used.",)
check_build_deps: Callable[..., Option] = partial( Option, "--check-build-dependencies", dest="check_build_deps", action="store_true", default=False, help="Check the build dependencies.",)
use_pep517: Any = partial( Option, "--use-pep517", dest="use_pep517", action="store_true", default=True, help=SUPPRESS_HELP,)
def _handle_config_settings( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: key, sep, val = value.partition("=") if sep != "=": parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL") dest = getattr(parser.values, option.dest) if dest is None: dest = {} setattr(parser.values, option.dest, dest) if key in dest: if isinstance(dest[key], list): dest[key].append(val) else: dest[key] = [dest[key], val] else: dest[key] = val
config_settings: Callable[..., Option] = partial( Option, "-C", "--config-settings", dest="config_settings", type=str, action="callback", callback=_handle_config_settings, metavar="settings", help="Configuration settings to be passed to the build backend. " "Settings take the form KEY=VALUE. Use multiple --config-settings options " "to pass multiple keys to the backend.",)
no_clean: Callable[..., Option] = partial( Option, "--no-clean", action="store_true", default=False, help="Don't clean up build directories.",)
pre: Callable[..., Option] = partial( Option, "--pre", action="store_true", default=False, help="Include pre-release and development versions. By default, " "pip only finds stable versions.",)
json: Callable[..., Option] = partial( Option, "--json", action="store_true", default=False, help="Output data in a machine-readable JSON format.",)
disable_pip_version_check: Callable[..., Option] = partial( Option, "--disable-pip-version-check", dest="disable_pip_version_check", action="store_true", default=False, help="Don't periodically check PyPI to determine whether a new version " "of pip is available for download. Implied with --no-index.",)
root_user_action: Callable[..., Option] = partial( Option, "--root-user-action", dest="root_user_action", default="warn", choices=["warn", "ignore"], help="Action if pip is run as a root user [warn, ignore] (default: warn)",)
def _handle_merge_hash( option: Option, opt_str: str, value: str, parser: OptionParser) -> None: """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} try: algo, digest = value.split(":", 1) except ValueError: parser.error( f"Arguments to {opt_str} must be a hash name " "followed by a value, like --hash=sha256:" "abcde..." ) if algo not in STRONG_HASHES: parser.error( "Allowed hash algorithms for {} are {}.".format( opt_str, ", ".join(STRONG_HASHES) ) ) parser.values.hashes.setdefault(algo, []).append(digest)
hash: Callable[..., Option] = partial( Option, "--hash", # Hash values eventually end up in InstallRequirement.hashes due to # __dict__ copying in process_line(). dest="hashes", action="callback", callback=_handle_merge_hash, type="string", help="Verify that the package's archive matches this " "hash before installing. Example: --hash=sha256:abcdef...",)
require_hashes: Callable[..., Option] = partial( Option, "--require-hashes", dest="require_hashes", action="store_true", default=False, help="Require a hash to check each requirement against, for " "repeatable installs. This option is implied when any package in a " "requirements file has a --hash option.",)
list_path: Callable[..., Option] = partial( PipOption, "--path", dest="path", type="path", action="append", help="Restrict to the specified installation path for listing " "packages (can be used multiple times).",)
def check_list_path_option(options: Values) -> None: if options.path and (options.user or options.local): raise CommandError("Cannot combine '--path' with '--user' or '--local'")
list_exclude: Callable[..., Option] = partial( PipOption, "--exclude", dest="excludes", action="append", metavar="package", type="package_name", help="Exclude specified package from the output",)
no_python_version_warning: Callable[..., Option] = partial( Option, "--no-python-version-warning", dest="no_python_version_warning", action="store_true", default=False, help=SUPPRESS_HELP, # No-op, a hold-over from the Python 2->3 transition.)
# Features that are now always on. A warning is printed if they are used.ALWAYS_ENABLED_FEATURES = [ "truststore", # always on since 24.2 "no-binary-enable-wheel-cache", # always on since 23.1]
use_new_feature: Callable[..., Option] = partial( Option, "--use-feature", dest="features_enabled", metavar="feature", action="append", default=[], choices=[ "fast-deps", "build-constraint", "inprocess-build-deps", ] + ALWAYS_ENABLED_FEATURES, help="Enable new functionality, that may be backward incompatible.",)
use_deprecated_feature: Callable[..., Option] = partial( Option, "--use-deprecated", dest="deprecated_features_enabled", metavar="feature", action="append", default=[], choices=[ "legacy-resolver", "legacy-certs", ], help=("Enable deprecated functionality, that will be removed in the future."),)
########### groups ###########
general_group: dict[str, Any] = { "name": "General Options", "options": [ help_, debug_mode, isolated_mode, require_virtualenv, python, verbose, version, quiet, log, no_input, keyring_provider, proxy, retries, timeout, exists_action, trusted_host, cert, client_cert, cache_dir, no_cache, disable_pip_version_check, no_color, no_python_version_warning, use_new_feature, use_deprecated_feature, resume_retries, ],}
index_group: dict[str, Any] = { "name": "Package Index Options", "options": [ index_url, extra_index_url, no_index, find_links, uploaded_prior_to, ],}
package_selection_group: dict[str, Any] = { "name": "Package Selection Options", "options": [ pre, all_releases, only_final, no_binary, only_binary, prefer_binary, ],}12345678910111213141516171819202122232425262728from collections.abc import Generatorfrom contextlib import AbstractContextManager, ExitStack, contextmanagerfrom typing import TypeVar
_T = TypeVar("_T", covariant=True)
class CommandContextMixIn: def __init__(self) -> None: super().__init__() self._in_main_context = False self._main_context = ExitStack()
@contextmanager def main_context(self) -> Generator[None, None, None]: assert not self._in_main_context
self._in_main_context = True try: with self._main_context: yield finally: self._in_main_context = False
def enter_context(self, context_provider: AbstractContextManager[_T]) -> _T: assert self._in_main_context
return self._main_context.enter_context(context_provider)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""Contains command classes which may interact with an index / the network.
Unlike its sister module, req_command, this module still uses lazy importsso commands which don't always hit the network (e.g. list w/o --outdated or--uptodate) don't need waste time importing PipSession and friends."""
from __future__ import annotations
import contextlibimport loggingimport osfrom collections.abc import Iteratorfrom functools import lru_cachefrom optparse import Valuesfrom typing import TYPE_CHECKING
from pip._vendor import certifi
from pip._internal.cli.base_command import Commandfrom pip._internal.cli.command_context import CommandContextMixIn
if TYPE_CHECKING: from ssl import SSLContext
from pip._vendor.packaging.utils import NormalizedName
from pip._internal.network.session import PipSession from pip._internal.self_outdated_check import UpgradePrompt
logger = logging.getLogger(__name__)
@lru_cachedef _create_truststore_ssl_context() -> SSLContext | None: try: import ssl except ImportError: logger.warning("Disabling truststore since ssl support is missing") return None
try: from pip._vendor import truststore except ImportError: logger.warning("Disabling truststore because platform isn't supported") return None
ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.load_verify_locations(certifi.where()) return ctx
class SessionCommandMixin(CommandContextMixIn): """ A class mixin for command classes needing _build_session(). """
def __init__(self) -> None: super().__init__() self._session: PipSession | None = None
@classmethod def _get_index_urls(cls, options: Values) -> list[str] | None: """Return a list of index urls from user-provided options.""" index_urls = [] if not getattr(options, "no_index", False): url = getattr(options, "index_url", None) if url: index_urls.append(url) urls = getattr(options, "extra_index_urls", None) if urls: index_urls.extend(urls) # Return None rather than an empty list return index_urls or None
def get_default_session(self, options: Values) -> PipSession: """Get a default-managed session.""" if self._session is None: self._session = self.enter_context(self._build_session(options)) # there's no type annotation on requests.Session, so it's # automatically ContextManager[Any] and self._session becomes Any, # then https://github.com/python/mypy/issues/7696 kicks in assert self._session is not None return self._session
def _build_session( self, options: Values, retries: int | None = None, timeout: int | None = None, ) -> PipSession: from pip._internal.network.session import PipSession
cache_dir = options.cache_dir assert not cache_dir or os.path.isabs(cache_dir)
if "legacy-certs" not in options.deprecated_features_enabled: ssl_context = _create_truststore_ssl_context() else: ssl_context = None
session = PipSession( cache=os.path.join(cache_dir, "http-v2") if cache_dir else None, retries=retries if retries is not None else options.retries, resume_retries=options.resume_retries, trusted_hosts=options.trusted_hosts, index_urls=self._get_index_urls(options), ssl_context=ssl_context, )
# Handle custom ca-bundles from the user if options.cert: session.verify = options.cert
# Handle SSL client certificate if options.client_cert: session.cert = options.client_cert
# Handle timeouts if options.timeout or timeout: session.timeout = timeout if timeout is not None else options.timeout
# Handle configured proxies if options.proxy: session.proxies = { "http": options.proxy, "https": options.proxy, } session.trust_env = False session.pip_proxy = options.proxy
# Determine if we can prompt the user for authentication or not session.auth.prompting = not options.no_input session.auth.keyring_provider = options.keyring_provider
return session
def _pip_self_version_check_fetch( session: PipSession, options: Values) -> UpgradePrompt | None: from pip._internal.self_outdated_check import pip_self_version_check_fetch
return pip_self_version_check_fetch(session, options)
def _pip_self_version_check_emit(upgrade_prompt: UpgradePrompt | None) -> None: from pip._internal.self_outdated_check import pip_self_version_check_emit
pip_self_version_check_emit(upgrade_prompt)
class IndexGroupCommand(Command, SessionCommandMixin): """ Abstract base class for commands with the index_group options.
This also corresponds to the commands that permit the pip version check. """
def should_exclude_prerelease( self, options: Values, package_name: NormalizedName ) -> bool: """ Determine if pre-releases should be excluded for a package. """ # Check per-package release control settings if options.release_control: allow_prereleases = options.release_control.allows_prereleases(package_name) if allow_prereleases is True: return False # Include pre-releases elif allow_prereleases is False: return True # Exclude pre-releases
# No specific setting: exclude prereleases by default return True
@contextlib.contextmanager def pip_version_check(self, options: Values, args: list[str]) -> Iterator[None]: """ Do the pip version check if not disabled.
This overrides the default behavior of not doing the check. """ # Make sure the index_group options are present. assert hasattr(options, "no_index")
if options.disable_pip_version_check or options.no_index: yield return
upgrade_prompt: UpgradePrompt | None = None try: session = self._build_session( options, retries=0, timeout=min(5, options.timeout), ) with session: upgrade_prompt = _pip_self_version_check_fetch(session, options) except Exception: logger.warning("There was an error checking the latest version of pip.") logger.debug("See below for error", exc_info=True)
try: yield finally: try: _pip_self_version_check_emit(upgrade_prompt) except Exception: logger.warning("There was an error checking the latest version of pip.") logger.debug("See below for error", exc_info=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Primary application entrypoint."""
from __future__ import annotations
import localeimport loggingimport osimport sysimport warnings
logger = logging.getLogger(__name__)
# Do not import and use main() directly! Using it directly is actively# discouraged by pip's maintainers. The name, location and behavior of# this function is subject to change, so calling it directly is not# portable across different pip versions.
# In addition, running pip in-process is unsupported and unsafe. This is# elaborated in detail at# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.# That document also provides suggestions that should work for nearly# all users that are considering importing and using main() directly.
# However, we know that certain users will still want to invoke pip# in-process. If you understand and accept the implications of using pip# in an unsupported manner, the best approach is to use runpy to avoid# depending on the exact location of this entry point.
# The following example shows how to use runpy to invoke pip in that# case:## sys.argv = ["pip", your, args, here]# runpy.run_module("pip", run_name="__main__")## Note that this will exit the process after running, unlike a direct# call to main. As it is not safe to do any processing after calling# main, this should not be an issue in practice.
def main(args: list[str] | None = None) -> int: # NOTE: Lazy imports to speed up import of this module, # which is imported from the pip console script. This doesn't # speed up normal pip execution, but might be important in the future # if we use ``multiprocessing`` module, # which imports __main__ for each spawned subprocess. from pip._internal.cli.autocompletion import autocomplete from pip._internal.cli.main_parser import parse_command from pip._internal.commands import create_command from pip._internal.exceptions import PipError from pip._internal.utils import deprecation
if args is None: args = sys.argv[1:]
# Suppress the pkg_resources deprecation warning # Note - we use a module of .*pkg_resources to cover # the normal case (pip._vendor.pkg_resources) and the # devendored case (a bare pkg_resources) warnings.filterwarnings( action="ignore", category=DeprecationWarning, module=".*pkg_resources" )
# Configure our deprecation warnings to be sent through loggers deprecation.install_warning_logger()
autocomplete()
try: cmd_name, cmd_args = parse_command(args) except PipError as exc: sys.stderr.write(f"ERROR: {exc}") sys.stderr.write(os.linesep) sys.exit(1)
# Needed for locale.getpreferredencoding(False) to work # in pip._internal.utils.encoding.auto_decode try: locale.setlocale(locale.LC_ALL, "") except locale.Error as e: # setlocale can apparently crash if locale are uninitialized logger.debug("Ignoring error %s when setting locale", e) command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
return command.main(cmd_args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""A single place for constructing and exposing the main parser"""
from __future__ import annotations
import osimport subprocessimport sys
from pip._vendor.rich.markup import escape
from pip._internal.build_env import get_runnable_pipfrom pip._internal.cli import cmdoptionsfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatterfrom pip._internal.commands import commands_dict, get_similar_commandsfrom pip._internal.exceptions import CommandErrorfrom pip._internal.utils.misc import get_pip_version, get_prog
__all__ = ["create_main_parser", "parse_command"]
def create_main_parser() -> ConfigOptionParser: """Creates and returns the main parser for pip's CLI"""
parser = ConfigOptionParser( usage="\n%prog <command> [options]", add_help_option=False, formatter=UpdatingDefaultsHelpFormatter(), name="global", prog=get_prog(), ) parser.disable_interspersed_args()
parser.version = get_pip_version()
# add the general options gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser) parser.add_option_group(gen_opts)
# so the help formatter knows parser.main = True # type: ignore
# create command listing for description description = [""] + [ f"[optparse.longargs]{name:27}[/] {escape(command_info.summary)}" for name, command_info in commands_dict.items() ] parser.description = "\n".join(description)
return parser
def identify_python_interpreter(python: str) -> str | None: # If the named file exists, use it. # If it's a directory, assume it's a virtual environment and # look for the environment's Python executable. if os.path.exists(python): if os.path.isdir(python): # bin/python for Unix, Scripts/python.exe for Windows # Try both in case of odd cases like cygwin. for exe in ("bin/python", "Scripts/python.exe"): py = os.path.join(python, exe) if os.path.exists(py): return py else: return python
# Could not find the interpreter specified return None
def parse_command(args: list[str]) -> tuple[str, list[str]]: parser = create_main_parser()
# Note: parser calls disable_interspersed_args(), so the result of this # call is to split the initial args into the general options before the # subcommand and everything else. # For example: # args: ['--timeout=5', 'install', '--user', 'INITools'] # general_options: ['--timeout==5'] # args_else: ['install', '--user', 'INITools'] general_options, args_else = parser.parse_args(args)
# --python if general_options.python and "_PIP_RUNNING_IN_SUBPROCESS" not in os.environ: # Re-invoke pip using the specified Python interpreter interpreter = identify_python_interpreter(general_options.python) if interpreter is None: raise CommandError( f"Could not locate Python interpreter {general_options.python}" )
pip_cmd = [ interpreter, get_runnable_pip(), ] pip_cmd.extend(args)
# Set a flag so the child doesn't re-invoke itself, causing # an infinite loop. os.environ["_PIP_RUNNING_IN_SUBPROCESS"] = "1" returncode = 0 try: proc = subprocess.run(pip_cmd) returncode = proc.returncode except (subprocess.SubprocessError, OSError) as exc: raise CommandError(f"Failed to run pip under {interpreter}: {exc}") sys.exit(returncode)
# --version if general_options.version: sys.stdout.write(parser.version) sys.stdout.write(os.linesep) sys.exit()
# pip || pip help -> print_help() if not args_else or (args_else[0] == "help" and len(args_else) == 1): parser.print_help() sys.exit()
# the subcommand name cmd_name = args_else[0]
if cmd_name not in commands_dict: guess = get_similar_commands(cmd_name)
msg = [f'unknown command "{cmd_name}"'] if guess: msg.append(f'maybe you meant "{guess}"')
raise CommandError(" - ".join(msg))
# all the args without the subcommand cmd_args = args[:] cmd_args.remove(cmd_name)
return cmd_name, cmd_args123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358"""Base option parser setup"""
from __future__ import annotations
import loggingimport optparseimport osimport reimport shutilimport sysimport textwrapfrom collections.abc import Generatorfrom contextlib import suppressfrom typing import Any, NoReturn
from pip._vendor.rich.markup import escapefrom pip._vendor.rich.theme import Theme
from pip._internal.cli.status_codes import UNKNOWN_ERRORfrom pip._internal.configuration import Configuration, ConfigurationErrorfrom pip._internal.utils.logging import PipConsolefrom pip._internal.utils.misc import redact_auth_from_url, strtobool
logger = logging.getLogger(__name__)
class PrettyHelpFormatter(optparse.IndentedHelpFormatter): """A prettier/less verbose help formatter for optparse."""
styles = { "optparse.shortargs": "green", "optparse.longargs": "cyan", "optparse.groups": "bold blue", "optparse.metavar": "yellow", } highlights = { r"\s(-{1}[\w]+[\w-]*)": "shortargs", # highlight -letter as short args r"\s(-{2}[\w]+[\w-]*)": "longargs", # highlight --words as long args }
def __init__(self, *args: Any, **kwargs: Any) -> None: # help position must be aligned with __init__.parseopts.description kwargs["max_help_position"] = 30 kwargs["indent_increment"] = 1 kwargs["width"] = shutil.get_terminal_size()[0] - 2 super().__init__(*args, **kwargs)
def format_option_strings(self, option: optparse.Option) -> str: """Return a comma-separated list of option strings and metavars.""" opts = []
if option._short_opts: opts.append(f"[optparse.shortargs]{option._short_opts[0]}[/]") if option._long_opts: opts.append(f"[optparse.longargs]{option._long_opts[0]}[/]") if len(opts) > 1: opts.insert(1, ", ")
if option.takes_value(): assert option.dest is not None metavar = option.metavar or option.dest.lower() opts.append(f" [optparse.metavar]<{escape(metavar.lower())}>[/]")
return "".join(opts)
def format_option(self, option: optparse.Option) -> str: """Overridden method with Rich support.""" # fmt: off result = [] opts = self.option_strings[option] opt_width = self.help_position - self.current_indent - 2 # Remove the rich style tags before calculating width during # text wrap calculations. Also store the length removed to adjust # the padding in the else branch. stripped = re.sub(r"(\[[a-z.]+\])|(\[\/\])", "", opts) style_tag_length = len(opts) - len(stripped) if len(stripped) > opt_width: opts = "%*s%s\n" % (self.current_indent, "", opts) # noqa: UP031 indent_first = self.help_position else: # start help on same line as opts opts = "%*s%-*s " % (self.current_indent, "", # noqa: UP031 opt_width + style_tag_length, opts) indent_first = 0 result.append(opts) if option.help: help_text = self.expand_default(option) help_lines = textwrap.wrap(help_text, self.help_width) result.append("%*s%s\n" % (indent_first, "", help_lines[0])) # noqa: UP031 result.extend(["%*s%s\n" % (self.help_position, "", line) # noqa: UP031 for line in help_lines[1:]]) elif opts[-1] != "\n": result.append("\n") return "".join(result) # fmt: on
def format_heading(self, heading: str) -> str: if heading == "Options": return "" return "[optparse.groups]" + escape(heading) + ":[/]\n"
def format_usage(self, usage: str) -> str: """ Ensure there is only one newline between usage and the first heading if there is no description. """ contents = self.indent_lines(textwrap.dedent(usage), " ") msg = f"\n[optparse.groups]Usage:[/] {escape(contents)}\n" return msg
def format_description(self, description: str | None) -> str: # leave full control over description to us if description: if hasattr(self.parser, "main"): label = "[optparse.groups]Commands:[/]" else: label = "[optparse.groups]Description:[/]"
# some doc strings have initial newlines, some don't description = description.lstrip("\n") # some doc strings have final newlines and spaces, some don't description = description.rstrip() # dedent, then reindent description = self.indent_lines(textwrap.dedent(description), " ") description = f"{label}\n{description}\n" return description else: return ""
def format_epilog(self, epilog: str | None) -> str: # leave full control over epilog to us if epilog: return escape(epilog) else: return ""
def expand_default(self, option: optparse.Option) -> str: """Overridden HelpFormatter.expand_default() which colorizes flags.""" help = escape(super().expand_default(option)) for regex, style in self.highlights.items(): help = re.sub(regex, rf"[optparse.{style}] \1[/]", help) return help
def indent_lines(self, text: str, indent: str) -> str: new_lines = [indent + line for line in text.split("\n")] return "\n".join(new_lines)
class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter): """Custom help formatter for use in ConfigOptionParser.
This is updates the defaults before expanding them, allowing them to show up correctly in the help listing.
Also redact auth from url type options """
def expand_default(self, option: optparse.Option) -> str: default_values = None if self.parser is not None: assert isinstance(self.parser, ConfigOptionParser) self.parser._update_defaults(self.parser.defaults) assert option.dest is not None default_values = self.parser.defaults.get(option.dest) help_text = super().expand_default(option)
if default_values and option.metavar == "URL": if isinstance(default_values, str): default_values = [default_values]
# If its not a list, we should abort and just return the help text if not isinstance(default_values, list): default_values = []
for val in default_values: help_text = help_text.replace(val, redact_auth_from_url(val))
return help_text
class CustomOptionParser(optparse.OptionParser): def insert_option_group( self, idx: int, *args: Any, **kwargs: Any ) -> optparse.OptionGroup: """Insert an OptionGroup at a given position.""" group = self.add_option_group(*args, **kwargs)
self.option_groups.pop() self.option_groups.insert(idx, group)
return group
@property def option_list_all(self) -> list[optparse.Option]: """Get a list of all options, including those in option groups.""" res = self.option_list[:] for i in self.option_groups: res.extend(i.option_list)
return res
class ConfigOptionParser(CustomOptionParser): """Custom option parser which updates its defaults by checking the configuration files and environmental variables"""
def __init__( self, *args: Any, name: str, isolated: bool = False, **kwargs: Any, ) -> None: self.name = name self.config = Configuration(isolated)
assert self.name super().__init__(*args, **kwargs)
def check_default(self, option: optparse.Option, key: str, val: Any) -> Any: try: return option.check_value(key, val) except optparse.OptionValueError as exc: print(f"An error occurred during configuration: {exc}") sys.exit(3)
def _get_ordered_configuration_items( self, ) -> Generator[tuple[str, Any], None, None]: # Configuration gives keys in an unordered manner. Order them. override_order = ["global", self.name, ":env:"]
# Pool the options into different groups # Use a dict because we need to implement the fallthrough logic after PR 12201 # was merged which removed the fallthrough logic for options section_items_dict: dict[str, dict[str, Any]] = { name: {} for name in override_order }
for _, value in self.config.items(): for section_key, val in value.items():
section, key = section_key.split(".", 1) if section in override_order: section_items_dict[section][key] = val
# Now that we a dict of items per section, convert to list of tuples # Make sure we completely remove empty values again section_items = { name: [(k, v) for k, v in section_items_dict[name].items() if v] for name in override_order }
# Yield each group in their override order for section in override_order: yield from section_items[section]
def _update_defaults(self, defaults: dict[str, Any]) -> dict[str, Any]: """Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists)."""
# Accumulate complex default state. self.values = optparse.Values(self.defaults) late_eval = set() # Then set the options with those values for key, val in self._get_ordered_configuration_items(): # '--' because configuration supports only long names option = self.get_option("--" + key)
# Ignore options not present in this parser. E.g. non-globals put # in [global] by users that want them to apply to all applicable # commands. if option is None: continue
assert option.dest is not None
if option.action in ("store_true", "store_false"): try: val = strtobool(val) except ValueError: self.error( f"{val} is not a valid value for {key} option, " "please specify a boolean value like yes/no, " "true/false or 1/0 instead." ) elif option.action == "count": with suppress(ValueError): val = strtobool(val) with suppress(ValueError): val = int(val) if not isinstance(val, int) or val < 0: self.error( f"{val} is not a valid value for {key} option, " "please instead specify either a non-negative integer " "or a boolean value like yes/no or false/true " "which is equivalent to 1/0." ) elif option.action == "append": val = val.split() val = [self.check_default(option, key, v) for v in val] elif option.action == "callback": assert option.callback is not None late_eval.add(option.dest) opt_str = option.get_opt_string() val = option.convert_value(opt_str, val) # From take_action args = option.callback_args or () kwargs = option.callback_kwargs or {} option.callback(option, opt_str, val, self, *args, **kwargs) else: val = self.check_default(option, key, val)
defaults[option.dest] = val
for key in late_eval: defaults[key] = getattr(self.values, key) self.values = None return defaults
def get_default_values(self) -> optparse.Values: """Overriding to make updating the defaults after instantiation of the option parser possible, _update_defaults() does the dirty work.""" if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults)
# Load the configuration, or error out in case of an error try: self.config.load() except ConfigurationError as err: self.exit(UNKNOWN_ERROR, str(err))
defaults = self._update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): assert option.dest is not None default = defaults.get(option.dest) if isinstance(default, str): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return optparse.Values(defaults)
def error(self, msg: str) -> NoReturn: self.print_usage(sys.stderr) self.exit(UNKNOWN_ERROR, f"{msg}\n")
def print_help(self, file: Any = None) -> None: # This is unfortunate but necessary since arguments may have not been # parsed yet at this point, so detect --no-color manually. no_color = ( "--no-color" in sys.argv or bool(strtobool(os.environ.get("PIP_NO_COLOR", "no") or "no")) or "NO_COLOR" in os.environ ) console = PipConsole( theme=Theme(PrettyHelpFormatter.styles), no_color=no_color, file=file ) console.print(self.format_help().rstrip(), highlight=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153from __future__ import annotations
import functoolsimport sysfrom collections.abc import Generator, Iterable, Iteratorfrom typing import TYPE_CHECKING, Callable, Literal, TypeVar
from pip._vendor.rich.progress import ( BarColumn, DownloadColumn, FileSizeColumn, MofNCompleteColumn, Progress, ProgressColumn, SpinnerColumn, TextColumn, TimeElapsedColumn, TimeRemainingColumn, TransferSpeedColumn,)
from pip._internal.cli.spinners import RateLimiterfrom pip._internal.utils.logging import get_console, get_indentation
if TYPE_CHECKING: from pip._internal.req.req_install import InstallRequirement
T = TypeVar("T")ProgressRenderer = Callable[[Iterable[T]], Iterator[T]]BarType = Literal["on", "off", "raw"]
def _rich_download_progress_bar( iterable: Iterable[bytes], *, bar_type: BarType, size: int | None, initial_progress: int | None = None,) -> Generator[bytes, None, None]: assert bar_type == "on", "This should only be used in the default mode."
if not size: total = float("inf") columns: tuple[ProgressColumn, ...] = ( TextColumn("[progress.description]{task.description}"), SpinnerColumn("line", speed=1.5), FileSizeColumn(), TransferSpeedColumn(), TimeElapsedColumn(), ) else: total = size columns = ( TextColumn("[progress.description]{task.description}"), BarColumn(), DownloadColumn(), TransferSpeedColumn(), TextColumn("{task.fields[time_description]}"), TimeRemainingColumn(elapsed_when_finished=True), )
progress = Progress(*columns, refresh_per_second=5) task_id = progress.add_task( " " * (get_indentation() + 2), total=total, time_description="eta" ) if initial_progress is not None: progress.update(task_id, advance=initial_progress) with progress: for chunk in iterable: yield chunk progress.update(task_id, advance=len(chunk)) progress.update(task_id, time_description="")
def _rich_install_progress_bar( iterable: Iterable[InstallRequirement], *, total: int) -> Iterator[InstallRequirement]: columns = ( TextColumn("{task.fields[indent]}"), BarColumn(), MofNCompleteColumn(), TextColumn("{task.description}"), ) console = get_console()
bar = Progress(*columns, refresh_per_second=6, console=console, transient=True) # Hiding the progress bar at initialization forces a refresh cycle to occur # until the bar appears, avoiding very short flashes. task = bar.add_task("", total=total, indent=" " * get_indentation(), visible=False) with bar: for req in iterable: bar.update(task, description=rf"\[{req.name}]", visible=True) yield req bar.advance(task)
def _raw_progress_bar( iterable: Iterable[bytes], *, size: int | None, initial_progress: int | None = None,) -> Generator[bytes, None, None]: def write_progress(current: int, total: int) -> None: sys.stdout.write(f"Progress {current} of {total}\n") sys.stdout.flush()
current = initial_progress or 0 total = size or 0 rate_limiter = RateLimiter(0.25)
write_progress(current, total) for chunk in iterable: current += len(chunk) if rate_limiter.ready() or current == total: write_progress(current, total) rate_limiter.reset() yield chunk
def get_download_progress_renderer( *, bar_type: BarType, size: int | None = None, initial_progress: int | None = None) -> ProgressRenderer[bytes]: """Get an object that can be used to render the download progress.
Returns a callable, that takes an iterable to "wrap". """ if bar_type == "on": return functools.partial( _rich_download_progress_bar, bar_type=bar_type, size=size, initial_progress=initial_progress, ) elif bar_type == "raw": return functools.partial( _raw_progress_bar, size=size, initial_progress=initial_progress, ) else: return iter # no-op, when passed an iterator
def get_install_progress_renderer( *, bar_type: BarType, total: int) -> ProgressRenderer[InstallRequirement]: """Get an object that can be used to render the install progress. Returns a callable, that takes an iterable to "wrap". """ if bar_type == "on": return functools.partial(_rich_install_progress_bar, total=total) else: return iter.gitattributes+4
.venv-deploy/lib/python3.14/site-packages/idna-3.18.dist-info/WHEELAdded+4
.venv-deploy/lib/python3.14/site-packages/idna-3.18.dist-info/entry_points.txtAdded+3
.venv-deploy/lib/python3.14/site-packages/idna-3.18.dist-info/licenses/LICENSE.mdAdded+31
.venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/INSTALLERAdded+1
.venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/METADATAAdded+112
.venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/RECORDAdded+52
.venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/WHEELAdded+4
.venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/licenses/LICENSEAdded+3
.venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/licenses/LICENSE.APACHEAdded+177
.venv-deploy/lib/python3.14/site-packages/packaging-26.3.dist-info/licenses/LICENSE.BSDAdded+23
.venv-deploy/lib/python3.14/site-packages/packaging/__init__.pyAdded+15
.venv-deploy/lib/python3.14/site-packages/packaging/_elffile.pyAdded+108
.venv-deploy/lib/python3.14/site-packages/packaging/_manylinux.pyAdded+278
.venv-deploy/lib/python3.14/site-packages/packaging/_musllinux.pyAdded+88
.venv-deploy/lib/python3.14/site-packages/packaging/_parser.pyAdded+418
.venv-deploy/lib/python3.14/site-packages/packaging/_ranges.pyAdded+836
.venv-deploy/lib/python3.14/site-packages/packaging/_structures.pyAdded+33
.venv-deploy/lib/python3.14/site-packages/packaging/_tokenizer.pyAdded+200
.venv-deploy/lib/python3.14/site-packages/packaging/dependency_groups.pyAdded+335
.venv-deploy/lib/python3.14/site-packages/packaging/direct_url.pyAdded+349
.venv-deploy/lib/python3.14/site-packages/packaging/errors.pyAdded+94
.venv-deploy/lib/python3.14/site-packages/packaging/licenses/__init__.pyAdded+198
.venv-deploy/lib/python3.14/site-packages/packaging/licenses/_spdx.pyAdded+799
.venv-deploy/lib/python3.14/site-packages/packaging/markers.pyAdded+576
.venv-deploy/lib/python3.14/site-packages/packaging/metadata.pyAdded+1054
.venv-deploy/lib/python3.14/site-packages/packaging/py.typedAdded
.venv-deploy/lib/python3.14/site-packages/packaging/pylock.pyAdded+943
.venv-deploy/lib/python3.14/site-packages/packaging/ranges.pyAdded+2067
.venv-deploy/lib/python3.14/site-packages/packaging/requirements.pyAdded+192
.venv-deploy/lib/python3.14/site-packages/packaging/specifiers.pyAdded+1457
.venv-deploy/lib/python3.14/site-packages/packaging/tags.pyAdded+1053
.venv-deploy/lib/python3.14/site-packages/packaging/utils.pyAdded+370
.venv-deploy/lib/python3.14/site-packages/packaging/version.pyAdded+1252
.venv-deploy/lib/python3.14/site-packages/pip/__init__.pyAdded+13
.venv-deploy/lib/python3.14/site-packages/pip/__main__.pyAdded+24
.venv-deploy/lib/python3.14/site-packages/pip/__pip-runner__.pyAdded+50
.venv-deploy/lib/python3.14/site-packages/pip/_internal/__init__.pyAdded+18
.venv-deploy/lib/python3.14/site-packages/pip/_internal/build_env.pyAdded+606
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cache.pyAdded+291
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/__init__.pyAdded+3
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/autocompletion.pyAdded+184
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/base_command.pyAdded+264
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/cmdoptions.pyAdded+1298
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/command_context.pyAdded+28
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/index_command.pyAdded+212
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/main.pyAdded+85
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/main_parser.pyAdded+136
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/parser.pyAdded+358
.venv-deploy/lib/python3.14/site-packages/pip/_internal/cli/progress_bars.pyAdded+153