././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8143685 packaging-26.0/CHANGELOG.rst0000644000000000000000000005103515133751156012347 0ustar00Changelog --------- 26.0 - 2026-01-20 ~~~~~~~~~~~~~~~~~ Features: * PEP 751: support pylock (:pull:`900`) * PEP 794: import name metadata (:pull:`948`) * Support for writing metadata to a file (:pull:`846`) * Support ``__replace__`` on Version (:pull:`1003`) * Support positional pattern matching for ``Version`` and ``SpecifierSet`` (:pull:`1004`) Behavior adaptations: * PEP 440 handling of prereleases for ``Specifier.contains``, ``SpecifierSet.contains``, and ``SpecifierSet.filter`` (:pull:`897`) * Handle PEP 440 edge case in ``SpecifierSet.filter`` (:pull:`942`) * Adjust arbitrary equality intersection preservation in ``SpecifierSet`` (:pull:`951`) * Return ``False`` instead of raising for ``.contains`` with invalid version (:pull:`932`) * Support arbitrary equality on arbitrary strings for ``Specifier`` and ``SpecifierSet``'s ``filter`` and ``contains`` method. (:pull:`954`) * Only try to parse as ``Version`` on certain marker keys, return ``False`` on unequal ordered comparisons (:pull:`939`) Fixes: * Update ``_hash`` when unpickling ``Tag()`` (:pull:`860`) * Correct comment and simplify implicit prerelease handling in ``Specifier.prereleases`` (:pull:`896`) * Use explicit ``_GLibCVersion`` ``NamedTuple`` in ``_manylinux`` (:pull:`868`) * Detect invalid license expressions containing ``()`` (:pull:`879`) * Correct regex for metadata ``'name'`` format (:pull:`925`) * Improve the message around expecting a semicolon (:pull:`833`) * Support nested parens in license expressions (:pull:`931`) * Add space before at symbol in ``Requirements`` string (:pull:`953`) * A root logger use found, use a ``packaging`` logger instead (:pull:`965`) * Better support for subclassing ``Marker`` and ``Requirement`` (:pull:`1022`) * Normalize all extras, not just if it comes first (:pull:`1024`) * Don't produce a broken repr if ``Marker`` fails to construct (:pull:`1033`) Performance: * Avoid recompiling regexes in the tokenizer for a 3x speedup (:pull:`1019`) * Improve performance in ``_manylinux.py`` (:pull:`869`) * Minor cleanups to ``Version`` (:pull:`913`) * Skip redundant creation of ``Version``'s in specifier comparison (:pull:`986`) * Cache the ``Specifier``'s ``Version`` (:pull:`985`) * Make ``Version`` a little faster (:pull:`987`) * Minor ``Version`` regex cleanup (:pull:`990`) * Faster regex on Python 3.11.5+ for ``Version`` (:pull:`988`, :pull:`1055`) * Lazily calculate ``_key`` in ``Version`` (:pull:`989`, :pull:`1048`) * Faster ``canonicalize_version`` (:pull:`993`) * Use ``re.fullmatch`` in a couple more places (:pull:`992`, :pull:`1029`) * Use ``map`` instead of generator (:pull:`996`) * Deprecate ``._version`` (``_Version``, a ``NamedTuple``) (:pull:`995`, :pull:`1062`) * Avoid duplicate ``Version`` creation in ``canonicalize_version`` (:pull:`994`) * Add ``__slots__`` to core classes (:pull:`1001`, :pull:`1002`, :pull:`1032`) * Use ``Version.__replace__`` in specifier comparison (:pull:`999`) * Use ``_get_spec_version`` in more places in ``Specifier`` (:pull:`1005`) * Pull ``set`` construction out of function (:pull:`1012`) * Letter normalization dict for prereleases and the like (:pull:`1014`) * Use ``str.partition`` in ``_parse_project_urls`` (:pull:`1013`) * Avoid normalizing extras again when comparing (:pull:`1028`) * Speed up ``Version.__str__`` by about 10% (:pull:`997`) * Much faster ``canonicalize_name`` by avoiding a regex (:pull:`1030`, :pull:`1047`, :pull:`1064`) * Faster zero stripping (:pull:`1058`) Type annotations: * Fix a type annotation (:pull:`907`) * Fix type hint of function used with ``contextlib.contextmanager`` (:pull:`1046`) * Fix tags return type in ``parse_wheel_filename`` docs (:pull:`973`) * Add type hint for ``_version`` in ``.version.Version`` (:pull:`927`) * Changed static type annotations in prereleases setter method in ``specifier.py`` (:pull:`930`) * Statically type our test suite (:pull:`982`) Internal: * Test and declare support for Python 3.14 (:pull:`901`) * Change our license metadata to use an SPDX license expression (:pull:`881`, :pull:`924`) * Expand the Ruff checks run on our codebase (:pull:`835`, :pull:`957`, :pull:`959`, :pull:`963`, :pull:`956`, :pull:`961`, :pull:`964`, :pull:`958`, :pull:`960`, :pull:`968`, :pull:`967`, :pull:`966`, :pull:`969`, :pull:`980`, :pull:`979`, :pull:`962`, :pull:`984`, :pull:`972`) * Add spell checking (:pull:`904`, :pull:`910`, :pull:`1015`) * Improve links back to source in the documentation (:pull:`991`) * Add case insensitivity tests for arbitrary equality (:pull:`975`) * Fix incorrectly implicitly concatenated string in specifiers test (:pull:`946`) * Simpler else instead of assert in a check (:pull:`1027`, :pull:`1031`) * Synchronize documentation and code for markers (:pull:`1008`) * Use the GitHub Actions slim runner for the all pass check (:pull:`1021`) * Use ``actionlint`` to check CI workflows (:pull:`1052`) * Use Trusted Publishing (:pull:`893`, :pull:`1043`, :pull:`1045`, :pull:`1051`) * Use zizmor to check CI (:pull:`1035`) * Test on first public release of CPython 3.11 and newer (:pull:`1056`) Since the final release candidate: Faster ``canonicalize_name``, especially on Python 3.12 and 3.13, where performance regressed previously (:pull:`1064`), and reintroduce (deprecated) support for ``Version._.version`` (:pull:`1062`). 26.0rc3 - 2026-01-15 ~~~~~~~~~~~~~~~~~~~~ Third release candidate for 26.0. Avoid bug in CPython 3.11.0-3.11.4 and older PyPy 3.11 (:pull:`1055`). 26.0rc2 - 2026-01-12 ~~~~~~~~~~~~~~~~~~~~ Second release candidate for 26.0. Fixed a regression in (private) ``Version._key`` for ``packaging_legacy`` (:pull:`1048`), and speed up stripping zeros a little more (:pull:`1058`). 26.0rc1 - 2026-01-09 ~~~~~~~~~~~~~~~~~~~~ First release candidate for 26.0. 25.0 - 2025-04-19 ~~~~~~~~~~~~~~~~~ * PEP 751: Add support for ``extras`` and ``dependency_groups`` markers. (:issue:`885`) * PEP 738: Add support for Android platform tags. (:issue:`880`) 24.2 - 2024-11-08 ~~~~~~~~~~~~~~~~~ * PEP 639: Implement License-Expression and License-File (:issue:`828`) * Use ``!r`` formatter for error messages with filenames (:issue:`844`) * Add support for PEP 730 iOS tags (:issue:`832`) * Fix prerelease detection for ``>`` and ``<`` (:issue:`794`) * Fix uninformative error message (:issue:`830`) * Refactor ``canonicalize_version`` (:issue:`793`) * Patch python_full_version unconditionally (:issue:`825`) * Fix doc for ``canonicalize_version`` to mention ``strip_trailing_zero`` and a typo in a docstring (:issue:`801`) * Fix typo in Version ``__str__`` (:issue:`817`) * Support creating a ``SpecifierSet`` from an iterable of ``Specifier`` objects (:issue:`775`) 24.1 - 2024-06-10 ~~~~~~~~~~~~~~~~~ * Document ``markers.default_environment()`` (:issue:`753`). * Add support for Python 3.13 (:issue:`783`). * Modernise type annotations (:issue:`785`). * Work around ``platform.python_version()`` returning non PEP 440 compliant version for non-tagged CPython builds (:issue:`802`). 24.0 - 2024-03-10 ~~~~~~~~~~~~~~~~~ * Do specifier matching correctly when the specifier contains an epoch number and has more components than the version (:issue:`683`) * Support the experimental ``--disable-gil`` builds in packaging.tags (:issue:`727`) * BREAKING: Make optional ``metadata.Metadata`` attributes default to ``None`` (:issue:`733`) * Fix errors when trying to access the ``description_content_type``, ``keywords``, and ``requires_python`` attributes on ``metadata.Metadata`` when those values have not been provided (:issue:`733`) * Fix a bug preventing the use of the built in ``ExceptionGroup`` on versions of Python that support it (:issue:`725`) 23.2 - 2023-10-01 ~~~~~~~~~~~~~~~~~ * Document calendar-based versioning scheme (:issue:`716`) * Enforce that the entire marker string is parsed (:issue:`687`) * Requirement parsing no longer automatically validates the URL (:issue:`120`) * Canonicalize names for requirements comparison (:issue:`644`) * Introduce ``metadata.Metadata`` (along with ``metadata.ExceptionGroup`` and ``metadata.InvalidMetadata``; :issue:`570`) * Introduce the ``validate`` keyword parameter to ``utils.normalize_name()`` (:issue:`570`) * Introduce ``utils.is_normalized_name()`` (:issue:`570`) * Make ``utils.parse_sdist_filename()`` and ``utils.parse_wheel_filename()`` raise ``InvalidSdistFilename`` and ``InvalidWheelFilename``, respectively, when the version component of the name is invalid * Remove support for Python 3.7 (:issue:`783`) 23.1 - 2023-04-12 ~~~~~~~~~~~~~~~~~ * Parse raw metadata (:issue:`671`) * Import underlying parser functions as an underscored variable (:issue:`663`) * Improve error for local version label with unsupported operators (:issue:`675`) * Add dedicated error for specifiers with incorrect ``.*`` suffix * Replace spaces in platform names with underscores (:issue:`620`) * Relax typing of ``_key`` on ``_BaseVersion`` (:issue:`669`) * Handle prefix match with zeros at end of prefix correctly (:issue:`674`) 23.0 - 2023-01-08 ~~~~~~~~~~~~~~~~~ * Allow ``"extra"`` to be ``None`` in the marker environment (:issue:`650`) * Refactor ``tags._generic_api`` to use ``EXT_SUFFIX`` (:issue:`607`) * Correctly handle trailing whitespace on URL requirements (:issue:`642`) * Fix typing for ``specifiers.BaseSpecifier.filter()`` (:issue:`643`) * Use stable Python 3.11 in tests (:issue:`641`) * Correctly handle non-normalised specifiers in requirements (:issue:`634`) * Move to ``src/`` layout (:issue:`626`) * Remove ``__about__`` file, in favour of keeping constants in ``__init__`` (:issue:`626`) 22.0 - 2022-12-07 ~~~~~~~~~~~~~~~~~ * Explicitly declare support for Python 3.11 (:issue:`587`) * Remove support for Python 3.6 (:issue:`500`) * Remove ``LegacySpecifier`` and ``LegacyVersion`` (:issue:`407`) * Add ``__hash__`` and ``__eq__`` to ``Requirement`` (:issue:`499`) * Add a ``cpNNN-none-any`` tag (:issue:`541`) * Adhere to :pep:`685` when evaluating markers with extras (:issue:`545`) * Allow accepting locally installed prereleases with ``SpecifierSet`` (:issue:`515`) * Allow pre-release versions in marker evaluation (:issue:`523`) * Correctly parse ELF for musllinux on Big Endian (:issue:`538`) * Document ``packaging.utils.NormalizedName`` (:issue:`565`) * Document exceptions raised by functions in ``packaging.utils`` (:issue:`544`) * Fix compatible version specifier incorrectly strip trailing ``0`` (:issue:`493`) * Fix macOS platform tags with old macOS SDK (:issue:`513`) * Forbid prefix version matching on pre-release/post-release segments (:issue:`563`) * Normalize specifier version for prefix matching (:issue:`561`) * Improve documentation for ``packaging.specifiers`` and ``packaging.version``. (:issue:`572`) * ``Marker.evaluate`` will now assume evaluation environment with empty ``extra``. Evaluating markers like ``"extra == 'xyz'"`` without passing any extra in the ``environment`` will no longer raise an exception (:issue:`550`) * Remove dependency on ``pyparsing``, by replacing it with a hand-written parser. This package now has no runtime dependencies (:issue:`468`) * Update return type hint for ``Specifier.filter`` and ``SpecifierSet.filter`` to use ``Iterator`` instead of ``Iterable`` (:issue:`584`) 21.3 - 2021-11-17 ~~~~~~~~~~~~~~~~~ * Add a ``pp3-none-any`` tag (:issue:`311`) * Replace the blank pyparsing 3 exclusion with a 3.0.5 exclusion (:issue:`481`, :issue:`486`) * Fix a spelling mistake (:issue:`479`) 21.2 - 2021-10-29 ~~~~~~~~~~~~~~~~~ * Update documentation entry for 21.1. 21.1 - 2021-10-29 ~~~~~~~~~~~~~~~~~ * Update pin to pyparsing to exclude 3.0.0. 21.0 - 2021-07-03 ~~~~~~~~~~~~~~~~~ * PEP 656: musllinux support (:issue:`411`) * Drop support for Python 2.7, Python 3.4 and Python 3.5. * Replace distutils usage with sysconfig (:issue:`396`) * Add support for zip files in ``parse_sdist_filename`` (:issue:`429`) * Use cached ``_hash`` attribute to short-circuit tag equality comparisons (:issue:`417`) * Specify the default value for the ``specifier`` argument to ``SpecifierSet`` (:issue:`437`) * Proper keyword-only "warn" argument in packaging.tags (:issue:`403`) * Correctly remove prerelease suffixes from ~= check (:issue:`366`) * Fix type hints for ``Version.post`` and ``Version.dev`` (:issue:`393`) * Use typing alias ``UnparsedVersion`` (:issue:`398`) * Improve type inference for ``packaging.specifiers.filter()`` (:issue:`430`) * Tighten the return type of ``canonicalize_version()`` (:issue:`402`) 20.9 - 2021-01-29 ~~~~~~~~~~~~~~~~~ * Run `isort `_ over the code base (:issue:`377`) * Add support for the ``macosx_10_*_universal2`` platform tags (:issue:`379`) * Introduce ``packaging.utils.parse_wheel_filename()`` and ``parse_sdist_filename()`` (:issue:`387` and :issue:`389`) 20.8 - 2020-12-11 ~~~~~~~~~~~~~~~~~ * Revert back to setuptools for compatibility purposes for some Linux distros (:issue:`363`) * Do not insert an underscore in wheel tags when the interpreter version number is more than 2 digits (:issue:`372`) 20.7 - 2020-11-28 ~~~~~~~~~~~~~~~~~ No unreleased changes. 20.6 - 2020-11-28 ~~~~~~~~~~~~~~~~~ .. note:: This release was subsequently yanked, and these changes were included in 20.7. * Fix flit configuration, to include LICENSE files (:issue:`357`) * Make ``intel`` a recognized CPU architecture for the ``universal`` macOS platform tag (:issue:`361`) * Add some missing type hints to ``packaging.requirements`` (issue:`350`) 20.5 - 2020-11-27 ~~~~~~~~~~~~~~~~~ * Officially support Python 3.9 (:issue:`343`) * Deprecate the ``LegacyVersion`` and ``LegacySpecifier`` classes (:issue:`321`) * Handle ``OSError`` on non-dynamic executables when attempting to resolve the glibc version string. 20.4 - 2020-05-19 ~~~~~~~~~~~~~~~~~ * Canonicalize version before comparing specifiers. (:issue:`282`) * Change type hint for ``canonicalize_name`` to return ``packaging.utils.NormalizedName``. This enables the use of static typing tools (like mypy) to detect mixing of normalized and un-normalized names. 20.3 - 2020-03-05 ~~~~~~~~~~~~~~~~~ * Fix changelog for 20.2. 20.2 - 2020-03-05 ~~~~~~~~~~~~~~~~~ * Fix a bug that caused a 32-bit OS that runs on a 64-bit ARM CPU (e.g. ARM-v8, aarch64), to report the wrong bitness. 20.1 - 2020-01-24 ~~~~~~~~~~~~~~~~~~~ * Fix a bug caused by reuse of an exhausted iterator. (:issue:`257`) 20.0 - 2020-01-06 ~~~~~~~~~~~~~~~~~ * Add type hints (:issue:`191`) * Add proper trove classifiers for PyPy support (:issue:`198`) * Scale back depending on ``ctypes`` for manylinux support detection (:issue:`171`) * Use ``sys.implementation.name`` where appropriate for ``packaging.tags`` (:issue:`193`) * Expand upon the API provided by ``packaging.tags``: ``interpreter_name()``, ``mac_platforms()``, ``compatible_tags()``, ``cpython_tags()``, ``generic_tags()`` (:issue:`187`) * Officially support Python 3.8 (:issue:`232`) * Add ``major``, ``minor``, and ``micro`` aliases to ``packaging.version.Version`` (:issue:`225`) * Properly mark ``packaging`` has being fully typed by adding a ``py.typed`` file (:issue:`226`) 19.2 - 2019-09-18 ~~~~~~~~~~~~~~~~~ * Remove dependency on ``attrs`` (:issue:`178`, :issue:`179`) * Use appropriate fallbacks for CPython ABI tag (:issue:`181`, :issue:`185`) * Add manylinux2014 support (:issue:`186`) * Improve ABI detection (:issue:`181`) * Properly handle debug wheels for Python 3.8 (:issue:`172`) * Improve detection of debug builds on Windows (:issue:`194`) 19.1 - 2019-07-30 ~~~~~~~~~~~~~~~~~ * Add the ``packaging.tags`` module. (:issue:`156`) * Correctly handle two-digit versions in ``python_version`` (:issue:`119`) 19.0 - 2019-01-20 ~~~~~~~~~~~~~~~~~ * Fix string representation of PEP 508 direct URL requirements with markers. * Better handling of file URLs This allows for using ``file:///absolute/path``, which was previously prevented due to the missing ``netloc``. This allows for all file URLs that ``urlunparse`` turns back into the original URL to be valid. 18.0 - 2018-09-26 ~~~~~~~~~~~~~~~~~ * Improve error messages when invalid requirements are given. (:issue:`129`) 17.1 - 2017-02-28 ~~~~~~~~~~~~~~~~~ * Fix ``utils.canonicalize_version`` when supplying non PEP 440 versions. 17.0 - 2017-02-28 ~~~~~~~~~~~~~~~~~ * Drop support for python 2.6, 3.2, and 3.3. * Define minimal pyparsing version to 2.0.2 (:issue:`91`). * Add ``epoch``, ``release``, ``pre``, ``dev``, and ``post`` attributes to ``Version`` and ``LegacyVersion`` (:issue:`34`). * Add ``Version().is_devrelease`` and ``LegacyVersion().is_devrelease`` to make it easy to determine if a release is a development release. * Add ``utils.canonicalize_version`` to canonicalize version strings or ``Version`` instances (:issue:`121`). 16.8 - 2016-10-29 ~~~~~~~~~~~~~~~~~ * Fix markers that utilize ``in`` so that they render correctly. * Fix an erroneous test on Python RC releases. 16.7 - 2016-04-23 ~~~~~~~~~~~~~~~~~ * Add support for the deprecated ``python_implementation`` marker which was an undocumented setuptools marker in addition to the newer markers. 16.6 - 2016-03-29 ~~~~~~~~~~~~~~~~~ * Add support for the deprecated, PEP 345 environment markers in addition to the newer markers. 16.5 - 2016-02-26 ~~~~~~~~~~~~~~~~~ * Fix a regression in parsing requirements with whitespaces between the comma separators. 16.4 - 2016-02-22 ~~~~~~~~~~~~~~~~~ * Fix a regression in parsing requirements like ``foo (==4)``. 16.3 - 2016-02-21 ~~~~~~~~~~~~~~~~~ * Fix a bug where ``packaging.requirements:Requirement`` was overly strict when matching legacy requirements. 16.2 - 2016-02-09 ~~~~~~~~~~~~~~~~~ * Add a function that implements the name canonicalization from PEP 503. 16.1 - 2016-02-07 ~~~~~~~~~~~~~~~~~ * Implement requirement specifiers from PEP 508. 16.0 - 2016-01-19 ~~~~~~~~~~~~~~~~~ * Relicense so that packaging is available under *either* the Apache License, Version 2.0 or a 2 Clause BSD license. * Support installation of packaging when only distutils is available. * Fix ``==`` comparison when there is a prefix and a local version in play. (:issue:`41`). * Implement environment markers from PEP 508. 15.3 - 2015-08-01 ~~~~~~~~~~~~~~~~~ * Normalize post-release spellings for rev/r prefixes. :issue:`35` 15.2 - 2015-05-13 ~~~~~~~~~~~~~~~~~ * Fix an error where the arbitrary specifier (``===``) was not correctly allowing pre-releases when it was being used. * Expose the specifier and version parts through properties on the ``Specifier`` classes. * Allow iterating over the ``SpecifierSet`` to get access to all of the ``Specifier`` instances. * Allow testing if a version is contained within a specifier via the ``in`` operator. 15.1 - 2015-04-13 ~~~~~~~~~~~~~~~~~ * Fix a logic error that was causing inconsistent answers about whether or not a pre-release was contained within a ``SpecifierSet`` or not. 15.0 - 2015-01-02 ~~~~~~~~~~~~~~~~~ * Add ``Version().is_postrelease`` and ``LegacyVersion().is_postrelease`` to make it easy to determine if a release is a post release. * Add ``Version().base_version`` and ``LegacyVersion().base_version`` to make it easy to get the public version without any pre or post release markers. * Support the update to PEP 440 which removed the implied ``!=V.*`` when using either ``>V`` or ``V`` or ````) operator. 14.3 - 2014-11-19 ~~~~~~~~~~~~~~~~~ * **BACKWARDS INCOMPATIBLE** Refactor specifier support so that it can sanely handle legacy specifiers as well as PEP 440 specifiers. * **BACKWARDS INCOMPATIBLE** Move the specifier support out of ``packaging.version`` into ``packaging.specifiers``. 14.2 - 2014-09-10 ~~~~~~~~~~~~~~~~~ * Add prerelease support to ``Specifier``. * Remove the ability to do ``item in Specifier()`` and replace it with ``Specifier().contains(item)`` in order to allow flags that signal if a prerelease should be accepted or not. * Add a method ``Specifier().filter()`` which will take an iterable and returns an iterable with items that do not match the specifier filtered out. 14.1 - 2014-09-08 ~~~~~~~~~~~~~~~~~ * Allow ``LegacyVersion`` and ``Version`` to be sorted together. * Add ``packaging.version.parse()`` to enable easily parsing a version string as either a ``Version`` or a ``LegacyVersion`` depending on it's PEP 440 validity. 14.0 - 2014-09-05 ~~~~~~~~~~~~~~~~~ * Initial release. .. _`master`: https://github.com/pypa/packaging/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/LICENSE0000644000000000000000000000030515133751156011325 0ustar00This software is made available under the terms of *either* of the licenses found in LICENSE.APACHE or LICENSE.BSD. Contributions to this software is made under the terms of *both* these licenses. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/LICENSE.APACHE0000644000000000000000000002367615133751156012265 0ustar00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/LICENSE.BSD0000644000000000000000000000250015133751156011733 0ustar00Copyright (c) Donald Stufft and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/README.rst0000644000000000000000000000406315133751156012014 0ustar00packaging ========= .. start-intro Reusable core utilities for various Python Packaging `interoperability specifications `_. This library provides utilities that implement the interoperability specifications 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 - Requirements - Tags - Metadata - Lockfiles - 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 ``#pypa`` on Freenode to ask questions or get involved. .. _`documentation`: https://packaging.pypa.io/ .. _`issue tracker`: https://github.com/pypa/packaging/issues Code of Conduct --------------- Everyone interacting in the packaging project's codebases, issue trackers, chat rooms, 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 as well as how to report a potential security issue. The documentation for this project 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`_ for recent changes and project history. .. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/Makefile0000644000000000000000000001271015133751156012713 0ustar00# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/packaging.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/packaging.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/packaging" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/packaging" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/changelog.rst0000644000000000000000000000003615133751156013732 0ustar00.. include:: ../CHANGELOG.rst ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/conf.py0000644000000000000000000000746115133751156012561 0ustar00# 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. import os # -- Project information loading ---------------------------------------------- ABOUT = {} _BASE_DIR = os.path.join(os.path.dirname(__file__), os.pardir) with open(os.path.join(_BASE_DIR, "src", "packaging", "__init__.py")) as f: exec(f.read(), ABOUT) # -- General configuration ---------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx_toolbox.more_autodoc.autotypeddict", ] # General information about the project. project = "Packaging" version = ABOUT["__version__"] release = ABOUT["__version__"] copyright = ABOUT["__copyright__"] # -- Options for HTML output -------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "furo" html_title = project html_theme_options = { "source_repository": "https://github.com/pypa/packaging", "source_branch": "main", "source_directory": "docs/", "footer_icons": [ { "name": "GitHub", "url": "https://github.com/pypa/packaging", "html": """ """, "class": "", }, ], } html_copy_source = False html_show_sourcelink = False # -- Options for autodoc ---------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#configuration autodoc_member_order = "bysource" autodoc_preserve_defaults = True # Automatically extract typehints when specified and place them in # descriptions of the relevant function/method. autodoc_typehints = "description" # Don't show class signature with the class' name. autodoc_class_signature = "separated" # -- Options for extlinks ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/extensions/extlinks.html#configuration extlinks = { "issue": ("https://github.com/pypa/packaging/issues/%s", "#%s"), "pull": ("https://github.com/pypa/packaging/pull/%s", "PR #%s"), } # -- Options for intersphinx ---------------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html#configuration intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "pypug": ("https://packaging.python.org/", None), } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/development/getting-started.rst0000644000000000000000000000454115133751156017437 0ustar00Getting started =============== Working on packaging requires the installation of a small number of development dependencies. To see what dependencies are required to run the tests manually, please look at the ``noxfile.py`` file. Running tests ~~~~~~~~~~~~~ The packaging unit tests are found in the ``tests/`` directory and are designed to be run using `pytest`_. `pytest`_ will discover the tests automatically, so all you have to do is: .. code-block:: console $ python -m pytest ... 29204 passed, 4 skipped, 1 xfailed in 83.98 seconds This runs the tests with the default Python interpreter. This also allows you to run select tests instead of the entire test suite. You can also verify that the tests pass on other supported Python interpreters. For this we use `nox`_, which will automatically create a `virtualenv`_ for each supported Python version and run the tests. For example: .. code-block:: console $ nox -s tests ... nox > Ran multiple sessions: nox > * tests-3.8: success nox > * tests-3.9: success nox > * tests-3.10: success nox > * tests-3.11: success nox > * tests-3.12: success nox > * tests-3.13: success nox > * tests-pypy3.8: skipped nox > * tests-pypy3.9: skipped nox > * tests-pypy3.10: skipped You may not have all the required Python versions installed, in which case you will see one or more ``InterpreterNotFound`` errors. Running linters ~~~~~~~~~~~~~~~ If you wish to run the linting rules, you may use `pre-commit`_ or run ``nox -s lint``. .. code-block:: console $ nox -s lint ... nox > Session lint was successful. Building documentation ~~~~~~~~~~~~~~~~~~~~~~ packaging documentation is stored in the ``docs/`` directory. It is written in `reStructured Text`_ and rendered using `Sphinx`_. Use `nox`_ to build the documentation. For example: .. code-block:: console $ nox -s docs ... nox > Session docs was successful. The HTML documentation index can now be found at ``docs/_build/html/index.html``. .. _`pytest`: https://pypi.org/project/pytest/ .. _`nox`: https://pypi.org/project/nox/ .. _`virtualenv`: https://pypi.org/project/virtualenv/ .. _`pip`: https://pypi.org/project/pip/ .. _`sphinx`: https://pypi.org/project/Sphinx/ .. _`reStructured Text`: https://www.sphinx-doc.org/en/master/usage/restructuredtext/ .. _`pre-commit`: https://pre-commit.com ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/development/index.rst0000644000000000000000000000103715133751156015436 0ustar00Development =========== As an open source project, packaging welcomes contributions of all forms. The sections below will help you get started. File bugs and feature requests on our issue tracker on `GitHub`_. If it is a bug check out `what to put in your bug report`_. .. toctree:: :maxdepth: 2 getting-started submitting-patches reviewing-patches release-process .. _`GitHub`: https://github.com/pypa/packaging .. _`what to put in your bug report`: https://www.contribution-guide.org/#what-to-put-in-your-bug-report ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/development/release-process.rst0000644000000000000000000000252115133751156017422 0ustar00Release Process =============== #. Checkout the current ``main`` branch. #. Install the latest ``nox``:: $ pip install nox #. Manually update the changelog to list all unreleased changes. Also verify that no new changes were added to a previous release in an earlier PR due to merge/rebase issues. #. Run the release automation with the required version number (YY.N):: $ nox -s release -- YY.N This creates a new tag for the release. It will tell you how to push the tag. #. Push the tag (command will be printed out in the last step). #. Run the 'Publish' manual GitHub workflow, specifying the Git tag's commit SHA. This will build and publish the package to PyPI. Publishing will wait for any `required approvals`_. #. Once it is approved and published to PyPI, add a `release on GitHub `__. Changelog can be auto-generated, but compare with the official changelog too. .. note:: Access needed for making the release are: - PyPI maintainer (or owner) access to ``packaging`` - push directly to the ``main`` branch on the source repository - push tags directly to the source repository .. _required approvals: https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-deployments/reviewing-deployments#approving-or-rejecting-a-job ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/development/reviewing-patches.rst0000644000000000000000000000176615133751156017764 0ustar00Reviewing and merging patches ============================= Everyone is encouraged to review open pull requests. We only ask that you try and think carefully, ask questions and are `excellent to one another`_. Code review is our opportunity to share knowledge, design ideas and make friends. When reviewing a patch try to keep each of these concepts in mind: Architecture ------------ * Is the proposed change being made in the correct place? Intent ------ * What is the change being proposed? * Do we want this feature or is the bug they're fixing really a bug? Implementation -------------- * Does the change do what the author claims? * Are there sufficient tests? * Has it been documented? * Will this change introduce new bugs? Grammar and style ----------------- These are small things that are not caught by the automated style checkers. * Does a variable need a better name? * Should this be a keyword argument? .. _`excellent to one another`: https://speakerdeck.com/ohrite/better-code-review ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/development/submitting-patches.rst0000644000000000000000000000477115133751156020151 0ustar00Submitting patches ================== * Always make a new branch for your work. * Patches should be small to facilitate easier review. `Studies have shown`_ that review quality falls off as patch size grows. Sometimes this will result in many small PRs to land a single large feature. * Larger changes should be discussed in a ticket before submission. * New features and significant bug fixes should be documented in the :doc:`/changelog`. * You must have legal permission to distribute any code you contribute and it must be available under both the BSD and Apache Software License Version 2.0 licenses. If you believe you've identified a security issue in packaging, please follow the directions on the :doc:`security page `. Code ---- This project's source is auto-formatted with |ruff|. You can check if your code meets our requirements by running our linters against it with ``nox -s lint`` or ``pre-commit run --all-files``. `Write comments as complete sentences.`_ Every code file must start with the boilerplate licensing notice: .. code-block:: python # 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. Tests ----- All code changes must be accompanied by unit tests with 100% code coverage (as measured by the combined metrics across our build matrix). Documentation ------------- All features should be documented with prose in the ``docs`` section. When referring to a hypothetical individual (such as "a person receiving an encrypted message") use gender neutral pronouns (they/them/their). Docstrings are typically only used when writing abstract classes, but should be written like this if required: .. code-block:: python def some_function(some_arg): """ Does some things. :param some_arg: Some argument. """ So, specifically: * Always use three double quotes. * Put the three double quotes on their own line. * No blank line at the end. * Use Sphinx parameter/attribute documentation `syntax`_. .. |ruff| replace:: ``ruff`` .. _ruff: https://astral.sh/ruff .. _`Write comments as complete sentences.`: https://nedbatchelder.com/blog/201401/comments_should_be_sentences.html .. _`syntax`: https://www.sphinx-doc.org/en/master/usage/restructuredtext/field-lists.html .. _`Studies have shown`: https://www.microsoft.com/en-us/research/publication/characteristics-of-useful-code-reviews-an-empirical-study-at-microsoft/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/index.rst0000644000000000000000000000116015133751156013111 0ustar00Welcome to packaging ==================== .. include:: ../README.rst :start-after: start-intro :end-before: end-intro Installation ------------ You can install packaging with ``pip``: .. code-block:: console $ pip install packaging The ``packaging`` library uses calendar-based versioning (``YY.N``). .. toctree:: :maxdepth: 1 :caption: API Documentation :hidden: version specifiers markers licenses requirements metadata tags pylock utils .. toctree:: :maxdepth: 2 :caption: Project :hidden: development/index security changelog ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/licenses.rst0000644000000000000000000000331715133751156013615 0ustar00Licenses ========= .. currentmodule:: packaging.licenses Helper for canonicalizing SPDX `License-Expression metadata `__ as `defined in PEP 639 `__. Reference --------- .. class:: NormalizedLicenseExpression A :class:`typing.NewType` of :class:`str`, representing a normalized License-Expression. .. exception:: InvalidLicenseExpression Raised when a License-Expression is invalid. .. function:: canonicalize_license_expression(raw_license_expression) 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' ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/markers.rst0000644000000000000000000001041215133751156013446 0ustar00Markers ======= .. currentmodule:: packaging.markers One extra requirement of dealing with dependencies is the ability to specify if it is required depending on the operating system or Python version in use. The :ref:`specification of dependency specifiers ` defines the scheme which has been implemented by this module. Usage ----- .. doctest:: >>> from packaging.markers import Marker, UndefinedEnvironmentName >>> marker = Marker("python_version>'2'") >>> marker "2"')> >>> # We can evaluate the marker to see if it is satisfied >>> marker.evaluate() True >>> # We can also override the environment >>> env = {'python_version': '1.5'} >>> marker.evaluate(environment=env) False >>> # Multiple markers can be ANDed >>> and_marker = Marker("os_name=='a' and os_name=='b'") >>> and_marker >>> # Multiple markers can be ORed >>> or_marker = Marker("os_name=='a' or os_name=='b'") >>> or_marker >>> # Markers can be also used with extras, to pull in dependencies if >>> # a certain extra is being installed >>> extra = Marker('extra == "bar"') >>> # You can do simple comparisons between marker objects: >>> Marker("python_version > '3.6'") == Marker("python_version > '3.6'") True >>> # You can also perform simple comparisons between sets of markers: >>> markers1 = {Marker("python_version > '3.6'"), Marker('os_name == "unix"')} >>> markers2 = {Marker('os_name == "unix"'), Marker("python_version > '3.6'")} >>> markers1 == markers2 True Reference --------- .. class:: Marker(markers) This class abstracts handling markers for dependencies of a project. It can be passed a single marker or multiple markers that are ANDed or ORed together. Each marker will be parsed according to the specification. :param str markers: The string representation of a marker or markers. :raises InvalidMarker: If the given ``markers`` are not parseable, then this exception will be raised. .. method:: evaluate(environment=None, context='metadata') Evaluate the marker given the context of the current Python process. :param dict environment: A dictionary containing keys and values to override the detected environment. :param EvaluateContext context: A string representing the context in which the marker is evaluated. :raises: UndefinedComparison: If the marker uses a comparison on strings which are not valid versions per the :ref:`specification of version specifiers `. :raises: UndefinedEnvironmentName: If the marker accesses a value that isn't present inside of the environment dictionary. :rtype: bool .. autotypeddict:: packaging.markers.Environment A dictionary that represents a Python environment as captured by :func:`default_environment`. .. py:data:: packaging.markers.EvaluateContext A ``typing.Literal`` enumerating valid values for the ``context`` passed to ``Marker.evaluate``, namely: * "metadata" (for core metadata; default) * "lock_file" (for lock files) * "requirement" (i.e. all other situations) .. function:: default_environment() Returns a dictionary representing the current Python process. This is the base environment that is used when evaluating markers in :meth:`Marker.evaluate`. :rtype: Environment .. exception:: InvalidMarker Raised when attempting to create a :class:`Marker` with a string that does not conform to the specification. .. exception:: UndefinedComparison Raised when attempting to evaluate a :class:`Marker` with a comparison operator against values that are not valid versions per the :ref:`specification of version specifiers `. .. exception:: UndefinedEnvironmentName Raised when attempting to evaluate a :class:`Marker` with a value that is missing from the evaluation environment. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/metadata.rst0000644000000000000000000000302215133751156013561 0ustar00Metadata ======== .. currentmodule:: packaging.markers Both `source distributions`_ and `binary distributions`_ (*sdists* and *wheels*, respectively) contain files recording the `core metadata`_ for the distribution. This information is used for everything from recording the name of the distribution to the installation dependencies. Usage ----- .. doctest:: >>> from packaging.metadata import parse_email >>> metadata = "Metadata-Version: 2.3\nName: packaging\nVersion: 24.0" >>> raw, unparsed = parse_email(metadata) >>> raw["metadata_version"] '2.3' >>> raw["name"] 'packaging' >>> raw["version"] '24.0' >>> from packaging.metadata import Metadata >>> parsed = Metadata.from_raw(raw) >>> parsed.name 'packaging' >>> parsed.version Reference --------- High Level Interface '''''''''''''''''''' .. autoclass:: packaging.metadata.Metadata :members: Low Level Interface ''''''''''''''''''' .. autoclass:: packaging.metadata.RawMetadata :members: .. autofunction:: packaging.metadata.parse_email Exceptions '''''''''' .. autoclass:: packaging.metadata.InvalidMetadata :members: .. autoclass:: packaging.metadata.ExceptionGroup :members: .. _source distributions: https://packaging.python.org/en/latest/specifications/source-distribution-format/ .. _binary distributions: https://packaging.python.org/en/latest/specifications/binary-distribution-format/ .. _core metadata: https://packaging.python.org/en/latest/specifications/core-metadata/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/pylock.rst0000644000000000000000000000422715133751156013312 0ustar00Lock Files ========== .. currentmodule:: packaging.pylock Parse and validate `pylock.toml files `_. Usage ----- .. code-block:: python import tomllib from pathlib import Path from packaging.pylock import Package, PackageWheel, Pylock from packaging.utils import NormalizedName from packaging.version import Version # validate a pylock file name assert is_valid_pylock_path(Path("pylock.example.toml")) # parse and validate pylock file toml_dict = tomllib.loads(Path("pylock.toml").read_text(encoding="utf-8")) pylock = PyLock.from_dict(toml_dict) # the resulting pylock object is validated against the specification, # else a PylockValidationError is raised # generate a pylock file pylock = Pylock( lock_version=Version("1.0"), created_by="some_tool", packages=[ Package( name=NormalizedName("example-package"), version=Version("1.0.0"), wheels=[ PackageWheel( url="https://example.com/example_package-1.0.0-py3-none-any.whl", hashes={"sha256": "0fd.."}, ) ], ) ], ) toml_dict = pylock.to_dict() # use a third-party library to serialize to TOML # you can validate a manually constructed Pylock class pylock.validate() Reference --------- .. autofunction:: is_valid_pylock_path The following frozen keyword-only dataclasses are used to represent the structure of a pylock file. The attributes correspond to the fields in the pylock file specification. .. autoclass:: Pylock :members: from_dict, to_dict, validate :exclude-members: __init__, __new__ .. class:: Package .. class:: PackageWheel .. class:: PackageSdist .. class:: PackageArchive .. class:: PackageVcs .. class:: PackageDirectory The following exception may be raised by this module: .. autoexception:: PylockValidationError :exclude-members: __init__, __new__ .. autoexception:: PylockUnsupportedVersionError :exclude-members: __init__, __new__ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/requirements.rst0000644000000000000000000000612215133751156014530 0ustar00Requirements ============ .. currentmodule:: packaging.requirements Parse a given requirements line for specifying dependencies of a Python project, using the :ref:`specification of dependency specifiers `, which defines the scheme that has been implemented by this module. Usage ----- .. doctest:: >>> from packaging.requirements import Requirement >>> simple_req = Requirement("name") >>> simple_req >>> simple_req.name 'name' >>> simple_req.url is None True >>> simple_req.extras set() >>> simple_req.specifier >>> simple_req.marker is None True >>> # Requirements can be specified with extras, specifiers and markers >>> req = Requirement('name[foo]>=2,<3; python_version>"2.0"') >>> req.name 'name' >>> req.extras {'foo'} >>> req.specifier =2')> >>> req.marker "2.0"')> >>> # Requirements can also be specified with a URL, but may not specify >>> # a version. >>> url_req = Requirement('name @ https://github.com/pypa ;os_name=="a"') >>> url_req.name 'name' >>> url_req.url 'https://github.com/pypa' >>> url_req.extras set() >>> url_req.marker >>> # You can do simple comparisons between requirement objects: >>> Requirement("packaging") == Requirement("packaging") True >>> # You can also perform simple comparisons between sets of requirements: >>> requirements1 = {Requirement("packaging"), Requirement("pip")} >>> requirements2 = {Requirement("pip"), Requirement("packaging")} >>> requirements1 == requirements2 True .. versionchanged:: 23.2 When a requirement is specified with a URL, the :class:`Requirement` class used to check the URL and reject values containing invalid scheme and netloc combinations. This is no longer performed since the specification does not have such rules, and the check incorrectly disallows valid requirement strings from being parsed. Reference --------- .. class:: Requirement(requirement) This class abstracts handling the details of a requirement for a project. Each requirement will be parsed according to the specification. :param str requirement: The string representation of a requirement. :raises InvalidRequirement: If the given ``requirement`` is not parseable, then this exception will be raised. .. attribute:: name The name of the requirement. .. attribute:: url The URL, if any where to download the requirement from. Can be None. .. attribute:: extras A set of extras that the requirement specifies. .. attribute:: specifier A :class:`~.SpecifierSet` of the version specified by the requirement. .. attribute:: marker A :class:`~.Marker` of the marker for the requirement. Can be None. .. exception:: InvalidRequirement Raised when attempting to create a :class:`Requirement` with a string that does not conform to the specification. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/requirements.txt0000644000000000000000000000010515133751156014532 0ustar00furo sphinx-toolbox typing-extensions>=4.1.0; python_version < "3.9" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/security.rst0000644000000000000000000000125515133751156013656 0ustar00Security ======== We take the security of packaging seriously. If you believe you've identified a security issue in it, DO NOT report the issue in any public forum, including (but not limited to): - GitHub issue tracker - Official or unofficial chat channels - Official or unofficial mailing lists Please report your issue to ``security@python.org``. Messages may be optionally encrypted with GPG using key fingerprints available at the `Python Security page `_. Once you've submitted an issue via email, you should receive an acknowledgment within 48 hours, and depending on the action to be taken, you may receive further follow-up emails. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8153684 packaging-26.0/docs/specifiers.rst0000644000000000000000000000347315133751156014147 0ustar00Specifiers ========== A core requirement of dealing with dependencies is the ability to specify what versions of a dependency are acceptable for you. See `Version Specifiers Specification`_ for more details on the exact format implemented in this module, for use in Python Packaging tooling. .. _Version Specifiers Specification: https://packaging.python.org/en/latest/specifications/version-specifiers/ Usage ----- .. doctest:: >>> from packaging.specifiers import SpecifierSet >>> from packaging.version import Version >>> spec1 = SpecifierSet("~=1.0") >>> spec1 >>> spec2 = SpecifierSet(">=1.0") >>> spec2 =1.0')> >>> # We can combine specifiers >>> combined_spec = spec1 & spec2 >>> combined_spec =1.0,~=1.0')> >>> # We can also implicitly combine a string specifier >>> combined_spec &= "!=1.1" >>> combined_spec =1.0,~=1.0')> >>> # We can iterate over the SpecifierSet to recover the >>> # individual specifiers >>> sorted(combined_spec, key=str) [, =1.0')>, ] >>> # Create a few versions to check for contains. >>> v1 = Version("1.0a5") >>> v2 = Version("1.0") >>> # We can check a version object to see if it falls within a specifier >>> v1 in combined_spec False >>> v2 in combined_spec True >>> # We can even do the same with a string based version >>> "1.4" in combined_spec True >>> # Finally we can filter a list of versions to get only those which are >>> # contained within our specifier. >>> list(combined_spec.filter([v1, v2, "1.4"])) [, '1.4'] Reference --------- .. automodule:: packaging.specifiers :members: :special-members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/docs/tags.rst0000644000000000000000000002325015133751156012744 0ustar00Tags ==== .. currentmodule:: packaging.tags Wheels encode the Python interpreter, ABI, and platform that they support in their filenames using `platform compatibility tags`_. This module provides support for both parsing these tags as well as discovering what tags the running Python interpreter supports. Usage ----- .. doctest:: >>> from packaging.tags import Tag, sys_tags >>> import sys >>> looking_for = Tag("py{major}".format(major=sys.version_info.major), "none", "any") >>> supported_tags = list(sys_tags()) >>> looking_for in supported_tags True >>> really_old = Tag("py1", "none", "any") >>> wheels = {really_old, looking_for} >>> best_wheel = None >>> for supported_tag in supported_tags: ... for wheel_tag in wheels: ... if supported_tag == wheel_tag: ... best_wheel = wheel_tag ... break >>> best_wheel == looking_for True Reference --------- High Level Interface '''''''''''''''''''' The following functions are the main interface to the library, and are typically the only items that applications should need to reference, in order to parse and check tags. .. class:: Tag(interpreter, abi, platform) A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported. :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"``. .. attribute:: interpreter The interpreter name. .. attribute:: abi The supported ABI. .. attribute:: platform The OS/platform. .. function:: parse_tag(tag) Parses the provided ``tag`` into a set 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. :param str tag: The tag to parse, e.g. ``"py3-none-any"``. .. function:: sys_tags(*, warn=False) Yields the tags 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`). Low Level Interface ''''''''''''''''''' The following functions are low-level implementation details. They should typically not be needed in application code, unless the application has specialised requirements (for example, constructing sets of supported tags for environments other than the running interpreter). These functions capture the precise details of which environments support which tags. That information is not defined in the compatibility tag standards but is noted as being up to the implementation to provide. .. attribute:: INTERPRETER_SHORT_NAMES A dictionary mapping interpreter names to their `abbreviation codes`_ (e.g. ``"cpython"`` is ``"cp"``). All interpreter names are lower-case. .. function:: interpreter_name() Returns the running interpreter's name. This typically acts as the prefix to the :attr:`~Tag.interpreter` tag. .. function:: interpreter_version(*, warn=False) Returns the running interpreter's version. This typically acts as the suffix to the :attr:`~Tag.interpreter` tag. .. function:: mac_platforms(version=None, arch=None) Yields the :attr:`~Tag.platform` tags for macOS. :param tuple version: A two-item tuple presenting 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 .. function:: ios_platforms(version=None, multiarch=None) 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 ``x84_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. .. function:: android_platforms(api_level=None, abi=None) 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 `__ to return. Defaults to the current system's version, as returned by ``platform.android_ver``. :param str abi: The `Android ABI `__, 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. .. function:: platform_tags(version=None, arch=None) Yields the :attr:`~Tag.platform` tags for the running interpreter. .. function:: compatible_tags(python_version=None, interpreter=None, platforms=None) Yields the tags for an interpreter compatible with the Python version specified by ``python_version``. The specific tags generated are: - ``py*-none-`` - ``-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. .. function:: cpython_tags(python_version=None, abis=None, platforms=None, *, warn=False) Yields the tags for the CPython interpreter. The specific tags generated are: - ``cp--`` - ``cp-abi3-`` - ``cp-none-`` - ``cp-abi3-`` 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. :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``. .. function:: generic_tags(interpreter=None, abis=None, platforms=None, *, warn=False) 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: - ``--`` 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``. .. _`abbreviation codes`: https://www.python.org/dev/peps/pep-0425/#python-tag .. _`compressed tag set`: https://www.python.org/dev/peps/pep-0425/#compressed-tag-sets .. _`platform compatibility tags`: https://packaging.python.org/specifications/platform-compatibility-tags/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/docs/utils.rst0000644000000000000000000001117415133751156013150 0ustar00Utilities ========= .. currentmodule:: packaging.utils A set of small, helper utilities for dealing with Python packages. Reference --------- .. class:: NormalizedName A :class:`typing.NewType` of :class:`str`, representing a normalized name. .. function:: canonicalize_name(name, validate=False) 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. .. doctest:: >>> from packaging.utils import canonicalize_name >>> canonicalize_name("Django") 'django' >>> canonicalize_name("oslo.concurrency") 'oslo-concurrency' >>> canonicalize_name("requests") 'requests' .. function:: is_normalized_name(name) Check if a name is already normalized (i.e. :func:`canonicalize_name` would roundtrip to the same value). :param str name: The name to check. .. doctest:: >>> from packaging.utils import is_normalized_name >>> is_normalized_name("requests") True >>> is_normalized_name("Django") False .. function:: canonicalize_version(version, strip_trailing_zero=True) 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. :param str version: The version to normalize. .. doctest:: >>> from packaging.utils import canonicalize_version >>> canonicalize_version('1.4.0.0.0') '1.4' .. function:: parse_wheel_filename(filename) 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). :param str filename: The name of the wheel file. :raises InvalidWheelFilename: If the filename in question does not follow the :ref:`wheel specification `. .. doctest:: >>> 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 .. function:: parse_sdist_filename(filename) 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``), or if it does not contain a dash separating the name and the version of the distribution. .. doctest:: >>> 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 .. exception:: InvalidName Raised when a distribution name is invalid. .. exception:: InvalidWheelFilename Raised when a file name for a wheel is invalid. .. exception:: InvalidSdistFilename Raised when a source distribution file name is considered invalid. .. _Source distribution format: https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-name ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/docs/version.rst0000644000000000000000000000217415133751156013475 0ustar00Version Handling ================ A core requirement of dealing with packages is the ability to work with versions. See `Version Specifiers Specification`_ for more details on the exact format implemented in this module, for use in Python Packaging tooling. .. _Version Specifiers Specification: https://packaging.python.org/en/latest/specifications/version-specifiers/ Usage ----- .. doctest:: >>> from packaging.version import Version, parse >>> v1 = parse("1.0a5") >>> v2 = Version("1.0") >>> v1 >>> v2 >>> v1 < v2 True >>> v1.epoch 0 >>> v1.release (1, 0) >>> v1.pre ('a', 5) >>> v1.is_prerelease True >>> v2.is_prerelease False >>> Version("french toast") Traceback (most recent call last): ... InvalidVersion: Invalid version: 'french toast' >>> Version("1.0").post >>> Version("1.0").is_postrelease False >>> Version("1.0.post0").post 0 >>> Version("1.0.post0").is_postrelease True Reference --------- .. automodule:: packaging.version :members: :special-members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/pyproject.toml0000644000000000000000000001004415133751156013235 0ustar00[build-system] requires = ["flit_core >=3.12"] build-backend = "flit_core.buildapi" [project] name = "packaging" description = "Core utilities for Python packages" dynamic = ["version"] license = "Apache-2.0 OR BSD-2-Clause" readme = "README.rst" requires-python = ">=3.8" authors = [{name = "Donald Stufft", email = "donald@stufft.io"}] classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Typing :: Typed", ] dependencies = [] [project.urls] Documentation = "https://packaging.pypa.io/" Source = "https://github.com/pypa/packaging" [dependency-groups] test = [ "coverage[toml]>=7.2.0", "pip>=21.1", "pretend", "pytest>=6.2.0", "tomli; python_version<'3.11'", "tomli_w", ] dev = [{ include-group = "test" }] [tool.flit.sdist] include = ["tests/", "docs/", "CHANGELOG.rst"] exclude = ["docs/_build", "tests/manylinux/build-hello-world.sh", "tests/musllinux/build.sh", "tests/hello-world.c", "tests/__pycache__", "build/__pycache__"] [tool.typos.default.extend-identifiers] iMatix = "iMatix" ANDed = "ANDed" ORed = "ORed" [tool.typos.default.extend-words] dynamc = "dynamc" notin = "notin" nd = "nd" tou = "tou" [tool.coverage.run] branch = true source_pkgs = ["packaging"] [tool.coverage.report] show_missing = true fail_under = 100 exclude_also = ["@abc.abstractmethod", "@abc.abstractproperty", "if typing.TYPE_CHECKING:"] [tool.pytest.ini_options] minversion = "6.2" addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config"] xfail_strict = true filterwarnings = ["error"] log_level = "INFO" testpaths = ["tests"] [tool.mypy] strict = true enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] warn_unused_ignores = true python_version = "3.8" files = ["src", "tests", "noxfile.py"] [[tool.mypy.overrides]] module = ["_manylinux", "pretend", "progress.*", "pkg_resources"] ignore_missing_imports = true [tool.ruff] extend-exclude = [ "src/packaging/licenses/_spdx.py" ] show-fixes = true [tool.ruff.lint] select = ["ALL"] ignore = [ "A002", # function args shadowing builtins is fine "C9", # complexity "COM812", # trailing commas teach the formatter "D", # doc formatting "EM", # flake8-errmsg "ERA", # commented out code "FBT", # boolean positional args (existing API) "FIX", # has todos "N818", # exceptions must end in "*Error" "PLR09", # too many ... "PLR2004", # magic value in comparison "PLW0127", # duplicate of F821 "PTH", # pathlib "RET505", # unused else/elif after return "RET506", # unused else/elif after raise "RET507", # unused else/elif after continue "RET508", # unused else/elif after break "S101", # assert is used by mypy and pytest "S105", # the name token doesn't mean it's a password "S603", # check for untrusted input "SIM103", # returning negated value directly not ideal for long chain "SIM105", # try/except is faster than contextlib.suppress "SLF001", # private member access "TD", # todo format "TRY003", # long messages outside exception class ] flake8-comprehensions.allow-dict-calls-with-keyword-arguments = true flake8-unused-arguments.ignore-variadic-names = true [tool.ruff.lint.per-file-ignores] "tests/test_*.py" = ["PYI024", "PLR", "SIM201", "T20", "S301"] "tasks/check.py" = ["UP032", "T20"] "tests/test_requirements.py" = ["UP032"] "src/packaging/_musllinux.py" = ["T20"] "docs/conf.py" = ["INP001", "S", "A001"] "noxfile.py" = ["T20", "S"] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/__init__.py0000644000000000000000000000075615133751156015156 0ustar00# 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.0" __author__ = "Donald Stufft and individual contributors" __email__ = "donald@stufft.io" __license__ = "BSD-2-Clause or Apache-2.0" __copyright__ = f"2014 {__author__}" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/_elffile.py0000644000000000000000000000621315133751156015156 0ustar00""" ELF file parser. This provides a class ``ELFFile`` that parses an ELF executable in a similar interface to ``ZipFile``. Only the read interface is implemented. ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html """ from __future__ import annotations import enum import os import struct from 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 AArc64 = 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 program header. # p_fmt: Format for section 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 MSB. (2, 1): ("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 section. self._e_phnum, # Number of sections. ) = 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 None ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/_manylinux.py0000644000000000000000000002252715133751156015602 0ustar00from __future__ import annotations import collections import contextlib import functools import os import re import sys import warnings from typing import Generator, Iterator, NamedTuple, Sequence from ._elffile import EIClass, EIData, ELFFile, EMachine EF_ARM_ABIMASK = 0xFF000000 EF_ARM_ABI_VER5 = 0x05000000 EF_ARM_ABI_FLOAT_HARD = 0x00000400 _ALLOWED_ARCHS = { "x86_64", "aarch64", "ppc64", "ppc64le", "s390x", "loongarch64", "riscv64", } # `os.PathLike` not a generic type until Python 3.9, so sticking with `str` # as the type for `path` until then. @contextlib.contextmanager def _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 version_str: str = gnu_get_libc_version() # py2 / py3 compatibility: if not isinstance(version_str, str): 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[0-9]+)\.(?P[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_cache def _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 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. try: import _manylinux # noqa: PLC0415 except ImportError: return True if hasattr(_manylinux, "manylinux_compatible"): result = _manylinux.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, "manylinux1_compatible"): return bool(_manylinux.manylinux1_compatible) if version == _GLibCVersion(2, 12) and hasattr( _manylinux, "manylinux2010_compatible" ): return bool(_manylinux.manylinux2010_compatible) if version == _GLibCVersion(2, 17) and hasattr( _manylinux, "manylinux2014_compatible" ): return bool(_manylinux.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}" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/_musllinux.py0000644000000000000000000000522315133751156015610 0ustar00"""PEP 656 support. This module implements logic to detect if the currently running Python is linked against musl, and what musl version is used. """ from __future__ import annotations import functools import re import subprocess import sys from typing import Iterator, NamedTuple, Sequence from ._elffile import ELFFile 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_cache def _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 ") ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/_parser.py0000644000000000000000000002442615133751156015052 0ustar00"""Handwritten parser of dependency specifiers. The docstring for each __parse_* function contains EBNF-inspired grammar representing the implementation. """ from __future__ import annotations import ast from typing import List, Literal, NamedTuple, Sequence, Tuple, Union from ._tokenizer import DEFAULT_RULES, 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 class Variable(Node): __slots__ = () def serialize(self) -> str: return str(self) class Value(Node): __slots__ = () def serialize(self) -> str: return f'"{self}"' 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 parsed_specifiers += tokenizer.read().text if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): tokenizer.raise_syntax_error( ".* suffix can only be used with `==` or `!=` operators", 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"): return process_python_str(tokenizer.read().text) 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" ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/_structures.py0000644000000000000000000000275215133751156015777 0ustar00# 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. import typing @typing.final class InfinityType: __slots__ = () def __repr__(self) -> str: return "Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return False def __le__(self, other: object) -> bool: return False def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) def __gt__(self, other: object) -> bool: return True def __ge__(self, other: object) -> bool: return True def __neg__(self: object) -> "NegativeInfinityType": return NegativeInfinity Infinity = InfinityType() @typing.final class NegativeInfinityType: __slots__ = () def __repr__(self) -> str: return "-Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return True def __le__(self, other: object) -> bool: return True def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) def __gt__(self, other: object) -> bool: return False def __ge__(self, other: object) -> bool: return False def __neg__(self: object) -> InfinityType: return Infinity NegativeInfinity = NegativeInfinityType() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/_tokenizer.py0000644000000000000000000001245515133751156015567 0ustar00from __future__ import annotations import contextlib import re from dataclasses import dataclass from typing import Generator, Mapping, NoReturn from .specifiers import Specifier @dataclass class Token: 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._operator_regex_str + Specifier._version_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"$"), } class Tokenizer: """Context-sensitive token parsing. Provides methods to examine the input stream to check whether the next token matches. """ 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 *not* read. """ 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() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8163686 packaging-26.0/src/packaging/licenses/__init__.py0000644000000000000000000001327315133751156016761 0ustar00####################################################################################### # # Adapted from: # https://github.com/pypa/hatch/blob/5352e44/backend/src/hatchling/licenses/parse.py # # MIT License # # Copyright (c) 2017-present Ofek Lev # # 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 re from typing import NewType, cast from ._spdx import EXCEPTIONS, LICENSES __all__ = [ "InvalidLicenseExpression", "NormalizedLicenseExpression", "canonicalize_license_expression", ] license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$") NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str) class InvalidLicenseExpression(ValueError): """Raised when a license-expression string is invalid >>> canonicalize_license_expression("invalid") Traceback (most recent call last): ... packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid' """ def canonicalize_license_expression( raw_license_expression: str, ) -> NormalizedLicenseExpression: 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 = [] for token in tokens: if token in {"or", "and", "with", "(", ")"}: normalized_tokens.append(token.upper()) 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"]) else: if token.endswith("+"): final_token = token[:-1] suffix = "+" else: final_token = token suffix = "" if final_token.startswith("licenseref-"): if not license_ref_allowed.match(final_token): message = f"Invalid licenseref: {final_token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(license_refs[final_token] + suffix) 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) normalized_expression = " ".join(normalized_tokens) return cast( "NormalizedLicenseExpression", normalized_expression.replace("( ", "(").replace(" )", ")"), ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/licenses/_spdx.py0000644000000000000000000014366215133751156016345 0ustar00 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}, } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/markers.py0000644000000000000000000003074315133751156015062 0ustar00# 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 operator import os import platform import sys from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast from ._parser import MarkerAtom, MarkerList, Op, Value, Variable from ._parser import parse_marker as _parse_marker from ._tokenizer import ParserSyntaxError from .specifiers import InvalidSpecifier, Specifier from .utils import canonicalize_name __all__ = [ "Environment", "EvaluateContext", "InvalidMarker", "Marker", "UndefinedComparison", "UndefinedEnvironmentName", "default_environment", ] Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] EvaluateContext = Literal["metadata", "lock_file", "requirement"] MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} MARKERS_REQUIRING_VERSION = { "implementation_version", "platform_release", "python_full_version", "python_version", } class InvalidMarker(ValueError): """ An invalid marker was found, users should refer to PEP 508. """ class UndefinedComparison(ValueError): """ An invalid operation was attempted on a value that doesn't support it. """ class UndefinedEnvironmentName(ValueError): """ A name was attempted to be used that does not exist inside of the environment. """ class Environment(TypedDict): 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 not isinstance(result, tuple): return result lhs, op, rhs = result if isinstance(lhs, Variable) and lhs.value == "extra": normalized_extra = canonicalize_name(rhs.value) rhs = Value(normalized_extra) elif isinstance(rhs, Variable) and rhs.value == "extra": normalized_extra = canonicalize_name(lhs.value) lhs = Value(normalized_extra) 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)) # Sometimes we have a structure like [[...]] which is a single item list # where the single item is itself it's own list. In that case we want skip # the rest of this function so that we don't get extraneous () on the # outside. if ( isinstance(marker, list) and len(marker) == 1 and isinstance(marker[0], (list, tuple)) ): return _format_marker(marker[0]) 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 _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 = environment[environment_key] rhs_value = rhs.value else: lhs_value = lhs.value environment_key = rhs.value rhs_value = environment[environment_key] assert isinstance(lhs_value, str), "lhs must be a string" 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 def default_environment() -> Environment: 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, } class Marker: 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: # [ # (, ')>, ), # 'and', # [ # (, , ), # 'or', # (, , ) # ] # ] except ParserSyntaxError as e: raise InvalidMarker(str(e)) from e def __str__(self) -> str: return _format_marker(self._markers) def __repr__(self) -> str: return f"<{self.__class__.__name__}('{self}')>" 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 evaluate( self, environment: Mapping[str, str | AbstractSet[str]] | None = None, context: EvaluateContext = "metadata", ) -> bool: """Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The *context* parameter specifies what context the markers are being evaluated for, which influences what markers are considered valid. Acceptable values are "metadata" (for core metadata; default), "lock_file", and "requirement" (i.e. all other situations). The environment is determined from the current Python process. """ current_environment = cast( "dict[str, str | AbstractSet[str]]", default_environment() ) if context == "lock_file": current_environment.update( extras=frozenset(), dependency_groups=frozenset() ) elif context == "metadata": current_environment["extra"] = "" if environment is not None: current_environment.update(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 _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"]) if python_full_version.endswith("+"): env["python_full_version"] = f"{python_full_version}local" return env ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/metadata.py0000644000000000000000000011470015133751156015172 0ustar00from __future__ import annotations import email.feedparser import email.header import email.message import email.parser import email.policy import keyword import pathlib import sys import typing from typing import ( Any, Callable, Generic, Literal, TypedDict, cast, ) from . import licenses, requirements, specifiers, utils from . import version as version_module if typing.TYPE_CHECKING: from .licenses import NormalizedLicenseExpression T = typing.TypeVar("T") if sys.version_info >= (3, 11): # pragma: no cover ExceptionGroup = ExceptionGroup # noqa: F821 else: # 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})" class InvalidMetadata(ValueError): """A metadata field contains invalid data.""" 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) # 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. """ # 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 license_files: list[str] # Metadata 2.5 - PEP 794 import_names: list[str] import_namespaces: list[str] # '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() assert isinstance(payload, str) 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) assert isinstance(bpayload, bytes) 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()} # This class is for writing RFC822 messages class 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. """ 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 = value.replace("\n", "\n" + " " * size) return (name, value) # This class is for writing RFC822 messages class 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()`. """ 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"] _MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"] _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.format_map({"field": repr(self.raw_name)}) ) 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("{field} 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 {{field}}", cause=exc ) from exc else: return value def _process_version(self, value: str) -> version_module.Version: if not value: raise self._invalid_metadata("{field} 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 {{field}}", cause=exc ) from exc def _process_summary(self, value: str) -> str: """Check the field contains no newlines.""" if "\n" in value: raise self._invalid_metadata("{field} 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"} message = email.message.EmailMessage() message["content-type"] = value content_type, parameters = ( # Defaults to `text/plain` if parsing failed. message.get_content_type().lower(), message["content-type"].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( f"{{field}} must be one of {list(content_types)}, not {value!r}" ) charset = parameters.get("charset", "UTF-8") if charset != "UTF-8": raise self._invalid_metadata( f"{{field}} can only specify the UTF-8 charset, not {list(charset)}" ) 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 {{field}} are {list(markdown_variants)}, " f"not {variant!r}", ) return value def _process_dynamic(self, value: list[str]) -> list[str]: for dynamic_field in map(str.lower, value): 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 list(map(str.lower, value)) 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 {{field}}", 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 {{field}}", 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 {{field}}", 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 {{field}}", 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 {{field}}, " "parent directory indicators are not allowed" ) if "*" in path: raise self._invalid_metadata( f"{path!r} is invalid for {{field}}, 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 {{field}}, paths must be relative" ) if pathlib.PureWindowsPath(path).as_posix() != path: raise self._invalid_metadata( f"{path!r} is invalid for {{field}}, 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 {{field}}; " f"{identifier!r} is not a valid identifier" ) elif keyword.iskeyword(identifier): raise self._invalid_metadata( f"{name!r} is invalid for {{field}}; " f"{identifier!r} is a keyword" ) if semicolon and private.lstrip() != "private": raise self._invalid_metadata( f"{import_name!r} is invalid for {{field}}; " "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). """ _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. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ ins = cls() ins._raw = data.copy() # Mutations occur due to caching enriched values. if validate: exceptions: list[Exception] = [] try: metadata_version = ins.metadata_version metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) except InvalidMetadata as metadata_version_exc: exceptions.append(metadata_version_exc) metadata_version = None # 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}") exceptions.append(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}", ) exceptions.append(exc) continue getattr(ins, key) except InvalidMetadata as exc: exceptions.append(exc) if exceptions: raise ExceptionGroup("invalid metadata", exceptions) 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: exceptions: list[Exception] = [] 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}" exceptions.append(InvalidMetadata(unparsed_key, message)) if exceptions: raise ExceptionGroup("unparsed", exceptions) try: return cls.from_raw(raw, validate=validate) except ExceptionGroup as exc_group: raise ExceptionGroup( "invalid or unparsed metadata", exc_group.exceptions ) from None 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_module.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`""" license_files: _Validator[list[str] | None] = _Validator(added="2.4") """:external:ref:`core-metadata-license-file`""" 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`""" import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") """:external:ref:`core-metadata-import-namespace`""" 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. """ 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) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/py.typed0000644000000000000000000000000015133751156014522 0ustar00././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/pylock.py0000644000000000000000000005401115133751156014711 0ustar00from __future__ import annotations import dataclasses import logging import re from collections.abc import Mapping, Sequence from dataclasses import dataclass from datetime import datetime from typing import ( TYPE_CHECKING, Any, Callable, Protocol, TypeVar, ) from .markers import Marker from .specifiers import SpecifierSet from .utils import NormalizedName, is_normalized_name from .version import Version if TYPE_CHECKING: # pragma: no cover from pathlib import Path from typing_extensions import Self _logger = logging.getLogger(__name__) __all__ = [ "Package", "PackageArchive", "PackageDirectory", "PackageSdist", "PackageVcs", "PackageWheel", "Pylock", "PylockUnsupportedVersionError", "PylockValidationError", "is_valid_pylock_path", ] _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): 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 _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`.""" @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 @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 @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" ) 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()) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/requirements.py0000644000000000000000000000546615133751156016145 0ustar00# 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 Iterator from ._parser import parse_requirement as _parse_requirement from ._tokenizer import ParserSyntaxError from .markers import Marker, _normalize_extra_values from .specifiers import SpecifierSet from .utils import canonicalize_name class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ 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. """ # 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? 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 or []) self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) 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 __str__(self) -> str: return "".join(self._iter_parts(self.name)) def __repr__(self) -> str: return f"<{self.__class__.__name__}('{self}')>" def __hash__(self) -> int: return hash(tuple(self._iter_parts(canonicalize_name(self.name)))) def __eq__(self, other: object) -> bool: if not isinstance(other, Requirement): return NotImplemented 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 ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/specifiers.py0000644000000000000000000011753515133751156015557 0ustar00# 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 abc import itertools import re from typing import Callable, Final, Iterable, Iterator, TypeVar, Union from .utils import canonicalize_version from .version import InvalidVersion, Version UnparsedVersion = Union[Version, str] UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) CallableOperator = Callable[[Version, str], bool] def _coerce_version(version: UnparsedVersion) -> Version | None: if not isinstance(version, Version): try: version = Version(version) except InvalidVersion: return None return version def _public_version(version: Version) -> Version: return version.__replace__(local=None) def _base_version(version: Version) -> Version: return version.__replace__(pre=None, post=None, dev=None, local=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): __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. """ @abc.abstractmethod def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None ) -> Iterator[UnparsedVersionVar]: """ 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). """ __slots__ = ("_prereleases", "_spec", "_spec_version") _operator_regex_str = r""" (?P(~=|==|!=|<=|>=|<|>|===)) """ _version_regex_str = r""" (?P (?: # 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 .* | (?: # 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 (?:\+[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. (?=": "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). """ match = self._regex.fullmatch(spec) if not match: raise InvalidSpecifier(f"Invalid specifier: {spec!r}") self._spec: tuple[str, str] = ( match.group("operator").strip(), match.group("version").strip(), ) # Store whether or not this Specifier should accept prereleases self._prereleases = prereleases # Specifier version cache self._spec_version: tuple[str, Version] | 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 @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 != "!=": # 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. if version.is_prerelease: return True return False @prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value @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') =1.0.0')> >>> Specifier('>=1.0.0', prereleases=False) =1.0.0', prereleases=False)> >>> Specifier('>=1.0.0', prereleases=True) =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 _get_operator(self, op: str) -> CallableOperator: operator_callable: CallableOperator = getattr( self, f"_compare_{self._operators[op]}" ) return operator_callable def _compare_compatible(self, prospective: Version, spec: str) -> bool: # Compatible releases have an equivalent combination of >= and ==. That # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to # implement this in terms of the other specifiers instead of # implementing it ourselves. The only thing we need to do is construct # the other specifiers. # We want everything but the last item in the version, but we want to # ignore suffix segments. prefix = _version_join( list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] ) # Add the prefix notation to the end of our string prefix += ".*" return self._get_operator(">=")(prospective, spec) and self._get_operator("==")( prospective, prefix ) def _compare_equal(self, prospective: Version, spec: str) -> bool: # We need special logic to handle prefix matching if spec.endswith(".*"): # In the case of prefix matching we want to ignore local segment. normalized_prospective = canonicalize_version( _public_version(prospective), strip_trailing_zero=False ) # Get the normalized version string ignoring the trailing .* normalized_spec = canonicalize_version(spec[:-2], strip_trailing_zero=False) # Split the spec out by bangs and dots, and pretend that there is # an implicit dot in between a release segment and a pre-release segment. split_spec = _version_split(normalized_spec) # Split the prospective version out by bangs and dots, and pretend # that there is an implicit dot in between a release segment and # a pre-release segment. split_prospective = _version_split(normalized_prospective) # 0-pad the prospective version before shortening it to get the correct # shortened version. padded_prospective, _ = _pad_version(split_prospective, split_spec) # Shorten the prospective version to be the same length as the spec # so that we can determine if the specifier is a prefix of the # prospective version or not. shortened_prospective = padded_prospective[: len(split_spec)] return shortened_prospective == split_spec else: # Convert our spec string into a Version spec_version = self._require_spec_version(spec) # If the specifier does not have a local segment, then we want to # act as if the prospective version also does not have a local # segment. if not spec_version.local: prospective = _public_version(prospective) return prospective == spec_version def _compare_not_equal(self, prospective: Version, spec: str) -> bool: return not self._compare_equal(prospective, spec) def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: # NB: Local version identifiers are NOT permitted in the version # specifier, so local version labels can be universally removed from # the prospective version. return _public_version(prospective) <= self._require_spec_version(spec) def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: # NB: Local version identifiers are NOT permitted in the version # specifier, so local version labels can be universally removed from # the prospective version. return _public_version(prospective) >= self._require_spec_version(spec) def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = self._require_spec_version(spec_str) # Check to see if the prospective version is less than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective < spec: return False # This special case is here so that, unless the specifier itself # includes is a pre-release version, that we do not accept pre-release # versions for the version mentioned in the specifier (e.g. <3.1 should # not match 3.1.dev0, but should match 3.0.dev0). if ( not spec.is_prerelease and prospective.is_prerelease and _base_version(prospective) == _base_version(spec) ): return False # If we've gotten to here, it means that prospective version is both # less than the spec version *and* it's not a pre-release of the same # version in the spec. return True def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = self._require_spec_version(spec_str) # Check to see if the prospective version is greater than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective > spec: return False # This special case is here so that, unless the specifier itself # includes is a post-release version, that we do not accept # post-release versions for the version mentioned in the specifier # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). if ( not spec.is_postrelease and prospective.is_postrelease and _base_version(prospective) == _base_version(spec) ): return False # Ensure that we do not allow a local version of the version mentioned # in the specifier, which is technically greater than, to match. if prospective.local is not None and _base_version( prospective ) == _base_version(spec): return False # If we've gotten to here, it means that prospective version is both # greater than the spec version *and* it's not a pre-release of the # same version in the spec. return True def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool: return str(prospective).lower() == str(spec).lower() 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:`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 """ return bool(list(self.filter([item], prereleases=prereleases))) def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None ) -> Iterator[UnparsedVersionVar]: """Filter items in the given iterable, that match the specifier. :param iterable: An iterable that can contain version strings and :class:`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. >>> 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', ] >>> 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'] """ prereleases_versions = [] found_non_prereleases = False # Determine if to include prereleases by default include_prereleases = ( prereleases if prereleases is not None else self.prereleases ) # Get the matching operator operator_callable = self._get_operator(self.operator) # Filter versions for version in iterable: parsed_version = _coerce_version(version) if parsed_version is None: # === operator can match arbitrary (non-version) strings if self.operator == "===" and self._compare_arbitrary( version, self.version ): yield version elif operator_callable(parsed_version, self.version): # If it's not a prerelease or prereleases are allowed, yield it directly if not parsed_version.is_prerelease or include_prereleases: found_non_prereleases = True yield version # Otherwise collect prereleases for potential later use elif prereleases is None and self._prereleases is not False: prereleases_versions.append(version) # If no non-prereleases were found and prereleases weren't # explicitly forbidden, yield the collected prereleases if ( not found_non_prereleases and prereleases is None and self._prereleases is not False ): yield from prereleases_versions _prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)") def _version_split(version: str) -> list[str]: """Split version into components. The split components are intended for version comparison. The logic does not attempt to retain the original version string, so joining the components back with :func:`_version_join` may not produce the original version string. """ result: list[str] = [] epoch, _, rest = version.rpartition("!") result.append(epoch or "0") for item in rest.split("."): match = _prefix_regex.fullmatch(item) if match: result.extend(match.groups()) else: result.append(item) return result def _version_join(components: list[str]) -> str: """Join split version components into a version string. This function assumes the input came from :func:`_version_split`, where the first component must be the epoch (either empty or numeric), and all other components numeric. """ epoch, *rest = components return f"{epoch}!{'.'.join(rest)}" def _is_not_suffix(segment: str) -> bool: return not any( segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") ) def _pad_version(left: list[str], right: list[str]) -> tuple[list[str], list[str]]: left_split, right_split = [], [] # Get the release segment of our versions left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) # Get the rest of our versions left_split.append(left[len(left_split[0]) :]) right_split.append(right[len(right_split[0]) :]) # Insert our padding left_split.insert(1, ["0"] * max(0, len(right_split[0]) - len(left_split[0]))) right_split.insert(1, ["0"] * max(0, len(left_split[0]) - len(right_split[0]))) return ( list(itertools.chain.from_iterable(left_split)), list(itertools.chain.from_iterable(right_split)), ) 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. """ __slots__ = ("_prereleases", "_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()] # Make each individual specifier a Specifier and save in a frozen set # for later. self._specs = frozenset(map(Specifier, split_specifiers)) else: # Save the supplied specifiers in a frozen set. self._specs = frozenset(specifiers) # Store our prereleases value so we can use it later to determine if # we accept prereleases or not. self._prereleases = prereleases @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 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') =1.0.0')> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) =1.0.0', prereleases=False)> >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) =1.0.0', prereleases=True)> """ pre = ( f", prereleases={self.prereleases!r}" if self._prereleases is not None else "" ) return f"" 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(sorted(str(s) for s in self._specs)) def __hash__(self) -> int: return hash(self._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' =1.0.0')> >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') =1.0.0')> """ if isinstance(other, str): other = SpecifierSet(other) elif not isinstance(other, SpecifierSet): return NotImplemented specifier = SpecifierSet() specifier._specs = frozenset(self._specs | other._specs) if self._prereleases is None and other._prereleases is not None: specifier._prereleases = other._prereleases elif ( self._prereleases is not None and other._prereleases is None ) or self._prereleases == other._prereleases: 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._specs == other._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) [, =1.0.0')>] """ return iter(self._specs) 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:`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 """ version = _coerce_version(item) if version is not None and installed and version.is_prerelease: prereleases = True check_item = item if version is None else version return bool(list(self.filter([check_item], prereleases=prereleases))) def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None ) -> Iterator[UnparsedVersionVar]: """Filter items in the given iterable, that match the specifiers in this set. :param iterable: An iterable that can contain version strings and :class:`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. >>> 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', ] >>> 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'] 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'] """ # 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 we have any specifiers, then we want to wrap our iterable in the # filter method for each one, this will act as a logical AND amongst # each specifier. if self._specs: # When prereleases is None, we need to let all versions through # the individual filters, then decide about prereleases at the end # based on whether any non-prereleases matched ALL specs. for spec in self._specs: iterable = spec.filter( iterable, prereleases=True if prereleases is None else prereleases ) if prereleases is not None: # If we have a forced prereleases value, # we can immediately return the iterator. return iter(iterable) else: # Handle empty SpecifierSet cases where prereleases is not None. if prereleases is True: return iter(iterable) if prereleases is False: return ( item for item in iterable if (version := _coerce_version(item)) is None or not version.is_prerelease ) # Finally if prereleases is None, apply PEP 440 logic: # exclude prereleases unless there are no final releases that matched. filtered_items: list[UnparsedVersionVar] = [] found_prereleases: list[UnparsedVersionVar] = [] found_final_release = False for item in iterable: parsed_version = _coerce_version(item) # Arbitrary strings are always included as it is not # possible to determine if they are prereleases, # and they have already passed all specifiers. if parsed_version is None: filtered_items.append(item) found_prereleases.append(item) elif parsed_version.is_prerelease: found_prereleases.append(item) else: filtered_items.append(item) found_final_release = True return iter(filtered_items if found_final_release else found_prereleases) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/tags.py0000644000000000000000000005451015133751156014352 0ustar00# 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 logging import platform import re import struct import subprocess import sys import sysconfig from importlib.machinery import EXTENSION_SUFFIXES from typing import ( Any, Iterable, Iterator, Sequence, Tuple, cast, ) from . import _manylinux, _musllinux logger = logging.getLogger(__name__) PythonVersion = Sequence[int] AppleVersion = Tuple[int, int] INTERPRETER_SHORT_NAMES: dict[str, str] = { "python": "py", # Generic. "cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy", } _32_BIT_INTERPRETER = struct.calcsize("P") == 4 class Tag: """ A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported. """ __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] def __init__(self, interpreter: str, abi: str, platform: str) -> None: 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: return self._interpreter @property def abi(self) -> str: return self._abi @property def platform(self) -> str: 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 __setstate__(self, state: tuple[None, dict[str, Any]]) -> None: # The cached _hash is wrong when unpickling. _, slots = state for k, v in slots.items(): setattr(self, k, v) self._hash = hash((self._interpreter, self._abi, self._platform)) def parse_tag(tag: str) -> frozenset[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set. """ tags = set() interpreters, abis, platforms = tag.split("-") for interpreter in interpreters.split("."): for abi in abis.split("."): for platform_ in platforms.split("."): tags.add(Tag(interpreter, abi, platform_)) return frozenset(tags) 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 threaded (`--disable-gil`) builds do not support abi3. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not 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 a CPython interpreter. The tags consist of: - cp-- - cp-abi3- - cp-none- - cp-abi3- # Older Python versions down to 3.2. If python_version only specifies a major version then user-provided ABIs and the 'none' ABItag will be used. If 'abi3' or 'none' are specified in 'abis' then they will be yielded at their normal position and not at the beginning. """ 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) # 'abi3' and 'none' are explicitly handled later. for explicit_abi in ("abi3", "none"): 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_) threading = _is_threaded_cpython(abis) use_abi3 = _abi3_applies(python_version, threading) if use_abi3: yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) if use_abi3: 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}" yield Tag(interpreter, "abi3", 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 ext_suffix[0] != ".": 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 abi = "cp" + soabi.split("-")[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 a generic interpreter. The tags consist of: - -- The "none" ABI will be added if it was not explicitly provided. """ 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 compatible_tags( python_version: PythonVersion | None = None, interpreter: str | None = None, platforms: Iterable[str] | None = None, ) -> Iterator[Tag]: """ Yields the sequence of tags that are compatible with a specific version of Python. The tags consist of: - py*-none- - -none-any # ... if `interpreter` is provided. - py*-none-any """ 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") for version in _py_interpreter_range(python_version): yield Tag(version, "none", "any") 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", "fat32"]) elif cpu_arch == "i386": if version < (10, 4): return [] formats.extend(["intel", "fat32", "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(["fat32", "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 platform tags for a macOS system. 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. """ 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}" if version >= (11, 0): # 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 platform tags for an iOS system. :param version: A two-item tuple specifying the iOS version to generate platform tags for. Defaults to the current iOS version. :param multiarch: The CPU architecture+ABI to generate platform tags for - (the value used by `sys.implementation._multiarch` e.g., `arm64_iphoneos` or `x84_64_iphonesimulator`). Defaults to the current multiarch value. """ 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 `__ to return. Defaults to the current system's version, as returned by ``platform.android_ver``. :param str abi: The `Android ABI `__, 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. """ 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]) yield from _manylinux.platform_tags(archs) yield from _musllinux.platform_tags(archs) for arch in archs: yield f"linux_{arch}" def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform()) def platform_tags() -> Iterator[str]: """ Provides the platform tags for this installation. """ 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() 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. """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name def interpreter_version(*, warn: bool = False) -> str: """ Returns the version of the running interpreter. """ 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]: """ Returns the sequence of tag triples for the running interpreter. The order of the sequence corresponds to priority order for the interpreter, from most to least important. """ interp_name = interpreter_name() if interp_name == "cp": yield from cpython_tags(warn=warn) else: yield from generic_tags() 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) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8173685 packaging-26.0/src/packaging/utils.py0000644000000000000000000001166015133751156014553 0ustar00# 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 re from typing import NewType, Tuple, Union, cast from .tags import Tag, parse_tag from .version import InvalidVersion, Version, _TrimmedRelease BuildTag = Union[Tuple[()], Tuple[int, str]] NormalizedName = NewType("NormalizedName", str) class InvalidName(ValueError): """ An invalid distribution name; users should refer to the packaging user guide. """ class InvalidWheelFilename(ValueError): """ An invalid wheel filename was found, users should refer to PEP 427. """ class InvalidSdistFilename(ValueError): """ An invalid sdist filename was found, users should refer to the packaging user guide. """ # Core metadata spec for `Name` _validate_regex = re.compile(r"[A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9]", re.IGNORECASE) _normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]") # PEP 427: The build number must start with a digit. _build_tag_regex = re.compile(r"(\d+)(.*)") def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: 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: 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. >>> 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' """ 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, ) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: 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 re.match(r"^[\w\d._]*$", name_part, re.UNICODE) 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 = () tags = parse_tag(parts[-1]) return (name, version, build, tags) def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: 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}") 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) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684 packaging-26.0/src/packaging/version.py0000644000000000000000000005535015133751156015104 0ustar00# 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, Version """ from __future__ import annotations import re import sys import typing from typing import ( Any, Callable, Literal, NamedTuple, SupportsInt, Tuple, TypedDict, Union, ) from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType if typing.TYPE_CHECKING: from typing_extensions import Self, Unpack if sys.version_info >= (3, 13): # pragma: no cover from warnings import deprecated as _deprecated elif typing.TYPE_CHECKING: from typing_extensions import deprecated as _deprecated else: # pragma: no cover import functools import warnings def _deprecated(message: str) -> object: def decorator(func: 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", "parse"] LocalType = Tuple[Union[int, str], ...] CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] CmpLocalType = Union[ NegativeInfinityType, Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], ] CmpKey = Tuple[ int, Tuple[int, ...], CmpPrePostDevType, CmpPrePostDevType, CmpPrePostDevType, CmpLocalType, ] VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] class _VersionReplace(TypedDict, total=False): epoch: int | None release: tuple[int, ...] | None pre: tuple[Literal["a", "b", "rc"], int] | None post: int | None dev: int | None local: str | None def parse(version: str) -> Version: """Parse the given version string. >>> parse('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 (?: (?:(?P[0-9]+)!)?+ # epoch (?P[0-9]+(?:\.[0-9]+)*+) # release segment (?P
                                          # pre-release
            [._-]?+
            (?Palpha|a|beta|b|preview|pre|c|rc)
            [._-]?+
            (?P[0-9]+)?
        )?+
        (?P                                         # post release
            (?:-(?P[0-9]+))
            |
            (?:
                [._-]?
                (?Ppost|rev|r)
                [._-]?
                (?P[0-9]+)?
            )
        )?+
        (?P                                          # dev release
            [._-]?+
            (?Pdev)
            [._-]?+
            (?P[0-9]+)?
        )?+
    )
    (?:\+
        (?P                                        # 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 larger
expressions (for example, matching a version number as part of a file name). The
regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
flags set.

:meta hide-value:
"""


# Validation pattern for local version in replace()
_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE)


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
        and value[0] in ("a", "b", "rc")
        and isinstance(value[1], int)
        and value[1] >= 0
    ):
        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[str, int] | None
    pre: tuple[str, int] | None
    post: tuple[str, 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
    
    >>> v2
    
    >>> v1 < v2
    True
    >>> v1 == v2
    False
    >>> v1 > v2
    False
    >>> v1 >= v2
    False
    >>> v1 <= v2
    True
    """

    __slots__ = ("_dev", "_epoch", "_key_cache", "_local", "_post", "_pre", "_release")
    __match_args__ = ("_str",)

    _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)

    _epoch: int
    _release: tuple[int, ...]
    _dev: tuple[str, int] | None
    _pre: tuple[str, int] | None
    _post: tuple[str, int] | None
    _local: LocalType | 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.
        """
        # Validate the version and parse it into pieces
        match = self._regex.fullmatch(version)
        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(".")))
        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))
        self._post = _parse_letter_version(
            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"))
        self._local = _parse_local_version(match.group("local"))

        # Key which will be used for sorting
        self._key_cache = None

    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
        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._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

    @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

    def __repr__(self) -> str:
        """A representation of the Version that shows all internal state.

        >>> Version('1.0.0')
        
        """
        return f""

    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[str, 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.

        >>> 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.

        >>> 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
        """
        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
        """
        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
        """
        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
            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


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:
    # When we compare a release version, we want to compare it with all of the
    # trailing zeros removed. We will use this for our sorting key.
    len_release = len(release)
    i = len_release
    while i and release[i - 1] == 0:
        i -= 1
    _release = release if i == len_release else release[:i]

    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
    # We'll do this by abusing the pre segment, but we _only_ want to do this
    # if there is not a pre or a post segment. If we have one of those then
    # the normal sorting rules will handle this case correctly.
    if pre is None and post is None and dev is not None:
        _pre: CmpPrePostDevType = NegativeInfinity
    # Versions without a pre-release (except as noted above) should sort after
    # those with one.
    elif pre is None:
        _pre = Infinity
    else:
        _pre = pre

    # Versions without a post segment should sort before those with one.
    if post is None:
        _post: CmpPrePostDevType = NegativeInfinity

    else:
        _post = post

    # Versions without a development segment should sort after those with one.
    if dev is None:
        _dev: CmpPrePostDevType = Infinity

    else:
        _dev = dev

    if local is None:
        # Versions without a local segment should sort before those with one.
        _local: CmpLocalType = NegativeInfinity
    else:
        # Versions with a local segment need that segment parsed to implement
        # the sorting rules in PEP440.
        # - Alpha numeric segments sort before numeric segments
        # - Alpha numeric segments sort lexicographically
        # - Numeric segments sort numerically
        # - Shorter versions sort before longer versions when the prefixes
        #   match exactly
        _local = tuple(
            (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local
        )

    return epoch, _release, _pre, _post, _dev, _local
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/__init__.py0000644000000000000000000000026415133751156013577 0ustar00# 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.
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/build.sh0000755000000000000000000000340215133751156015145 0ustar00#!/bin/bash

set -x
set -e

if [ $# -eq 0 ]; then
	docker run --rm -v $(pwd):/home/hello-world arm32v5/debian /home/hello-world/manylinux/build.sh incontainer 52
	docker run --rm -v $(pwd):/home/hello-world arm32v7/debian /home/hello-world/manylinux/build.sh incontainer 52
	docker run --rm -v $(pwd):/home/hello-world i386/debian /home/hello-world/manylinux/build.sh incontainer 52
	docker run --rm -v $(pwd):/home/hello-world s390x/debian /home/hello-world/manylinux/build.sh incontainer 64
	docker run --rm -v $(pwd):/home/hello-world debian /home/hello-world/manylinux/build.sh incontainer 64
	docker run --rm -v $(pwd):/home/hello-world debian /home/hello-world/manylinux/build.sh x32 52
	cp -f manylinux/hello-world-x86_64-i386 manylinux/hello-world-invalid-magic
	printf "\x00" | dd of=manylinux/hello-world-invalid-magic bs=1 seek=0x00 count=1 conv=notrunc
	cp -f manylinux/hello-world-x86_64-i386 manylinux/hello-world-invalid-class
	printf "\x00" | dd of=manylinux/hello-world-invalid-class bs=1 seek=0x04 count=1 conv=notrunc
	cp -f manylinux/hello-world-x86_64-i386 manylinux/hello-world-invalid-data
	printf "\x00" | dd of=manylinux/hello-world-invalid-data bs=1 seek=0x05 count=1 conv=notrunc
	head -c 40 manylinux/hello-world-x86_64-i386 > manylinux/hello-world-too-short
	exit 0
fi

export DEBIAN_FRONTEND=noninteractive
cd /home/hello-world/
apt-get update
apt-get install -y --no-install-recommends gcc libc6-dev
if [ "$1" == "incontainer" ]; then
	ARCH=$(dpkg --print-architecture)
	CFLAGS=""
else
	ARCH=$1
	dpkg --add-architecture ${ARCH}
	apt-get install -y --no-install-recommends gcc-multilib libc6-dev-${ARCH}
	CFLAGS="-mx32"
fi
NAME=hello-world-$(uname -m)-${ARCH}
gcc -Os -s ${CFLAGS} -o ${NAME}-full hello-world.c
head -c $2 ${NAME}-full > ${NAME}
rm -f ${NAME}-full
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-armv7l-armel0000755000000000000000000000006415133751156020172 0ustar00ELF(44 	(././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-armv7l-armhf0000755000000000000000000000006415133751156020167 0ustar00ELF(44 	(././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-invalid-class0000755000000000000000000000006415133751156020415 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-invalid-data0000755000000000000000000000006415133751156020221 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-invalid-magic0000755000000000000000000000006415133751156020370 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-s390x-s390x0000644000000000000000000000010015133751156017422 0ustar00ELFP@p@8	@././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-too-short0000644000000000000000000000005015133751156017612 0ustar00ELF401././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-x86_64-amd640000644000000000000000000000010015133751156017517 0ustar00ELF>p@H1@8@././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-x86_64-i3860000755000000000000000000000006415133751156017311 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/manylinux/hello-world-x86_64-x320000755000000000000000000000006415133751156017234 0ustar00ELF>p4<14 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/metadata/everything.metadata0000644000000000000000000000347115133751156017137 0ustar00Metadata-Version: 2.5
Name: BeagleVote
Version: 1.0a2
Platform: ObscureUnix
Platform: RareDOS
Supported-Platform: RedHat 7.2
Supported-Platform: i386-win32-2791
Summary: A module for collecting votes from beagles.
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Keywords: dog,puppy,voting,election
Home-page: http://www.example.com/~cschultz/bvote/
Download-URL: …/BeagleVote-0.45.tgz
Author: C. Schultz, Universal Features Syndicate,
        Los Angeles, CA 
Author-email: "C. Schultz" 
Maintainer: C. Schultz, Universal Features Syndicate,
        Los Angeles, CA 
Maintainer-email: "C. Schultz" 
License: This software may only be obtained by sending the
        author a postcard, and then the user promises not
        to redistribute it.
License-Expression: Apache-2.0 OR BSD-2-Clause
License-File: LICENSE.APACHE
License-File: LICENSE.BSD
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console (Text Based)
Provides-Extra: pdf
Requires-Dist: reportlab; extra == 'pdf'
Requires-Dist: pkginfo
Requires-Dist: PasteDeploy
Requires-Dist: zope.interface (>3.5.0)
Requires-Dist: pywin32 >1.0; sys_platform == 'win32'
Requires-Python: >=3
Requires-External: C
Requires-External: libpng (>=1.5)
Requires-External: make; sys_platform != "win32"
Project-URL: Bug Tracker, http://bitbucket.org/tarek/distribute/issues/
Project-URL: Documentation, https://example.com/BeagleVote
Provides-Dist: OtherProject
Provides-Dist: AnotherProject (3.4)
Provides-Dist: virtual_package; python_version >= "3.4"
Dynamic: Obsoletes-Dist
Import-Name: beaglevote
Import-Name: _beaglevote ; private
Import-Namespace: spam
Import-Namespace: _bacon ; private
ThisIsNotReal: Hello!

This description intentionally left blank.
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/glibc-x86_640000755000000000000000000000200015133751156015456 0ustar00ELF>@9@8
@@@@     XX-==X`-==888  XXXDDStd888  Ptd   DDQtdRtd-==HH/lib64/ld-linux-x86-64.so.2GNUGNUKWz7StyxyʍGNUemQ '././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/musl-aarch640000755000000000000000000000200015133751156015650 0ustar00ELF@@#@8@ @@@


`


Ptd44QtdRtd


XX/lib/ld-musl-aarch64.so.1
@
"L d ~ # 
_initprintf_fini__cxa_finalize__libc_start_mainlibc.musl-aarch64.so.1__deregister_frame_info_ITM_registerTMCloneTable_ITM_deregisterTMCloneTabl././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/musl-i3860000755000000000000000000000200015133751156015111 0ustar00ELF4=4 
(! 444@@ttt``   .>>(/??Ptd   $$QtdRtd.>>/lib/ld-musl-i386.so.1$"H d ~  #_initprintf_fini__cxa_finalize__libc_start_mainlibc.musl-x86.so.1__register_frame_info_bases_ITM_registerTMCloneTable__deregister_frame_info_bases_ITM_deregisterTMCloneTable???@???????././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8183684
packaging-26.0/tests/musllinux/musl-x86_640000755000000000000000000000200015133751156015356 0ustar00ELF>s@A@8
@! @@@00ppp  YY   .>>`0.0>0>Ptd   $$QtdRtd.>>/lib/ld-musl-x86_64.so.1@	emK c } # "Q_initprintf_fini__cxa_finalize__libc_start_mainlibc.musl-x86_64.so.1__der././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/pylock/pylock.spec-example.toml0000644000000000000000000000532215133751156017547 0ustar00# This is the example from PEP 751, with the following differences:
# - a minor modification to the 'environments' field to use double quotes
#   instead of single quotes, since that is what 'packaging' does when
#   serializing markers;
# - added an index field, which was not demonstrated in the PEP 751 example.
# - removed spaces in require-python specifiers

lock-version = '1.0'
environments = ['sys_platform == "win32"', 'sys_platform == "linux"']
requires-python = '==3.12'
created-by = 'mousebender'

[[packages]]
name = 'attrs'
version = '25.1.0'
requires-python = '>=3.8'

    [[packages.wheels]]
    name = 'attrs-25.1.0-py3-none-any.whl'
    upload-time = 2025-01-25T11:30:10.164985+00:00
    url = 'https://files.pythonhosted.org/packages/fc/30/d4986a882011f9df997a55e6becd864812ccfcd821d64aac8570ee39f719/attrs-25.1.0-py3-none-any.whl'
    size = 63152
    hashes = {sha256 = 'c75a69e28a550a7e93789579c22aa26b0f5b83b75dc4e08fe092980051e1090a'}

    [[packages.attestation-identities]]
    environment = 'release-pypi'
    kind = 'GitHub'
    repository = 'python-attrs/attrs'
    workflow = 'pypi-package.yml'

[[packages]]
name = 'cattrs'
version = '24.1.2'
requires-python = '>=3.8'
dependencies = [
    {name = 'attrs'},
]
index = 'https://pypi.org/simple'

    [[packages.wheels]]
    name = 'cattrs-24.1.2-py3-none-any.whl'
    upload-time = 2024-09-22T14:58:34.812643+00:00
    url = 'https://files.pythonhosted.org/packages/c8/d5/867e75361fc45f6de75fe277dd085627a9db5ebb511a87f27dc1396b5351/cattrs-24.1.2-py3-none-any.whl'
    size = 66446
    hashes = {sha256 = '67c7495b760168d931a10233f979b28dc04daf853b30752246f4f8471c6d68d0'}

[[packages]]
name = 'numpy'
version = '2.2.3'
requires-python = '>=3.10'

    [[packages.wheels]]
    name = 'numpy-2.2.3-cp312-cp312-win_amd64.whl'
    upload-time = 2025-02-13T16:51:21.821880+00:00
    url = 'https://files.pythonhosted.org/packages/42/6e/55580a538116d16ae7c9aa17d4edd56e83f42126cb1dfe7a684da7925d2c/numpy-2.2.3-cp312-cp312-win_amd64.whl'
    size = 12626357
    hashes = {sha256 = '83807d445817326b4bcdaaaf8e8e9f1753da04341eceec705c001ff342002e5d'}

    [[packages.wheels]]
    name = 'numpy-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl'
    upload-time = 2025-02-13T16:50:00.079662+00:00
    url = 'https://files.pythonhosted.org/packages/39/04/78d2e7402fb479d893953fb78fa7045f7deb635ec095b6b4f0260223091a/numpy-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl'
    size = 16116679
    hashes = {sha256 = '3b787adbf04b0db1967798dba8da1af07e387908ed1553a0d6e74c084d1ceafe'}

[tool.mousebender]
command = ['.', 'lock', '--platform', 'cpython3.12-windows-x64', '--platform', 'cpython3.12-manylinux2014-x64', 'cattrs', 'numpy']
run-on = 2025-03-06T12:28:57.760769
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_elffile.py0000644000000000000000000000636415133751156014514 0ustar00import io
import pathlib
import struct

import pytest

from packaging._elffile import EIClass, EIData, ELFFile, ELFInvalid, EMachine

DIR_MANYLINUX = pathlib.Path(__file__, "..", "manylinux").resolve()
DIR_MUSLLINUX = pathlib.Path(__file__, "..", "musllinux").resolve()
BIN_MUSL_X86_64 = DIR_MUSLLINUX.joinpath("musl-x86_64").read_bytes()


@pytest.mark.parametrize(
    ("name", "capacity", "encoding", "machine"),
    [
        ("x86_64-x32", EIClass.C32, EIData.Lsb, EMachine.X8664),
        ("x86_64-i386", EIClass.C32, EIData.Lsb, EMachine.I386),
        ("x86_64-amd64", EIClass.C64, EIData.Lsb, EMachine.X8664),
        ("armv7l-armel", EIClass.C32, EIData.Lsb, EMachine.Arm),
        ("armv7l-armhf", EIClass.C32, EIData.Lsb, EMachine.Arm),
        ("s390x-s390x", EIClass.C64, EIData.Msb, EMachine.S390),
    ],
)
def test_elffile_glibc(
    name: str, capacity: EIClass, encoding: EIData, machine: EMachine
) -> None:
    path = DIR_MANYLINUX.joinpath(f"hello-world-{name}")
    with path.open("rb") as f:
        ef = ELFFile(f)
        assert ef.capacity == capacity
        assert ef.encoding == encoding
        assert ef.machine == machine
        assert ef.flags is not None


@pytest.mark.parametrize(
    ("name", "capacity", "encoding", "machine", "interpreter"),
    [
        (
            "aarch64",
            EIClass.C64,
            EIData.Lsb,
            EMachine.AArc64,
            "aarch64",
        ),
        ("i386", EIClass.C32, EIData.Lsb, EMachine.I386, "i386"),
        ("x86_64", EIClass.C64, EIData.Lsb, EMachine.X8664, "x86_64"),
    ],
)
def test_elffile_musl(
    name: str, capacity: EIClass, encoding: EIData, machine: EMachine, interpreter: str
) -> None:
    path = DIR_MUSLLINUX.joinpath(f"musl-{name}")
    with path.open("rb") as f:
        ef = ELFFile(f)
        assert ef.capacity == capacity
        assert ef.encoding == encoding
        assert ef.machine == machine
        assert ef.interpreter == f"/lib/ld-musl-{interpreter}.so.1"


@pytest.mark.parametrize(
    "data",
    [
        # Too short for magic.
        b"\0",
        # Enough for magic, but not ELF.
        b"#!/bin/bash" + b"\0" * 16,
        # ELF, but unknown byte declaration.
        b"\x7fELF\3" + b"\0" * 16,
    ],
    ids=["no-magic", "wrong-magic", "unknown-format"],
)
def test_elffile_bad_ident(data: bytes) -> None:
    with pytest.raises(ELFInvalid):
        ELFFile(io.BytesIO(data))


def test_elffile_no_section() -> None:
    """Enough for magic, but not the section definitions."""
    data = BIN_MUSL_X86_64[:25]
    with pytest.raises(ELFInvalid):
        ELFFile(io.BytesIO(data))


def test_elffile_invalid_section() -> None:
    """Enough for section definitions, but not the actual sections."""
    data = BIN_MUSL_X86_64[:58]
    assert ELFFile(io.BytesIO(data)).interpreter is None


def test_elffle_no_interpreter_section() -> None:
    ef = ELFFile(io.BytesIO(BIN_MUSL_X86_64))

    # Change all sections to *not* PT_INTERP.
    data = BIN_MUSL_X86_64
    for i in range(ef._e_phnum + 1):
        sb = ef._e_phoff + ef._e_phentsize * i
        se = sb + ef._e_phentsize
        section = struct.unpack(ef._p_fmt, data[sb:se])
        data = data[:sb] + struct.pack(ef._p_fmt, 0, *section[1:]) + data[se:]

    assert ELFFile(io.BytesIO(data)).interpreter is None
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_licenses.py0000644000000000000000000000044215133751156014702 0ustar00from packaging.licenses._spdx import EXCEPTIONS, LICENSES


def test_licenses() -> None:
    for license_id in LICENSES:
        assert license_id == license_id.lower()


def test_exceptions() -> None:
    for exception_id in EXCEPTIONS:
        assert exception_id == exception_id.lower()
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_manylinux.py0000644000000000000000000001544615133751156015133 0ustar00from __future__ import annotations

try:
    import ctypes
except ImportError:
    ctypes = None  # type: ignore[assignment]
import os
import pathlib
import platform
import re
import sys
import types
import typing

if typing.TYPE_CHECKING:
    from collections.abc import Generator

import pretend
import pytest

from packaging import _manylinux
from packaging._manylinux import (
    _get_glibc_version,
    _glibc_version_string,
    _glibc_version_string_confstr,
    _glibc_version_string_ctypes,
    _GLibCVersion,
    _is_compatible,
    _parse_elf,
    _parse_glibc_version,
)


@pytest.fixture(autouse=True)
def clear_lru_cache() -> Generator[None, None, None]:
    yield
    _get_glibc_version.cache_clear()


@pytest.fixture
def manylinux_module(monkeypatch: pytest.MonkeyPatch) -> types.ModuleType:
    monkeypatch.setattr(_manylinux, "_get_glibc_version", lambda *args: (2, 20))
    module_name = "_manylinux"
    module = types.ModuleType(module_name)
    monkeypatch.setitem(sys.modules, module_name, module)
    return module


@pytest.mark.parametrize("tf", [True, False])
@pytest.mark.parametrize(
    ("attribute", "glibc"), [("1", (2, 5)), ("2010", (2, 12)), ("2014", (2, 17))]
)
def test_module_declaration(
    monkeypatch: pytest.MonkeyPatch,
    manylinux_module: types.ModuleType,
    attribute: str,
    glibc: tuple[int, int],
    tf: bool,
) -> None:
    manylinux = f"manylinux{attribute}_compatible"
    monkeypatch.setattr(manylinux_module, manylinux, tf, raising=False)
    glibc_version = _GLibCVersion(glibc[0], glibc[1])
    res = _is_compatible("x86_64", glibc_version)
    assert tf is res


@pytest.mark.parametrize(
    ("attribute", "glibc"), [("1", (2, 5)), ("2010", (2, 12)), ("2014", (2, 17))]
)
def test_module_declaration_missing_attribute(
    monkeypatch: pytest.MonkeyPatch,
    manylinux_module: types.ModuleType,
    attribute: str,
    glibc: tuple[int, int],
) -> None:
    manylinux = f"manylinux{attribute}_compatible"
    monkeypatch.delattr(manylinux_module, manylinux, raising=False)
    glibc_version = _GLibCVersion(glibc[0], glibc[1])
    assert _is_compatible("x86_64", glibc_version)


@pytest.mark.parametrize(
    ("version", "compatible"), [((2, 0), True), ((2, 5), True), ((2, 10), False)]
)
def test_is_manylinux_compatible_glibc_support(
    version: tuple[int, int], compatible: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
    monkeypatch.setitem(sys.modules, "_manylinux", None)
    monkeypatch.setattr(_manylinux, "_get_glibc_version", lambda: (2, 5))
    glibc_version = _GLibCVersion(version[0], version[1])
    assert bool(_is_compatible("any", glibc_version)) == compatible


@pytest.mark.parametrize("version_str", ["glibc-2.4.5", "2"])
def test_check_glibc_version_warning(version_str: str) -> None:
    msg = f"Expected glibc version with 2 components major.minor, got: {version_str}"
    with pytest.warns(RuntimeWarning, match=re.escape(msg)):
        _parse_glibc_version(version_str)


@pytest.mark.skipif(not ctypes, reason="requires ctypes")  # type: ignore[truthy-bool]
@pytest.mark.parametrize(
    ("version_str", "expected"),
    [
        # Be very explicit about bytes and Unicode for Python 2 testing.
        (b"2.4", "2.4"),
        ("2.4", "2.4"),
    ],
)
def test_glibc_version_string(
    version_str: str | bytes, expected: str, monkeypatch: pytest.MonkeyPatch
) -> None:
    class LibcVersion:
        def __init__(self, version_str: str | bytes) -> None:
            self.version_str = version_str

        def __call__(self) -> str | bytes:
            return self.version_str

    class ProcessNamespace:
        def __init__(self, libc_version: LibcVersion) -> None:
            self.gnu_get_libc_version = libc_version

    process_namespace = ProcessNamespace(LibcVersion(version_str))
    monkeypatch.setattr(ctypes, "CDLL", lambda _: process_namespace)
    monkeypatch.setattr(_manylinux, "_glibc_version_string_confstr", lambda: False)

    assert _glibc_version_string() == expected

    del process_namespace.gnu_get_libc_version
    assert _glibc_version_string() is None


def test_glibc_version_string_confstr(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
    assert _glibc_version_string_confstr() == "2.20"


def test_glibc_version_string_fail(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(os, "confstr", lambda _: None, raising=False)
    monkeypatch.setitem(sys.modules, "ctypes", None)
    assert _glibc_version_string() is None
    assert _get_glibc_version() == (-1, -1)


@pytest.mark.parametrize(
    "failure",
    [pretend.raiser(ValueError), pretend.raiser(OSError), lambda _: "XXX"],
)
def test_glibc_version_string_confstr_fail(
    monkeypatch: pytest.MonkeyPatch, failure: typing.Callable[[int], str | None]
) -> None:
    monkeypatch.setattr(os, "confstr", failure, raising=False)
    assert _glibc_version_string_confstr() is None


def test_glibc_version_string_confstr_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delattr(os, "confstr", raising=False)
    assert _glibc_version_string_confstr() is None


def test_glibc_version_string_ctypes_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setitem(sys.modules, "ctypes", None)
    assert _glibc_version_string_ctypes() is None


@pytest.mark.xfail(ctypes is None, reason="ctypes not available")
def test_glibc_version_string_ctypes_raise_oserror(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def patched_cdll(_name: str) -> None:
        raise OSError("Dynamic loading not supported")

    monkeypatch.setattr(ctypes, "CDLL", patched_cdll)
    assert _glibc_version_string_ctypes() is None


@pytest.mark.skipif(platform.system() != "Linux", reason="requires Linux")
def test_is_manylinux_compatible_old() -> None:
    # Assuming no one is running this test with a version of glibc released in
    # 1997.
    assert _is_compatible("any", _GLibCVersion(2, 0))


def test_is_manylinux_compatible(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(_manylinux, "_glibc_version_string", lambda: "2.4")
    assert _is_compatible("any", _GLibCVersion(2, 4))


def test_glibc_version_string_none(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(_manylinux, "_glibc_version_string", lambda: None)
    assert not _is_compatible("any", _GLibCVersion(2, 4))


@pytest.mark.parametrize(
    "content", [None, "invalid-magic", "invalid-class", "invalid-data", "too-short"]
)
def test_parse_elf_bad_executable(content: str | None) -> None:
    path_str: str | None
    if content:
        path = pathlib.Path(__file__).parent / "manylinux" / f"hello-world-{content}"
        path_str = os.fsdecode(path)
    else:
        path_str = None
    # None is not supported in the type annotation, but it was tested before.
    with _parse_elf(path_str) as ef:  # type: ignore[arg-type]
        assert ef is None
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_markers.py0000644000000000000000000004327615133751156014555 0ustar00# 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 collections
import itertools
import os
import platform
import sys
from typing import cast
from unittest import mock

import pytest

from packaging._parser import Node
from packaging.markers import (
    InvalidMarker,
    Marker,
    UndefinedComparison,
    default_environment,
    format_full_version,
)

VARIABLES = [
    "extra",
    "implementation_name",
    "implementation_version",
    "os_name",
    "platform_machine",
    "platform_release",
    "platform_system",
    "platform_version",
    "python_full_version",
    "python_version",
    "platform_python_implementation",
    "sys_platform",
]

PEP_345_VARIABLES = [
    "os.name",
    "sys.platform",
    "platform.version",
    "platform.machine",
    "platform.python_implementation",
]

SETUPTOOLS_VARIABLES = ["python_implementation"]

OPERATORS = ["===", "==", ">=", "<=", "!=", "~=", ">", "<", "in", "not in"]

VALUES = [
    "1.0",
    "5.6a0",
    "dog",
    "freebsd",
    "literally any string can go here",
    "things @#4 dsfd (((",
]


class TestNode:
    @pytest.mark.parametrize("value", ["one", "two", None, 3, 5, []])
    def test_accepts_value(self, value: str | None | int | list[str]) -> None:
        assert Node(value).value == value  # type: ignore[arg-type]

    @pytest.mark.parametrize("value", ["one", "two"])
    def test_str(self, value: str) -> None:
        assert str(Node(value)) == str(value)

    @pytest.mark.parametrize("value", ["one", "two"])
    def test_repr(self, value: str) -> None:
        assert repr(Node(value)) == f""

    def test_base_class(self) -> None:
        with pytest.raises(NotImplementedError):
            Node("cover all the code").serialize()


class TestOperatorEvaluation:
    def test_prefers_pep440(self) -> None:
        assert Marker('"2.7.9" < python_full_version').evaluate(
            dict(python_full_version="2.7.10")
        )
        assert not Marker('"2.7.9" < python_full_version').evaluate(
            dict(python_full_version="2.7.8")
        )

    def test_new_string_rules(self) -> None:
        assert not Marker('"b" < python_full_version').evaluate(
            dict(python_full_version="c")
        )
        assert not Marker('"b" < python_full_version').evaluate(
            dict(python_full_version="a")
        )
        assert not Marker('"b" > "a"').evaluate(dict(a="a"))
        assert not Marker('"b" < "a"').evaluate(dict(a="a"))
        assert not Marker('"b" >= "a"').evaluate(dict(a="a"))
        assert not Marker('"b" <= "a"').evaluate(dict(a="a"))
        assert Marker('"a" <= "a"').evaluate(dict(a="a"))

    def test_fails_when_undefined(self) -> None:
        with pytest.raises(UndefinedComparison):
            Marker("'2.7.0' ~= os_name").evaluate()

    def test_allows_prerelease(self) -> None:
        assert Marker('python_full_version > "3.6.2"').evaluate(
            {"python_full_version": "3.11.0a5"}
        )


FakeVersionInfo = collections.namedtuple(
    "FakeVersionInfo", ["major", "minor", "micro", "releaselevel", "serial"]
)


class TestDefaultEnvironment:
    def test_matches_expected(self) -> None:
        environment = default_environment()

        iver = (
            f"{sys.implementation.version.major}."
            f"{sys.implementation.version.minor}."
            f"{sys.implementation.version.micro}"
        )
        if sys.implementation.version.releaselevel != "final":
            iver = (
                f"{iver}{sys.implementation.version.releaselevel[0]}"
                f"{sys.implementation.version.serial}"
            )

        assert environment == {
            "implementation_name": sys.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 test_multidigit_minor_version(self, monkeypatch: pytest.MonkeyPatch) -> None:
        version_info = (3, 10, 0, "final", 0)
        monkeypatch.setattr(sys, "version_info", version_info, raising=False)

        monkeypatch.setattr(platform, "python_version", lambda: "3.10.0", raising=False)
        monkeypatch.setattr(
            platform, "python_version_tuple", lambda: ("3", "10", "0"), raising=False
        )

        environment = default_environment()
        assert environment["python_version"] == "3.10"

    def tests_when_releaselevel_final(self) -> None:
        v = FakeVersionInfo(3, 4, 2, "final", 0)
        assert format_full_version(v) == "3.4.2"  # type: ignore[arg-type]

    def tests_when_releaselevel_not_final(self) -> None:
        v = FakeVersionInfo(3, 4, 2, "beta", 4)
        assert format_full_version(v) == "3.4.2b4"  # type: ignore[arg-type]


class TestMarker:
    @pytest.mark.parametrize(
        "marker_string",
        [
            "{} {} {!r}".format(*i)
            for i in itertools.product(VARIABLES, OPERATORS, VALUES)
        ]
        + [
            "{2!r} {1} {0}".format(*i)
            for i in itertools.product(VARIABLES, OPERATORS, VALUES)
        ],
    )
    def test_parses_valid(self, marker_string: str) -> None:
        Marker(marker_string)

    @pytest.mark.parametrize(
        "marker_string",
        [
            "this_isnt_a_real_variable >= '1.0'",
            "python_version",
            "(python_version)",
            "python_version >= 1.0 and (python_version)",
            '(python_version == "2.7" and os_name == "linux"',
            '(python_version == "2.7") with random text',
        ],
    )
    def test_parses_invalid(self, marker_string: str) -> None:
        with pytest.raises(InvalidMarker):
            Marker(marker_string)

    @pytest.mark.parametrize(
        ("marker_string", "expected"),
        [
            # Test the different quoting rules
            ("python_version == '2.7'", 'python_version == "2.7"'),
            ('python_version == "2.7"', 'python_version == "2.7"'),
            # Test and/or expressions
            (
                'python_version == "2.7" and os_name == "linux"',
                'python_version == "2.7" and os_name == "linux"',
            ),
            (
                'python_version == "2.7" or os_name == "linux"',
                'python_version == "2.7" or os_name == "linux"',
            ),
            (
                'python_version == "2.7" and os_name == "linux" or '
                'sys_platform == "win32"',
                'python_version == "2.7" and os_name == "linux" or '
                'sys_platform == "win32"',
            ),
            # Test nested expressions and grouping with ()
            ('(python_version == "2.7")', 'python_version == "2.7"'),
            (
                '(python_version == "2.7" and sys_platform == "win32")',
                'python_version == "2.7" and sys_platform == "win32"',
            ),
            (
                'python_version == "2.7" and (sys_platform == "win32" or '
                'sys_platform == "linux")',
                'python_version == "2.7" and (sys_platform == "win32" or '
                'sys_platform == "linux")',
            ),
        ],
    )
    def test_str_repr_eq_hash(self, marker_string: str, expected: str) -> None:
        m = Marker(marker_string)
        assert str(m) == expected
        assert repr(m) == f""
        # Objects created from the same string should be equal.
        assert m == Marker(marker_string)
        # Objects created from the equivalent strings should also be equal.
        assert m == Marker(expected)
        # Objects created from the same string should have the same hash.
        assert hash(Marker(marker_string)) == hash(Marker(marker_string))
        # Objects created from equivalent strings should also have the same hash.
        assert hash(Marker(marker_string)) == hash(Marker(expected))

    @pytest.mark.parametrize(
        ("example1", "example2"),
        [
            # Test trivial comparisons.
            ('python_version == "2.7"', 'python_version == "3.7"'),
            (
                'python_version == "2.7"',
                'python_version == "2.7" and os_name == "linux"',
            ),
            (
                'python_version == "2.7"',
                '(python_version == "2.7" and os_name == "linux")',
            ),
            # Test different precedence.
            (
                'python_version == "2.7" and (os_name == "linux" or '
                'sys_platform == "win32")',
                'python_version == "2.7" and os_name == "linux" or '
                'sys_platform == "win32"',
            ),
        ],
    )
    def test_different_markers_different_hashes(
        self, example1: str, example2: str
    ) -> None:
        marker1, marker2 = Marker(example1), Marker(example2)
        # Markers created from strings that are not equivalent should differ.
        assert marker1 != marker2
        # Different Marker objects should have different hashes.
        assert hash(marker1) != hash(marker2)

    def test_compare_markers_to_other_objects(self) -> None:
        # Markers should not be comparable to other kinds of objects.
        assert Marker("os_name == 'nt'") != "os_name == 'nt'"

    def test_environment_assumes_empty_extra(self) -> None:
        assert Marker('extra == "im_valid"').evaluate() is False

    def test_environment_with_extra_none(self) -> None:
        # GIVEN
        marker_str = 'extra == "im_valid"'

        # Pretend that this is dict[str, str], even though it's not. This is a
        # test for being bug-for-bug compatible with the older implementation.
        environment = cast("dict[str, str]", {"extra": None})

        # WHEN
        marker = Marker(marker_str)

        # THEN
        assert marker.evaluate(environment) is False

    def test_environment_with_no_extras(self) -> None:
        # Environment is set but no 'extra' key is present; branch only hit on
        # non-metadata context.
        marker = Marker("os_name == 'foo'")
        assert marker.evaluate({"os_name": "foo"}, context="requirement")
        assert not marker.evaluate({"os_name": "bar"}, context="requirement")

    @pytest.mark.parametrize(
        ("marker_string", "environment", "expected"),
        [
            (f"os_name == '{os.name}'", None, True),
            ("os_name == 'foo'", {"os_name": "foo"}, True),
            ("os_name == 'foo'", {"os_name": "bar"}, False),
            ("'2.7' in python_version", {"python_version": "2.7.5"}, True),
            ("'2.7' not in python_version", {"python_version": "2.7"}, False),
            (
                "os_name == 'foo' and python_version ~= '2.7.0'",
                {"os_name": "foo", "python_version": "2.7.6"},
                True,
            ),
            (
                "python_version ~= '2.7.0' and (os_name == 'foo' or os_name == 'bar')",
                {"os_name": "foo", "python_version": "2.7.4"},
                True,
            ),
            (
                "python_version ~= '2.7.0' and (os_name == 'foo' or os_name == 'bar')",
                {"os_name": "bar", "python_version": "2.7.4"},
                True,
            ),
            (
                "python_version ~= '2.7.0' and (os_name == 'foo' or os_name == 'bar')",
                {"os_name": "other", "python_version": "2.7.4"},
                False,
            ),
            ("extra == 'security'", {"extra": "quux"}, False),
            ("extra == 'security'", {"extra": "security"}, True),
            ("extra == 'SECURITY'", {"extra": "security"}, True),
            ("extra == 'security'", {"extra": "SECURITY"}, True),
            ("extra == 'pep-685-norm'", {"extra": "PEP_685...norm"}, True),
            (
                "extra == 'Different.punctuation..is...equal'",
                {"extra": "different__punctuation_is_EQUAL"},
                True,
            ),
        ],
    )
    def test_evaluates(
        self, marker_string: str, environment: dict[str, str] | None, expected: bool
    ) -> None:
        args = () if environment is None else (environment,)
        assert Marker(marker_string).evaluate(*args) == expected

    @pytest.mark.parametrize(
        "marker_string",
        [
            "{} {} {!r}".format(*i)
            for i in itertools.product(PEP_345_VARIABLES, OPERATORS, VALUES)
        ]
        + [
            "{2!r} {1} {0}".format(*i)
            for i in itertools.product(PEP_345_VARIABLES, OPERATORS, VALUES)
        ],
    )
    def test_parses_pep345_valid(self, marker_string: str) -> None:
        Marker(marker_string)

    @pytest.mark.parametrize(
        ("marker_string", "environment", "expected"),
        [
            (f"os.name == '{os.name}'", None, True),
            ("sys.platform == 'win32'", {"sys_platform": "linux2"}, False),
            ("platform.version in 'Ubuntu'", {"platform_version": "#39"}, False),
            ("platform.machine=='x86_64'", {"platform_machine": "x86_64"}, True),
            (
                "platform.python_implementation=='Jython'",
                {"platform_python_implementation": "CPython"},
                False,
            ),
            (
                "python_version == '2.5' and platform.python_implementation!= 'Jython'",
                {"python_version": "2.7"},
                False,
            ),
        ],
    )
    def test_evaluate_pep345_markers(
        self, marker_string: str, environment: dict[str, str] | None, expected: bool
    ) -> None:
        args = () if environment is None else (environment,)
        assert Marker(marker_string).evaluate(*args) == expected

    @pytest.mark.parametrize(
        "marker_string",
        [
            "{} {} {!r}".format(*i)
            for i in itertools.product(SETUPTOOLS_VARIABLES, OPERATORS, VALUES)
        ]
        + [
            "{2!r} {1} {0}".format(*i)
            for i in itertools.product(SETUPTOOLS_VARIABLES, OPERATORS, VALUES)
        ],
    )
    def test_parses_setuptools_legacy_valid(self, marker_string: str) -> None:
        Marker(marker_string)

    def test_evaluate_setuptools_legacy_markers(self) -> None:
        marker_string = "python_implementation=='Jython'"
        args = ({"platform_python_implementation": "CPython"},)
        assert Marker(marker_string).evaluate(*args) is False

    def test_extra_str_normalization(self) -> None:
        raw_name = "S_P__A_M"
        normalized_name = "s-p-a-m"
        lhs = f"{raw_name!r} == extra"
        rhs = f"extra == {raw_name!r}"

        assert str(Marker(lhs)) == f'"{normalized_name}" == extra'
        assert str(Marker(rhs)) == f'extra == "{normalized_name}"'

    def test_python_full_version_untagged_user_provided(self) -> None:
        """A user-provided python_full_version ending with a + is also repaired."""
        assert Marker("python_full_version < '3.12'").evaluate(
            {"python_full_version": "3.11.1+"}
        )

    def test_python_full_version_untagged(self) -> None:
        with mock.patch("platform.python_version", return_value="3.11.1+"):
            assert Marker("python_full_version < '3.12'").evaluate()

    @pytest.mark.parametrize("variable", ["extras", "dependency_groups"])
    @pytest.mark.parametrize(
        ("expression", "result"),
        [
            pytest.param('"foo" in {0}', True, id="value-in-foo"),
            pytest.param('"bar" in {0}', True, id="value-in-bar"),
            pytest.param('"baz" in {0}', False, id="value-not-in"),
            pytest.param('"baz" not in {0}', True, id="value-not-in-negated"),
            pytest.param('"foo" in {0} and "bar" in {0}', True, id="and-in"),
            pytest.param('"foo" in {0} or "bar" in {0}', True, id="or-in"),
            pytest.param(
                '"baz" in {0} and "foo" in {0}', False, id="short-circuit-and"
            ),
            pytest.param('"foo" in {0} or "baz" in {0}', True, id="short-circuit-or"),
            pytest.param('"Foo" in {0}', True, id="case-sensitive"),
        ],
    )
    def test_extras_and_dependency_groups(
        self, variable: str, expression: str, result: bool
    ) -> None:
        environment = {variable: {"foo", "bar"}}
        assert Marker(expression.format(variable)).evaluate(environment) == result

    @pytest.mark.parametrize("variable", ["extras", "dependency_groups"])
    def test_extras_and_dependency_groups_disallowed(self, variable: str) -> None:
        marker = Marker(f'"foo" in {variable}')
        assert not marker.evaluate(context="lock_file")

        with pytest.raises(KeyError):
            marker.evaluate()

        with pytest.raises(KeyError):
            marker.evaluate(context="requirement")

    @pytest.mark.parametrize(
        ("marker_string", "environment", "expected"),
        [
            ('extra == "v2"', None, False),
            ('extra == "v2"', {"extra": ""}, False),
            ('extra == "v2"', {"extra": "v2"}, True),
            ('extra == "v2"', {"extra": "v2a3"}, False),
            ('extra == "v2a3"', {"extra": "v2"}, False),
            ('extra == "v2a3"', {"extra": "v2a3"}, True),
        ],
    )
    def test_version_like_equality(
        self, marker_string: str, environment: dict[str, str] | None, expected: bool
    ) -> None:
        """
        Test for issue #938: Extras are meant to be literal strings, even if
        they look like versions, and therefore should not be parsed as version.
        """
        marker = Marker(marker_string)
        assert marker.evaluate(environment) is expected
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_metadata.py0000644000000000000000000012551215133751156014663 0ustar00from __future__ import annotations

import email.message
import inspect
import pathlib
import textwrap

import pytest

from packaging import metadata, requirements, specifiers, utils, version
from packaging.metadata import ExceptionGroup, RawMetadata


class TestRawMetadata:
    @pytest.mark.parametrize("raw_field", sorted(metadata._STRING_FIELDS))
    def test_non_repeating_fields_only_once(self, raw_field: str) -> None:
        data = "VaLuE"
        header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
        single_header = f"{header_field}: {data}"
        raw, unparsed = metadata.parse_email(single_header)
        assert not unparsed
        assert len(raw) == 1
        assert raw_field in raw
        assert raw[raw_field] == data  # type: ignore[literal-required]

    @pytest.mark.parametrize("raw_field", sorted(metadata._STRING_FIELDS))
    def test_non_repeating_fields_repeated(self, raw_field: str) -> None:
        header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
        data = "VaLuE"
        single_header = f"{header_field}: {data}"
        repeated_header = "\n".join([single_header] * 2)
        raw, unparsed = metadata.parse_email(repeated_header)
        assert not raw
        assert len(unparsed) == 1
        assert header_field in unparsed
        assert unparsed[header_field] == [data] * 2

    @pytest.mark.parametrize("raw_field", sorted(metadata._LIST_FIELDS))
    def test_repeating_fields_only_once(self, raw_field: str) -> None:
        data = "VaLuE"
        header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
        single_header = f"{header_field}: {data}"
        raw, unparsed = metadata.parse_email(single_header)
        assert not unparsed
        assert len(raw) == 1
        assert raw_field in raw
        assert raw[raw_field] == [data]  # type: ignore[literal-required]

    @pytest.mark.parametrize("raw_field", sorted(metadata._LIST_FIELDS))
    def test_repeating_fields_repeated(self, raw_field: str) -> None:
        header_field = metadata._RAW_TO_EMAIL_MAPPING[raw_field]
        data = "VaLuE"
        single_header = f"{header_field}: {data}"
        repeated_header = "\n".join([single_header] * 2)
        raw, unparsed = metadata.parse_email(repeated_header)
        assert not unparsed
        assert len(raw) == 1
        assert raw_field in raw
        assert raw[raw_field] == [data] * 2  # type: ignore[literal-required]

    @pytest.mark.parametrize(
        ("given", "expected"),
        [
            ("A", ["A"]),
            ("A ", ["A"]),
            (" A", ["A"]),
            ("A, B", ["A", "B"]),
            ("A,B", ["A", "B"]),
            (" A, B", ["A", "B"]),
            ("A,B ", ["A", "B"]),
            ("A B", ["A B"]),
        ],
    )
    def test_keywords(self, given: str, expected: list[str]) -> None:
        header = f"Keywords: {given}"
        raw, unparsed = metadata.parse_email(header)
        assert not unparsed
        assert len(raw) == 1
        assert "keywords" in raw
        assert raw["keywords"] == expected

    @pytest.mark.parametrize(
        ("given", "expected"),
        [
            ("", {"": ""}),
            ("A", {"A": ""}),
            ("A,B", {"A": "B"}),
            ("A, B", {"A": "B"}),
            (" A,B", {"A": "B"}),
            ("A,B ", {"A": "B"}),
            ("A,B,C", {"A": "B,C"}),
        ],
    )
    def test_project_urls_parsing(self, given: str, expected: dict[str, str]) -> None:
        header = f"project-url: {given}"
        raw, unparsed = metadata.parse_email(header)
        assert not unparsed
        assert len(raw) == 1
        assert "project_urls" in raw
        assert raw["project_urls"] == expected

    def test_duplicate_project_urls(self) -> None:
        header = "project-url: A, B\nproject-url: A, C"
        raw, unparsed = metadata.parse_email(header)
        assert not raw
        assert len(unparsed) == 1
        assert "project-url" in unparsed
        assert unparsed["project-url"] == ["A, B", "A, C"]

    def test_str_input(self) -> None:
        name = "Tarek Ziadé"
        header = f"author: {name}"
        raw, unparsed = metadata.parse_email(header)
        assert not unparsed
        assert len(raw) == 1
        assert "author" in raw
        assert raw["author"] == name

    def test_bytes_input(self) -> None:
        name = "Tarek Ziadé"
        header = f"author: {name}".encode()
        raw, unparsed = metadata.parse_email(header)
        assert not unparsed
        assert len(raw) == 1
        assert "author" in raw
        assert raw["author"] == name

    def test_header_mojibake(self) -> None:
        value = "\xc0msterdam"
        header_name = "value"
        header_bytes = f"{header_name}: {value}".encode("latin1")
        raw, unparsed = metadata.parse_email(header_bytes)
        # Sanity check
        with pytest.raises(UnicodeDecodeError):
            header_bytes.decode("utf-8")
        assert not raw
        assert len(unparsed) == 1
        assert header_name in unparsed
        assert unparsed[header_name] == [value]

    @pytest.mark.parametrize("given", ["hello", "description: hello", b"hello"])
    def test_description(self, given: str | bytes) -> None:
        raw, unparsed = metadata.parse_email(given)
        assert not unparsed
        assert len(raw) == 1
        assert "description" in raw
        assert raw["description"] == "hello"

    def test_description_non_utf8(self) -> None:
        header = "\xc0msterdam"
        header_bytes = header.encode("latin1")
        raw, unparsed = metadata.parse_email(header_bytes)
        assert not raw
        assert len(unparsed) == 1
        assert "description" in unparsed
        # TODO: type annotations are not happy about this, investigate.
        assert unparsed["description"] == [header_bytes]  # type: ignore[comparison-overlap]

    @pytest.mark.parametrize(
        ("given", "expected"),
        [
            ("description: 1\ndescription: 2", ["1", "2"]),
            ("description: 1\n\n2", ["1", "2"]),
            ("description: 1\ndescription: 2\n\n3", ["1", "2", "3"]),
        ],
    )
    def test_description_multiple(
        self, given: str | bytes, expected: list[str]
    ) -> None:
        raw, unparsed = metadata.parse_email(given)
        assert not raw
        assert len(unparsed) == 1
        assert "description" in unparsed
        assert unparsed["description"] == expected

    def test_lowercase_keys(self) -> None:
        header = "AUTHOR: Tarek Ziadé\nWhatever: Else"
        raw, unparsed = metadata.parse_email(header)
        assert len(raw) == 1
        assert "author" in raw
        assert len(unparsed) == 1
        assert "whatever" in unparsed

    def test_complete(self) -> None:
        """Test all fields (except `Obsoletes-Dist`).

        `Obsoletes-Dist` was sacrificed to provide a value for `Dynamic`.
        """
        path = pathlib.Path(__file__).parent / "metadata" / "everything.metadata"
        with path.open("r", encoding="utf-8") as file:
            metadata_contents = file.read()
        raw, unparsed = metadata.parse_email(metadata_contents)
        assert len(unparsed) == 1  # "ThisIsNotReal" key
        assert unparsed["thisisnotreal"] == ["Hello!"]
        assert len(raw) == 28
        assert raw["metadata_version"] == "2.5"
        assert raw["name"] == "BeagleVote"
        assert raw["version"] == "1.0a2"
        assert raw["platforms"] == ["ObscureUnix", "RareDOS"]
        assert raw["supported_platforms"] == ["RedHat 7.2", "i386-win32-2791"]
        assert raw["summary"] == "A module for collecting votes from beagles."
        assert (
            raw["description_content_type"]
            == "text/markdown; charset=UTF-8; variant=GFM"
        )
        assert raw["keywords"] == ["dog", "puppy", "voting", "election"]
        assert raw["home_page"] == "http://www.example.com/~cschultz/bvote/"
        assert raw["download_url"] == "…/BeagleVote-0.45.tgz"
        assert raw["author"] == (
            "C. Schultz, Universal Features Syndicate,\n"
            "        Los Angeles, CA "
        )
        assert raw["author_email"] == '"C. Schultz" '
        assert raw["maintainer"] == (
            "C. Schultz, Universal Features Syndicate,\n"
            "        Los Angeles, CA "
        )
        assert raw["maintainer_email"] == '"C. Schultz" '
        assert raw["license"] == (
            "This software may only be obtained by sending the\n"
            "        author a postcard, and then the user promises not\n"
            "        to redistribute it."
        )
        assert raw["license_expression"] == "Apache-2.0 OR BSD-2-Clause"
        assert raw["license_files"] == ["LICENSE.APACHE", "LICENSE.BSD"]
        assert raw["classifiers"] == [
            "Development Status :: 4 - Beta",
            "Environment :: Console (Text Based)",
        ]
        assert raw["provides_extra"] == ["pdf"]
        assert raw["requires_dist"] == [
            "reportlab; extra == 'pdf'",
            "pkginfo",
            "PasteDeploy",
            "zope.interface (>3.5.0)",
            "pywin32 >1.0; sys_platform == 'win32'",
        ]
        assert raw["requires_python"] == ">=3"
        assert raw["requires_external"] == [
            "C",
            "libpng (>=1.5)",
            'make; sys_platform != "win32"',
        ]
        assert raw["project_urls"] == {
            "Bug Tracker": "http://bitbucket.org/tarek/distribute/issues/",
            "Documentation": "https://example.com/BeagleVote",
        }
        assert raw["provides_dist"] == [
            "OtherProject",
            "AnotherProject (3.4)",
            'virtual_package; python_version >= "3.4"',
        ]
        assert raw["dynamic"] == ["Obsoletes-Dist"]
        assert raw["description"] == "This description intentionally left blank.\n"
        assert raw["import_names"] == ["beaglevote", "_beaglevote ; private"]
        assert raw["import_namespaces"] == ["spam", "_bacon ; private"]


class TestExceptionGroup:
    def test_attributes(self) -> None:
        individual_exception = Exception("not important")
        exc = metadata.ExceptionGroup("message", [individual_exception])
        assert exc.message == "message"
        assert list(exc.exceptions) == [individual_exception]

    def test_repr(self) -> None:
        individual_exception = RuntimeError("not important")
        exc = metadata.ExceptionGroup("message", [individual_exception])
        assert individual_exception.__class__.__name__ in repr(exc)


_RAW_EXAMPLE: RawMetadata = {
    "metadata_version": "2.5",
    "name": "packaging",
    "version": "2023.0.0",
}


class TestMetadata:
    def _invalid_with_cause(
        self,
        meta: metadata.Metadata,
        attr: str,
        cause: type[BaseException] | None = None,
        *,
        field: str | None = None,
    ) -> None:
        if field is None:
            field = attr
        with pytest.raises(metadata.InvalidMetadata) as exc_info:
            getattr(meta, attr)
        exc = exc_info.value
        assert exc.field == field
        if cause is None:
            assert exc.__cause__ is None
        else:
            assert isinstance(exc.__cause__, cause)

    def test_from_email(self) -> None:
        metadata_version = "2.5"
        meta = metadata.Metadata.from_email(
            f"Metadata-Version: {metadata_version}", validate=False
        )

        assert meta.metadata_version == metadata_version
        assert meta.import_names is None

    def test_from_email_empty_import_name(self) -> None:
        meta = metadata.Metadata.from_email(
            "Metadata-Version: 2.5\nImport-Name:\n", validate=False
        )
        assert meta.import_names == []

    def test_from_email_unparsed(self) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email("Hello: PyPA")

        assert len(exc_info.value.exceptions) == 1
        assert isinstance(exc_info.value.exceptions[0], metadata.InvalidMetadata)

    def test_from_email_validate(self) -> None:
        with pytest.raises(ExceptionGroup):
            # Lacking all required fields.
            metadata.Metadata.from_email("Name: packaging", validate=True)

    def test_from_email_unparsed_valid_field_name(self) -> None:
        with pytest.raises(ExceptionGroup):
            metadata.Metadata.from_email(
                "Project-URL: A, B\nProject-URL: A, C", validate=True
            )

    def test_required_fields(self) -> None:
        meta = metadata.Metadata.from_raw(_RAW_EXAMPLE)

        assert meta.metadata_version == _RAW_EXAMPLE["metadata_version"]

    @pytest.mark.parametrize("field", list(_RAW_EXAMPLE.keys()))
    def test_required_fields_missing(self, field: str) -> None:
        required_fields = _RAW_EXAMPLE.copy()

        del required_fields[field]  # type: ignore[misc]

        with pytest.raises(ExceptionGroup):
            metadata.Metadata.from_raw(required_fields)

    def test_raw_validate_unrecognized_field(self) -> None:
        raw: RawMetadata = {
            "metadata_version": "2.3",
            "name": "packaging",
            "version": "2023.0.0",
        }

        # Safety check (always true)
        assert metadata.Metadata.from_raw(raw, validate=True)  # type: ignore[truthy-bool]

        # Misspelled; missing an "i":
        raw["dynamc"] = ["Obsoletes-Dist"]  # type: ignore[typeddict-unknown-key]

        with pytest.raises(ExceptionGroup):
            metadata.Metadata.from_raw(raw, validate=True)

    def test_raw_data_not_mutated(self) -> None:
        raw = _RAW_EXAMPLE.copy()
        meta = metadata.Metadata.from_raw(raw, validate=True)

        assert meta.version == version.Version(_RAW_EXAMPLE["version"])
        assert raw == _RAW_EXAMPLE

    def test_caching(self) -> None:
        meta = metadata.Metadata.from_raw(_RAW_EXAMPLE, validate=True)

        assert meta.version is meta.version

    def test_from_raw_validate(self) -> None:
        required_fields = _RAW_EXAMPLE.copy()
        required_fields["version"] = "-----"

        with pytest.raises(ExceptionGroup):
            # Multiple things to trigger a validation error:
            # invalid version, missing keys, etc.
            metadata.Metadata.from_raw(required_fields)

    @pytest.mark.parametrize("meta_version", ["2.2", "2.3"])
    def test_metadata_version_field_introduction(self, meta_version: str) -> None:
        raw: RawMetadata = {
            "metadata_version": meta_version,
            "name": "packaging",
            "version": "2023.0.0",
            "dynamic": ["Obsoletes-Dist"],  # Introduced in 2.2.
        }

        assert metadata.Metadata.from_raw(raw, validate=True)  # type: ignore[truthy-bool]

    @pytest.mark.parametrize("meta_version", ["1.0", "1.1", "1.2", "2.1"])
    def test_metadata_version_field_introduction_mismatch(
        self, meta_version: str
    ) -> None:
        raw: RawMetadata = {
            "metadata_version": meta_version,
            "name": "packaging",
            "version": "2023.0.0",
            "dynamic": ["Obsoletes-Dist"],  # Introduced in 2.2.
        }

        with pytest.raises(ExceptionGroup):
            metadata.Metadata.from_raw(raw, validate=True)

    @pytest.mark.parametrize(
        "attribute",
        [
            "description",
            "home_page",
            "download_url",
            "author",
            "author_email",
            "maintainer",
            "maintainer_email",
            "license",
        ],
    )
    def test_single_value_unvalidated_attribute(self, attribute: str) -> None:
        value = "Not important"
        meta = metadata.Metadata.from_raw({attribute: value}, validate=False)  # type: ignore[misc]

        assert getattr(meta, attribute) == value

    @pytest.mark.parametrize(
        "attribute",
        [
            "supported_platforms",
            "platforms",
            "classifiers",
            "provides_dist",
            "obsoletes_dist",
            "requires",
            "provides",
            "obsoletes",
        ],
    )
    def test_multi_value_unvalidated_attribute(self, attribute: str) -> None:
        values = ["Not important", "Still not important"]
        meta = metadata.Metadata.from_raw({attribute: values}, validate=False)  # type: ignore[misc]

        assert getattr(meta, attribute) == values

    @pytest.mark.parametrize("version", ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"])
    def test_valid_metadata_version(self, version: str) -> None:
        meta = metadata.Metadata.from_raw({"metadata_version": version}, validate=False)

        assert meta.metadata_version == version

    @pytest.mark.parametrize("version", ["1.3", "2.0"])
    def test_invalid_metadata_version(self, version: str) -> None:
        meta = metadata.Metadata.from_raw({"metadata_version": version}, validate=False)

        with pytest.raises(metadata.InvalidMetadata):
            meta.metadata_version  # noqa: B018

    def test_valid_version(self) -> None:
        version_str = "1.2.3"
        meta = metadata.Metadata.from_raw({"version": version_str}, validate=False)
        assert meta.version == version.parse(version_str)

    def test_missing_version(self) -> None:
        meta = metadata.Metadata.from_raw({}, validate=False)
        with pytest.raises(metadata.InvalidMetadata) as exc_info:
            meta.version  # noqa: B018
        assert exc_info.value.field == "version"

    def test_invalid_version(self) -> None:
        meta = metadata.Metadata.from_raw({"version": "a.b.c"}, validate=False)
        self._invalid_with_cause(meta, "version", version.InvalidVersion)

    def test_valid_summary(self) -> None:
        summary = "Hello"
        meta = metadata.Metadata.from_raw({"summary": summary}, validate=False)

        assert meta.summary == summary

    def test_invalid_summary(self) -> None:
        meta = metadata.Metadata.from_raw(
            {"summary": "Hello\n    Again"}, validate=False
        )

        with pytest.raises(metadata.InvalidMetadata) as exc_info:
            meta.summary  # noqa: B018
        assert exc_info.value.field == "summary"

    def test_valid_name(self) -> None:
        name = "Hello_World"
        meta = metadata.Metadata.from_raw({"name": name}, validate=False)
        assert meta.name == name

    def test_invalid_name(self) -> None:
        meta = metadata.Metadata.from_raw({"name": "-not-legal"}, validate=False)
        self._invalid_with_cause(meta, "name", utils.InvalidName)

    @pytest.mark.parametrize(
        "content_type",
        [
            "text/plain",
            "TEXT/PLAIN",
            "text/x-rst",
            "text/markdown",
            "text/plain; charset=UTF-8",
            "text/x-rst; charset=UTF-8",
            "text/markdown; charset=UTF-8; variant=GFM",
            "text/markdown; charset=UTF-8; variant=CommonMark",
            "text/markdown; variant=GFM",
            "text/markdown; variant=CommonMark",
        ],
    )
    def test_valid_description_content_type(self, content_type: str) -> None:
        meta = metadata.Metadata.from_raw(
            {"description_content_type": content_type}, validate=False
        )

        assert meta.description_content_type == content_type

    @pytest.mark.parametrize(
        "content_type",
        [
            "application/json",
            "text/plain; charset=ascii",
            "text/plain; charset=utf-8",
            "text/markdown; variant=gfm",
            "text/markdown; variant=commonmark",
        ],
    )
    def test_invalid_description_content_type(self, content_type: str) -> None:
        meta = metadata.Metadata.from_raw(
            {"description_content_type": content_type}, validate=False
        )

        with pytest.raises(metadata.InvalidMetadata):
            meta.description_content_type  # noqa: B018

    def test_keywords(self) -> None:
        keywords = ["hello", "world"]
        meta = metadata.Metadata.from_raw({"keywords": keywords}, validate=False)

        assert meta.keywords == keywords

    def test_valid_project_urls(self) -> None:
        urls = {
            "Documentation": "https://example.com/BeagleVote",
            "Bug Tracker": "http://bitbucket.org/tarek/distribute/issues/",
        }
        meta = metadata.Metadata.from_raw({"project_urls": urls}, validate=False)

        assert meta.project_urls == urls

    @pytest.mark.parametrize("specifier", [">=3", ">2.6,!=3.0.*,!=3.1.*", "~=2.6"])
    def test_valid_requires_python(self, specifier: str) -> None:
        expected = specifiers.SpecifierSet(specifier)
        meta = metadata.Metadata.from_raw(
            {"requires_python": specifier}, validate=False
        )

        assert meta.requires_python == expected

    def test_invalid_requires_python(self) -> None:
        meta = metadata.Metadata.from_raw(
            {"requires_python": "NotReal"}, validate=False
        )
        self._invalid_with_cause(
            meta,
            "requires_python",
            specifiers.InvalidSpecifier,
            field="requires-python",
        )

    def test_requires_external(self) -> None:
        externals = [
            "C",
            "libpng (>=1.5)",
            'make; sys_platform != "win32"',
            "libjpeg (>6b)",
        ]
        meta = metadata.Metadata.from_raw(
            {"requires_external": externals}, validate=False
        )

        assert meta.requires_external == externals

    def test_valid_provides_extra(self) -> None:
        extras = ["dev", "test"]
        meta = metadata.Metadata.from_raw({"provides_extra": extras}, validate=False)

        assert meta.provides_extra == extras

    def test_invalid_provides_extra(self) -> None:
        extras = ["pdf", "-Not-Valid", "ok"]
        meta = metadata.Metadata.from_raw({"provides_extra": extras}, validate=False)
        self._invalid_with_cause(
            meta, "provides_extra", utils.InvalidName, field="provides-extra"
        )

    def test_valid_requires_dist(self) -> None:
        requires = [
            "pkginfo",
            "PasteDeploy",
            "zope.interface (>3.5.0)",
            "pywin32 >1.0; sys_platform == 'win32'",
        ]
        expected_requires = list(map(requirements.Requirement, requires))
        meta = metadata.Metadata.from_raw({"requires_dist": requires}, validate=False)

        assert meta.requires_dist == expected_requires

    def test_invalid_requires_dist(self) -> None:
        requires = ["pkginfo", "-not-real", "zope.interface (>3.5.0)"]
        meta = metadata.Metadata.from_raw({"requires_dist": requires}, validate=False)
        self._invalid_with_cause(
            meta,
            "requires_dist",
            requirements.InvalidRequirement,
            field="requires-dist",
        )

    def test_valid_dynamic(self) -> None:
        dynamic = ["Keywords", "Home-Page", "Author"]
        meta = metadata.Metadata.from_raw({"dynamic": dynamic}, validate=False)

        assert meta.dynamic == [d.lower() for d in dynamic]

    def test_invalid_dynamic_value(self) -> None:
        dynamic = ["Keywords", "NotReal", "Author"]
        meta = metadata.Metadata.from_raw({"dynamic": dynamic}, validate=False)

        with pytest.raises(metadata.InvalidMetadata):
            meta.dynamic  # noqa: B018

    @pytest.mark.parametrize("field_name", ["name", "version", "metadata-version"])
    def test_disallowed_dynamic(self, field_name: str) -> None:
        meta = metadata.Metadata.from_raw({"dynamic": [field_name]}, validate=False)

        message = f"{field_name!r} is not allowed"
        with pytest.raises(metadata.InvalidMetadata, match=message) as execinfo:
            meta.dynamic  # noqa: B018

        # The name of the specific offending field should be used,
        # not a list with all fields:
        assert "[" not in str(execinfo.value)

    @pytest.mark.parametrize(
        "field_name",
        sorted(metadata._RAW_TO_EMAIL_MAPPING.keys() - metadata._REQUIRED_ATTRS),
    )
    def test_optional_defaults_to_none(self, field_name: str) -> None:
        meta = metadata.Metadata.from_raw({}, validate=False)
        assert getattr(meta, field_name) is None

    @pytest.mark.parametrize(
        ("license_expression", "expected"),
        [
            ("MIT", "MIT"),
            ("mit", "MIT"),
            ("BSD-3-Clause", "BSD-3-Clause"),
            ("Bsd-3-clause", "BSD-3-Clause"),
            (
                "MIT AND (Apache-2.0 OR BSD-2-Clause)",
                "MIT AND (Apache-2.0 OR BSD-2-Clause)",
            ),
            (
                "mit and (apache-2.0 or bsd-2-clause)",
                "MIT AND (Apache-2.0 OR BSD-2-Clause)",
            ),
            (
                "MIT OR GPL-2.0-or-later OR (FSFUL AND BSD-2-Clause)",
                "MIT OR GPL-2.0-or-later OR (FSFUL AND BSD-2-Clause)",
            ),
            (
                "GPL-3.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause",
                "GPL-3.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause",
            ),
            (
                "LicenseRef-Special-License OR CC0-1.0 OR Unlicense",
                "LicenseRef-Special-License OR CC0-1.0 OR Unlicense",
            ),
            ("mIt", "MIT"),
            (" mIt ", "MIT"),
            ("mit or apache-2.0", "MIT OR Apache-2.0"),
            ("mit and apache-2.0", "MIT AND Apache-2.0"),
            (
                "gpl-2.0-or-later with bison-exception-2.2",
                "GPL-2.0-or-later WITH Bison-exception-2.2",
            ),
            (
                "mit or apache-2.0 and (bsd-3-clause or mpl-2.0)",
                "MIT OR Apache-2.0 AND (BSD-3-Clause OR MPL-2.0)",
            ),
            ("mit and (apache-2.0+ or mpl-2.0+)", "MIT AND (Apache-2.0+ OR MPL-2.0+)"),
            (
                "mit  and  ( apache-2.0+  or  mpl-2.0+ )",
                "MIT AND (Apache-2.0+ OR MPL-2.0+)",
            ),
            # Valid non-SPDX values
            ("LicenseRef-Public-Domain", "LicenseRef-Public-Domain"),
            ("licenseref-public-domain", "LicenseRef-public-domain"),
            ("licenseref-proprietary", "LicenseRef-proprietary"),
            ("LicenseRef-Proprietary", "LicenseRef-Proprietary"),
            ("LicenseRef-Beerware-4.2", "LicenseRef-Beerware-4.2"),
            ("licenseref-beerware-4.2", "LicenseRef-beerware-4.2"),
            (
                "(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense",
                "(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense",
            ),
            (
                "(LicenseRef-Special-License OR licenseref-OtherLicense) OR unlicense",
                "(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense",
            ),
            # we don't canonicalize redundant parens, instead leaving them as-is
            # in the license expression.
            ("(MIT)", "(MIT)"),
            ("((MIT))", "((MIT))"),
            ("(( MIT ))", "((MIT))"),
            ("((MIT AND (MIT)))", "((MIT AND (MIT)))"),
        ],
    )
    def test_valid_license_expression(
        self, license_expression: str, expected: str
    ) -> None:
        meta = metadata.Metadata.from_raw(
            {"license_expression": license_expression}, validate=False
        )
        assert meta.license_expression == expected

    @pytest.mark.parametrize(
        "license_expression",
        [
            "",
            "Use-it-after-midnight",
            "LicenseRef-License with spaces",
            "LicenseRef-License_with_underscores",
            "or",
            "and",
            "with",
            "mit or",
            "mit and",
            "mit with",
            "or mit",
            "and mit",
            "with mit",
            "(mit",
            "mit)",
            ") mit",
            "mit (",
            "mit or or apache-2.0",
            # Missing an operator before `(`.
            "mit or apache-2.0 (bsd-3-clause and MPL-2.0)",
            # "2-BSD-Clause is not a valid license.
            "Apache-2.0 OR 2-BSD-Clause",
            # Empty parenthesis.
            "()",
            "( ) or mit",
            "mit and ( )",
            "( ) or mit and ( )",
            "( ) with ( ) or mit",
            "mit with ( ) with ( ) or mit",
        ],
    )
    def test_invalid_license_expression(self, license_expression: str) -> None:
        meta = metadata.Metadata.from_raw(
            {"license_expression": license_expression}, validate=False
        )

        with pytest.raises(metadata.InvalidMetadata):
            meta.license_expression  # noqa: B018

    @pytest.mark.parametrize(
        "license_files",
        [
            [],
            ["licenses/LICENSE.MIT", "licenses/LICENSE.CC0"],
            ["LICENSE"],
        ],
    )
    def test_valid_license_files(self, license_files: list[str]) -> None:
        meta = metadata.Metadata.from_raw(
            {"license_files": license_files}, validate=False
        )
        assert meta.license_files == license_files

    @pytest.mark.parametrize(
        "license_files",
        [
            # Can't escape out of the project's directory.
            ["../LICENSE"],
            ["./../LICENSE"],
            # Paths should be resolved.
            ["licenses/../LICENSE"],
            # Absolute paths are not allowed.
            ["/licenses/LICENSE"],
            # Paths must be valid
            # (i.e. glob pattern didn't escape out of pyproject.toml.)
            ["licenses/*"],
            # Paths must use / delimiter
            ["licenses\\LICENSE"],
        ],
    )
    def test_invalid_license_files(self, license_files: list[str]) -> None:
        meta = metadata.Metadata.from_raw(
            {"license_files": license_files}, validate=False
        )

        with pytest.raises(metadata.InvalidMetadata):
            meta.license_files  # noqa: B018

    @pytest.mark.parametrize("key", ["import_namespaces", "import_names"])
    def test_valid_import_names(self, key: str) -> None:
        import_names = [
            "packaging",
            "packaging.metadata",
            "_utils ; private",
            "_stuff;private",
        ]
        meta = metadata.Metadata.from_raw({key: import_names}, validate=False)  # type: ignore[misc]
        assert getattr(meta, key) == import_names

    @pytest.mark.parametrize("key", ["import_namespaces", "import_names"])
    @pytest.mark.parametrize(
        "name", ["not-valid", "still.not-valid", "stuff;", "stuff; extra"]
    )
    def test_invalid_import_names_identifier(self, key: str, name: str) -> None:
        meta = metadata.Metadata.from_raw({key: [name]}, validate=False)  # type: ignore[misc]

        with pytest.raises(metadata.InvalidMetadata):
            getattr(meta, key)

    @pytest.mark.parametrize("key", ["import_namespaces", "import_names"])
    def test_invalid_import_names_keyword(self, key: str) -> None:
        import_names = ["class"]
        meta = metadata.Metadata.from_raw({key: import_names}, validate=False)  # type: ignore[misc]

        with pytest.raises(metadata.InvalidMetadata):
            getattr(meta, key)


class TestMetadataWriting:
    def test_write_metadata(self) -> None:
        meta = metadata.Metadata.from_raw(_RAW_EXAMPLE)
        written = meta.as_rfc822().as_string()
        assert (
            written == "metadata-version: 2.5\nname: packaging\nversion: 2023.0.0\n\n"
        )

    def test_write_metadata_with_description(self) -> None:
        # Intentionally out of order to make sure it is written in order
        meta = metadata.Metadata.from_raw(
            {
                "version": "1.2.3",
                "name": "Hello",
                "description": "Hello\n\nWorld👋",
                "metadata_version": "2.3",
            }
        )
        written = meta.as_rfc822().as_string()
        assert (
            written == "metadata-version: 2.3\nname: Hello\n"
            "version: 1.2.3\n\nHello\n\nWorld👋"
        )
        written_bytes = meta.as_rfc822().as_bytes()
        assert (
            written_bytes
            == "metadata-version: 2.3\nname: Hello\n"
            "version: 1.2.3\n\nHello\n\nWorld👋".encode()
        )

    def test_multiline_license(self) -> None:
        meta = metadata.Metadata.from_raw(
            {
                "version": "1.2.3",
                "name": "packaging",
                "license": "Hello\nWorld🐍",
                "metadata_version": "2.3",
            }
        )
        written = meta.as_rfc822().as_string()
        assert (
            written == "metadata-version: 2.3\nname: packaging\nversion: 1.2.3"
            "\nlicense: Hello\n         World🐍\n\n"
        )
        written_bytes = meta.as_rfc822().as_bytes()
        assert (
            written_bytes
            == "metadata-version: 2.3\nname: packaging\nversion: 1.2.3"
            "\nlicense: Hello\n         World🐍\n\n".encode()
        )

    def test_large(self) -> None:
        meta = metadata.Metadata.from_raw(
            {
                "author": "Example!",
                "author_email": "Unknown ",
                "classifiers": [
                    "Development Status :: 4 - Beta",
                    "Programming Language :: Python",
                ],
                "description": "some readme 👋\n",
                "description_content_type": "text/markdown",
                "keywords": ["trampolim", "is", "interesting"],
                "license": "some license text",
                "maintainer_email": "Other Example ",
                "metadata_version": "2.1",
                "name": "full_metadata",
                "project_urls": {
                    "homepage": "example.com",
                    "documentation": "readthedocs.org",
                    "repository": "github.com/some/repo",
                    "changelog": "github.com/some/repo/blob/master/CHANGELOG.rst",
                },
                "provides_extra": ["test"],
                "requires_dist": [
                    "dependency1",
                    "dependency2>1.0.0",
                    "dependency3[extra]",
                    'dependency4; os_name != "nt"',
                    'dependency5[other-extra]>1.0; os_name == "nt"',
                    'test_dependency; extra == "test"',
                    'test_dependency[test_extra]; extra == "test"',
                    "test_dependency[test_extra2]>3.0; "
                    'os_name == "nt" and extra == "test"',
                ],
                "requires_python": ">=3.8",
                "summary": "A package with all the metadata :)",
                "version": "3.2.1",
            }
        )

        core_metadata = meta.as_rfc822()
        assert core_metadata.items() == [
            ("metadata-version", "2.1"),
            ("name", "full_metadata"),
            ("version", "3.2.1"),
            ("summary", "A package with all the metadata :)"),
            ("description-content-type", "text/markdown"),
            ("keywords", "trampolim,is,interesting"),
            ("author", "Example!"),
            ("author-email", "Unknown "),
            ("maintainer-email", "Other Example "),
            ("license", "some license text"),
            ("classifier", "Development Status :: 4 - Beta"),
            ("classifier", "Programming Language :: Python"),
            ("requires-dist", "dependency1"),
            ("requires-dist", "dependency2>1.0.0"),
            ("requires-dist", "dependency3[extra]"),
            ("requires-dist", 'dependency4; os_name != "nt"'),
            ("requires-dist", 'dependency5[other-extra]>1.0; os_name == "nt"'),
            ("requires-dist", 'test_dependency; extra == "test"'),
            ("requires-dist", 'test_dependency[test_extra]; extra == "test"'),
            (
                "requires-dist",
                'test_dependency[test_extra2]>3.0; os_name == "nt" and extra == "test"',
            ),
            ("requires-python", ">=3.8"),
            ("project-url", "homepage, example.com"),
            ("project-url", "documentation, readthedocs.org"),
            ("project-url", "repository, github.com/some/repo"),
            (
                "project-url",
                "changelog, github.com/some/repo/blob/master/CHANGELOG.rst",
            ),
            ("provides-extra", "test"),
        ]

        assert core_metadata.get_payload() == "some readme 👋\n"

    def test_modern_license(self) -> None:
        meta = metadata.Metadata.from_raw(
            {
                "metadata_version": "2.4",
                "name": "full_metadata",
                "version": "3.2.1",
                "license_expression": "MIT",
                "license_files": ["LICENSE.txt", "LICENSE"],
            }
        )

        core_metadata = meta.as_rfc822()
        assert core_metadata.items() == [
            ("metadata-version", "2.4"),
            ("name", "full_metadata"),
            ("version", "3.2.1"),
            ("license-expression", "MIT"),
            ("license-file", "LICENSE.txt"),
            ("license-file", "LICENSE"),
        ]

        assert core_metadata.get_payload() is None

    def test__import_names(self) -> None:
        meta = metadata.Metadata.from_raw(
            {
                "metadata_version": "2.5",
                "name": "full_metadata",
                "version": "3.2.1",
                "import_names": ["one", "two"],
                "import_namespaces": ["three"],
            }
        )

        core_metadata = meta.as_rfc822()
        assert core_metadata.items() == [
            ("metadata-version", "2.5"),
            ("name", "full_metadata"),
            ("version", "3.2.1"),
            ("import-name", "one"),
            ("import-name", "two"),
            ("import-namespace", "three"),
        ]

        assert core_metadata.get_payload() is None

    def test_empty_import_names(self) -> None:
        meta = metadata.Metadata.from_raw(
            {
                "metadata_version": "2.5",
                "name": "full_metadata",
                "version": "3.2.1",
                "import_names": [],
            }
        )

        core_metadata = meta.as_rfc822()
        assert core_metadata.items() == [
            ("metadata-version", "2.5"),
            ("name", "full_metadata"),
            ("version", "3.2.1"),
            ("import-name", ""),
        ]

        assert core_metadata.get_payload() is None

    @pytest.mark.parametrize(
        ("items", "data"),
        [
            pytest.param(
                [],
                "",
                id="empty",
            ),
            pytest.param(
                [
                    ("Foo", "Bar"),
                ],
                "Foo: Bar\n",
                id="simple",
            ),
            pytest.param(
                [
                    ("Foo", "Bar"),
                    ("Foo2", "Bar2"),
                ],
                """\
                Foo: Bar
                Foo2: Bar2
                """,
                id="multiple",
            ),
            pytest.param(
                [
                    ("Foo", "Unicøde"),
                ],
                "Foo: Unicøde\n",
                id="unicode",
            ),
            pytest.param(
                [
                    ("Foo", "🕵️"),
                ],
                "Foo: 🕵️\n",
                id="emoji",
            ),
            pytest.param(
                [
                    ("Item", None),
                ],
                "",
                id="none",
            ),
            pytest.param(
                [
                    ("ItemA", "ValueA"),
                    ("ItemB", "ValueB"),
                    ("ItemC", "ValueC"),
                ],
                """\
                ItemA: ValueA
                ItemB: ValueB
                ItemC: ValueC
                """,
                id="order 1",
            ),
            pytest.param(
                [
                    ("ItemB", "ValueB"),
                    ("ItemC", "ValueC"),
                    ("ItemA", "ValueA"),
                ],
                """\
                ItemB: ValueB
                ItemC: ValueC
                ItemA: ValueA
                """,
                id="order 2",
            ),
            pytest.param(
                [
                    ("ItemA", "ValueA1"),
                    ("ItemB", "ValueB"),
                    ("ItemC", "ValueC"),
                    ("ItemA", "ValueA2"),
                ],
                """\
                ItemA: ValueA1
                ItemB: ValueB
                ItemC: ValueC
                ItemA: ValueA2
                """,
                id="multiple keys",
            ),
            pytest.param(
                [
                    ("ItemA", "ValueA"),
                    ("ItemB", "ValueB1\nValueB2\nValueB3"),
                    ("ItemC", "ValueC"),
                ],
                """\
                ItemA: ValueA
                ItemB: ValueB1
                       ValueB2
                       ValueB3
                ItemC: ValueC
                """,
                id="multiline",
            ),
        ],
    )
    def test_headers(self, items: list[tuple[str, None | str]], data: str) -> None:
        message = metadata.RFC822Message()

        for name, value in items:
            if value:
                message[name] = value

        data = textwrap.dedent(data) + "\n"
        assert str(message) == data
        assert bytes(message) == data.encode()

        assert email.message_from_string(str(message)).items() == [
            (a, "\n       ".join(b.splitlines())) for a, b in items if b is not None
        ]

    def test_body(self) -> None:
        message = metadata.RFC822Message()

        message["ItemA"] = "ValueA"
        message["ItemB"] = "ValueB"
        message["ItemC"] = "ValueC"
        body = inspect.cleandoc(
            """
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
            congue semper fermentum. Nunc vitae tempor ante. Aenean aliquet
            posuere lacus non faucibus.  In porttitor congue luctus. Vivamus eu
            dignissim orci. Donec egestas mi ac ipsum volutpat, vel elementum
            sapien consectetur. Praesent dictum finibus fringilla. Sed vel
            feugiat leo. Nulla a pharetra augue, at tristique metus.

            Aliquam fermentum elit at risus sagittis, vel pretium augue congue.
            Donec leo risus, faucibus vel posuere efficitur, feugiat ut leo.
            Aliquam vestibulum vel dolor id elementum. Ut bibendum nunc interdum
            neque interdum, vel tincidunt lacus blandit. Ut volutpat
            sollicitudin dapibus. Integer vitae lacinia ex, eget finibus nulla.
            Donec sit amet ante in neque pulvinar faucibus sed nec justo.  Fusce
            hendrerit massa libero, sit amet pulvinar magna tempor quis. ø
            """
        )
        headers = inspect.cleandoc(
            """
            ItemA: ValueA
            ItemB: ValueB
            ItemC: ValueC
            """
        )
        full = f"{headers}\n\n{body}"

        message.set_payload(textwrap.dedent(body))

        assert str(message) == full

        new_message = email.message_from_string(str(message))
        assert new_message.items() == message.items()
        assert new_message.get_payload() == message.get_payload()

        assert bytes(message) == full.encode("utf-8")
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_musllinux.py0000644000000000000000000000554315133751156015144 0ustar00from __future__ import annotations

import collections
import pathlib
import subprocess
import typing

import pretend
import pytest

from packaging import _musllinux
from packaging._musllinux import _get_musl_version, _MuslVersion, _parse_musl_version

if typing.TYPE_CHECKING:
    from collections.abc import Generator

MUSL_AMD64 = "musl libc (x86_64)\nVersion 1.2.2\n"
MUSL_I386 = "musl libc (i386)\nVersion 1.2.1\n"
MUSL_AARCH64 = "musl libc (aarch64)\nVersion 1.1.24\n"
MUSL_INVALID = "musl libc (invalid)\n"
MUSL_UNKNOWN = "musl libc (unknown)\nVersion unknown\n"

MUSL_DIR = pathlib.Path(__file__).with_name("musllinux").resolve()

BIN_GLIBC_X86_64 = MUSL_DIR.joinpath("glibc-x86_64")
BIN_MUSL_X86_64 = MUSL_DIR.joinpath("musl-x86_64")
BIN_MUSL_I386 = MUSL_DIR.joinpath("musl-i386")
BIN_MUSL_AARCH64 = MUSL_DIR.joinpath("musl-aarch64")

LD_MUSL_X86_64 = "/lib/ld-musl-x86_64.so.1"
LD_MUSL_I386 = "/lib/ld-musl-i386.so.1"
LD_MUSL_AARCH64 = "/lib/ld-musl-aarch64.so.1"


@pytest.fixture(autouse=True)
def clear_lru_cache() -> Generator[None, None, None]:
    yield
    _get_musl_version.cache_clear()


@pytest.mark.parametrize(
    ("output", "version"),
    [
        (MUSL_AMD64, _MuslVersion(1, 2)),
        (MUSL_I386, _MuslVersion(1, 2)),
        (MUSL_AARCH64, _MuslVersion(1, 1)),
        (MUSL_INVALID, None),
        (MUSL_UNKNOWN, None),
    ],
    ids=["amd64-1.2.2", "i386-1.2.1", "aarch64-1.1.24", "invalid", "unknown"],
)
def test_parse_musl_version(output: str, version: _MuslVersion | None) -> None:
    assert _parse_musl_version(output) == version


@pytest.mark.parametrize(
    ("executable", "output", "version", "ld_musl"),
    [
        (MUSL_DIR.joinpath("does-not-exist"), "error", None, None),
        (BIN_GLIBC_X86_64, "error", None, None),
        (BIN_MUSL_X86_64, MUSL_AMD64, _MuslVersion(1, 2), LD_MUSL_X86_64),
        (BIN_MUSL_I386, MUSL_I386, _MuslVersion(1, 2), LD_MUSL_I386),
        (BIN_MUSL_AARCH64, MUSL_AARCH64, _MuslVersion(1, 1), LD_MUSL_AARCH64),
    ],
    ids=["does-not-exist", "glibc", "x86_64", "i386", "aarch64"],
)
def test_get_musl_version(
    monkeypatch: pytest.MonkeyPatch,
    executable: pathlib.Path,
    output: str,
    version: _MuslVersion | None,
    ld_musl: str | None,
) -> None:
    def mock_run(*args: object, **kwargs: object) -> tuple[object, ...]:
        return collections.namedtuple("Proc", "stderr")(output)

    run_recorder = pretend.call_recorder(mock_run)
    monkeypatch.setattr(_musllinux.subprocess, "run", run_recorder)  # type: ignore[attr-defined]

    assert _get_musl_version(str(executable)) == version

    if ld_musl is not None:
        expected_calls = [
            pretend.call(
                [ld_musl],
                check=False,
                stderr=subprocess.PIPE,
                text=True,
            )
        ]
    else:
        expected_calls = []
    assert run_recorder.calls == expected_calls
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_pylock.py0000644000000000000000000004053015133751156014400 0ustar00from __future__ import annotations

import datetime
import sys
from pathlib import Path
from typing import Any

import pytest
import tomli_w

from packaging.markers import Marker
from packaging.pylock import (
    Package,
    PackageDirectory,
    PackageVcs,
    PackageWheel,
    Pylock,
    PylockUnsupportedVersionError,
    PylockValidationError,
    is_valid_pylock_path,
)
from packaging.specifiers import SpecifierSet
from packaging.utils import NormalizedName
from packaging.version import Version

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib


@pytest.mark.parametrize(
    ("file_name", "valid"),
    [
        ("pylock.toml", True),
        ("pylock.spam.toml", True),
        ("pylock.json", False),
        ("pylock..toml", False),
    ],
)
def test_pylock_file_name(file_name: str, valid: bool) -> None:
    assert is_valid_pylock_path(Path(file_name)) is valid


def test_toml_roundtrip() -> None:
    pep751_example = (
        Path(__file__).parent / "pylock" / "pylock.spec-example.toml"
    ).read_text()
    pylock_dict = tomllib.loads(pep751_example)
    pylock = Pylock.from_dict(pylock_dict)
    # Check that the roundrip via Pylock dataclasses produces the same TOML
    # output, modulo TOML serialization differences.
    assert tomli_w.dumps(pylock.to_dict()) == tomli_w.dumps(pylock_dict)


@pytest.mark.parametrize("version", ["1.0", "1.1"])
def test_pylock_version(version: str) -> None:
    data = {
        "lock-version": version,
        "created-by": "pip",
        "packages": [],
    }
    Pylock.from_dict(data)


@pytest.mark.parametrize("version", ["0.9", "2", "2.0", "2.1"])
def test_pylock_unsupported_version(version: str) -> None:
    data = {
        "lock-version": version,
        "created-by": "pip",
        "packages": [],
    }
    with pytest.raises(PylockUnsupportedVersionError):
        Pylock.from_dict(data)


def test_pylock_invalid_version() -> None:
    data = {
        "lock-version": "2.x",
        "created-by": "pip",
        "packages": [],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == "Invalid version: '2.x' in 'lock-version'"


def test_pylock_unexpected_type() -> None:
    data = {
        "lock-version": 1.0,
        "created-by": "pip",
        "packages": [],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Unexpected type float (expected str) in 'lock-version'"
    )


def test_pylock_missing_version() -> None:
    data = {
        "created-by": "pip",
        "packages": [],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == "Missing required value in 'lock-version'"


def test_pylock_missing_created_by() -> None:
    data = {
        "lock-version": "1.0",
        "packages": [],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == "Missing required value in 'created-by'"


def test_pylock_missing_packages() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "uv",
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == "Missing required value in 'packages'"


def test_pylock_packages_without_dist() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [{"name": "example", "version": "1.0"}],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Exactly one of vcs, directory, archive must be set "
        "if sdist and wheels are not set "
        "in 'packages[0]'"
    )


def test_pylock_packages_with_dist_and_archive() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "version": "1.0",
                "archive": {
                    "path": "example.tar.gz",
                    "hashes": {"sha256": "f" * 40},
                },
                "sdist": {
                    "path": "example.tar.gz",
                    "hashes": {"sha256": "f" * 40},
                },
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "None of vcs, directory, archive must be set "
        "if sdist or wheels are set "
        "in 'packages[0]'"
    )


def test_pylock_packages_with_archive_directory_and_vcs() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "version": "1.0",
                "archive": {
                    "path": "example.tar.gz",
                    "hashes": {"sha256": "f" * 40},
                },
                "vcs": {
                    "type": "git",
                    "url": "https://githhub/pypa/packaging",
                    "commit-id": "...",
                },
                "directory": {
                    "path": ".",
                    "editable": False,
                },
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Exactly one of vcs, directory, archive must be set "
        "if sdist and wheels are not set "
        "in 'packages[0]'"
    )


def test_pylock_basic_package() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "requires-python": ">=3.10",
        "environments": ['os_name == "posix"'],
        "packages": [
            {
                "name": "example",
                "version": "1.0",
                "marker": 'os_name == "posix"',
                "requires-python": "!=3.10.1,>=3.10",
                "directory": {
                    "path": ".",
                    "editable": False,
                },
            }
        ],
    }
    pylock = Pylock.from_dict(data)
    assert pylock.environments == [Marker('os_name == "posix"')]
    package = pylock.packages[0]
    assert package.version == Version("1.0")
    assert package.marker == Marker('os_name == "posix"')
    assert package.requires_python == SpecifierSet(">=3.10, !=3.10.1")
    assert pylock.to_dict() == data


def test_pylock_vcs_package() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "packaging",
                "vcs": {
                    "type": "git",
                    "url": "https://githhub/pypa/packaging",
                    "commit-id": "...",
                },
            }
        ],
    }
    pylock = Pylock.from_dict(data)
    assert pylock.to_dict() == data


def test_pylock_invalid_archive() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "requires-python": ">=3.10",
        "environments": ['os_name == "posix"'],
        "packages": [
            {
                "name": "example",
                "archive": {
                    # "path": "example.tar.gz",
                    "hashes": {"sha256": "f" * 40},
                },
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "path or url must be provided in 'packages[0].archive'"
    )


def test_pylock_invalid_vcs() -> None:
    with pytest.raises(PylockValidationError) as exc_info:
        PackageVcs._from_dict({"type": "git", "commit-id": "f" * 40})
    assert str(exc_info.value) == "path or url must be provided"


def test_pylock_invalid_wheel() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "requires-python": ">=3.10",
        "environments": ['os_name == "posix"'],
        "packages": [
            {
                "name": "example",
                "wheels": [
                    {
                        "name": "example-1.0-py3-none-any.whl",
                        "path": "./example-1.0-py3-none-any.whl",
                        # Purposefully no "hashes" key.
                    }
                ],
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Missing required value in 'packages[0].wheels[0].hashes'"
    )


def test_pylock_invalid_environments() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "environments": [
            'os_name == "posix"',
            'invalid_marker == "..."',
        ],
        "packages": [],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Expected a marker variable or quoted string\n"
        '    invalid_marker == "..."\n'
        "    ^ "
        "in 'environments[1]'"
    )


def test_pylock_invalid_environments_type() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "environments": [
            'os_name == "posix"',
            1,
        ],
        "packages": [],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Unexpected type int (expected str) in 'environments[1]'"
    )


def test_pylock_extras_and_groups() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "extras": ["feat1", "feat2"],
        "dependency-groups": ["dev", "docs"],
        "default-groups": ["dev"],
        "packages": [],
    }
    pylock = Pylock.from_dict(data)
    assert pylock.extras == ["feat1", "feat2"]
    assert pylock.dependency_groups == ["dev", "docs"]
    assert pylock.default_groups == ["dev"]


def test_pylock_tool() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "sdist": {
                    "name": "example-1.0.tar.gz",
                    "path": "./example-1.0.tar.gz",
                    "upload-time": datetime.datetime(
                        2023, 10, 1, 0, 0, tzinfo=datetime.timezone.utc
                    ),
                    "hashes": {"sha256": "f" * 40},
                },
                "tool": {"pip": {"foo": "bar"}},
            }
        ],
        "tool": {"pip": {"version": "25.2"}},
    }
    pylock = Pylock.from_dict(data)
    assert pylock.tool == {"pip": {"version": "25.2"}}
    package = pylock.packages[0]
    assert package.tool == {"pip": {"foo": "bar"}}


def test_pylock_package_not_a_table() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": ["example"],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Unexpected type str (expected Mapping) in 'packages[0]'"
    )


@pytest.mark.parametrize(
    ("hashes", "expected_error"),
    [
        (
            {
                "sha256": "f" * 40,
                "md5": 1,
            },
            "Hash values must be strings in 'hashes'",
        ),
        (
            {},
            "At least one hash must be provided in 'hashes'",
        ),
        (
            "sha256:...",
            "Unexpected type str (expected Mapping) in 'hashes'",
        ),
    ],
)
def test_hash_validation(hashes: dict[str, Any], expected_error: str) -> None:
    with pytest.raises(PylockValidationError) as exc_info:
        PackageWheel._from_dict(
            dict(
                name="example-1.0-py3-none-any.whl",
                upload_time=None,
                url="https://example.com/example-1.0-py3-none-any.whl",
                path=None,
                size=None,
                hashes=hashes,
            )
        )
    assert str(exc_info.value) == expected_error


def test_package_name_validation() -> None:
    with pytest.raises(PylockValidationError) as exc_info:
        Package._from_dict({"name": "Example"})
    assert str(exc_info.value) == "Name 'Example' is not normalized in 'name'"


def test_extras_name_validation() -> None:
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(
            {
                "lock-version": "1.0",
                "created-by": "pip",
                "extras": ["extra", "Feature"],
                "packages": [],
            }
        )
    assert str(exc_info.value) == "Name 'Feature' is not normalized in 'extras[1]'"


def test_is_direct() -> None:
    direct_package = Package(
        name=NormalizedName("example"),
        directory=PackageDirectory(path="."),
    )
    assert direct_package.is_direct
    wheel_package = Package(
        name=NormalizedName("example"),
        wheels=[
            PackageWheel(
                url="https://example.com/example-1.0-py3-none-any.whl",
                hashes={"sha256": "f" * 40},
            )
        ],
    )
    assert not wheel_package.is_direct


def test_validate() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=NormalizedName("example-package"),
                version=Version("1.0.0"),
                wheels=[
                    PackageWheel(
                        url="https://example.com/example_package-1.0.0-py3-none-any.whl",
                        hashes={"sha256": "0fd.."},
                    )
                ],
            )
        ],
    )
    pylock.validate()  # Should not raise any exceptions
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=NormalizedName("example_package"),  # not normalized
                version=Version("1.0.0"),
                wheels=[
                    PackageWheel(
                        url="https://example.com/example_package-1.0.0-py3-none-any.whl",
                        hashes={"sha256": "0fd.."},
                    )
                ],
            )
        ],
    )
    with pytest.raises(PylockValidationError) as exc_info:
        pylock.validate()
    assert (
        str(exc_info.value)
        == "Name 'example_package' is not normalized in 'packages[0].name'"
    )


def test_validate_sequence_of_str() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[],
        dependency_groups="abc",  # should be a sequence of str
    )
    with pytest.raises(PylockValidationError) as exc_info:
        pylock.validate()
    assert str(exc_info.value) == (
        "Unexpected type str (expected Sequence) in 'dependency-groups'"
    )


def test_validate_attestation_identity_missing_kind() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "version": "1.0",
                "directory": {
                    "path": ".",
                },
                "attestation-identities": [
                    {
                        # missing "kind" field
                        "value": "some-value",
                    }
                ],
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Missing required value in 'packages[0].attestation-identities[0].kind'"
    )


def test_validate_attestation_identity_invalid_kind() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "version": "1.0",
                "directory": {
                    "path": ".",
                },
                "attestation-identities": [
                    {
                        "kind": 123,
                        "value": "some-value",
                    }
                ],
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Unexpected type int (expected str) "
        "in 'packages[0].attestation-identities[0].kind'"
    )
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_requirements.py0000644000000000000000000005154215133751156015627 0ustar00# 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 pytest

from packaging.markers import Marker
from packaging.requirements import InvalidRequirement, Requirement
from packaging.specifiers import SpecifierSet

EQUAL_DEPENDENCIES = [
    ("packaging>20.1", "packaging>20.1"),
    (
        'requests[security, tests]>=2.8.1,==2.8.*;python_version<"2.7"',
        'requests [security,tests] >= 2.8.1, == 2.8.* ; python_version < "2.7"',
    ),
    (
        'importlib-metadata; python_version<"3.8"',
        "importlib-metadata; python_version<'3.8'",
    ),
    (
        'appdirs>=1.4.4,<2; os_name=="posix" and extra=="testing"',
        "appdirs>=1.4.4,<2; os_name == 'posix' and extra == 'testing'",
    ),
]

EQUIVALENT_DEPENDENCIES = [
    ("scikit-learn==1.0.1", "scikit_learn==1.0.1"),
]

DIFFERENT_DEPENDENCIES = [
    ("package_one", "package_two"),
    ("packaging>20.1", "packaging>=20.1"),
    ("packaging>20.1", "packaging>21.1"),
    ("packaging>20.1", "package>20.1"),
    (
        'requests[security,tests]>=2.8.1,==2.8.*;python_version<"2.7"',
        'requests [security,tests] >= 2.8.1 ; python_version < "2.7"',
    ),
    (
        'importlib-metadata; python_version<"3.8"',
        "importlib-metadata; python_version<'3.7'",
    ),
    (
        'appdirs>=1.4.4,<2; os_name=="posix" and extra=="testing"',
        "appdirs>=1.4.4,<2; os_name == 'posix' and extra == 'docs'",
    ),
]


@pytest.mark.parametrize(
    "name",
    [
        "package",
        "pAcKaGe",
        "Package",
        "foo-bar.quux_bAz",
        "installer",
        "android12",
    ],
)
@pytest.mark.parametrize(
    "extras",
    [
        set(),
        {"a"},
        {"a", "b"},
        {"a", "B", "CDEF123"},
    ],
)
@pytest.mark.parametrize(
    ("url", "specifier"),
    [
        (None, ""),
        ("https://example.com/packagename.zip", ""),
        ("ssh://user:pass%20word@example.com/packagename.zip", ""),
        ("https://example.com/name;v=1.1/?query=foo&bar=baz#blah", ""),
        ("git+ssh://git.example.com/MyProject", ""),
        ("git+ssh://git@github.com:pypa/packaging.git", ""),
        ("git+https://git.example.com/MyProject.git@master", ""),
        ("git+https://git.example.com/MyProject.git@v1.0", ""),
        ("git+https://git.example.com/MyProject.git@refs/pull/123/head", ""),
        ("gopher:/foo/com", ""),
        (None, "==={ws}arbitrarystring"),
        (None, "({ws}==={ws}arbitrarystring{ws})"),
        (None, "=={ws}1.0"),
        (None, "({ws}=={ws}1.0{ws})"),
        (None, "=={ws}1.0-alpha"),
        (None, "<={ws}1!3.0.0.rc2"),
        (None, ">{ws}2.2{ws},{ws}<{ws}3"),
        (None, "(>{ws}2.2{ws},{ws}<{ws}3)"),
    ],
)
@pytest.mark.parametrize(
    "marker",
    [
        None,
        "python_version{ws}>={ws}'3.3'",
        '({ws}python_version{ws}>={ws}"3.4"{ws}){ws}and extra{ws}=={ws}"oursql"',
        (
            "sys_platform{ws}!={ws}'linux' and(os_name{ws}=={ws}'linux' or "
            "python_version{ws}>={ws}'3.3'{ws}){ws}"
        ),
    ],
)
@pytest.mark.parametrize("whitespace", ["", " ", "\t"])
def test_basic_valid_requirement_parsing(
    name: str,
    extras: set[str],
    specifier: str,
    url: str | None,
    marker: str,
    whitespace: str,
) -> None:
    # GIVEN
    parts = [name]
    if extras:
        parts.append("[")
        parts.append("{ws},{ws}".format(ws=whitespace).join(sorted(extras)))
        parts.append("]")
    if specifier:
        parts.append(specifier.format(ws=whitespace))
    if url is not None:
        parts.append("@")
        parts.append(url.format(ws=whitespace))
    if marker is not None:
        if url is not None:
            parts.append(" ;")
        else:
            parts.append(";")
        parts.append(marker.format(ws=whitespace))

    to_parse = whitespace.join(parts)

    # WHEN
    req = Requirement(to_parse)

    # THEN
    assert req.name == name
    assert req.extras == extras
    assert req.url == url
    assert req.specifier == specifier.format(ws="").strip("()")
    assert req.marker == (Marker(marker.format(ws="")) if marker else None)


@pytest.mark.parametrize(
    ("input_req", "norm_req"),
    [
        (
            'mariadb>=1.0.1; extra == "mariadb_connector"',
            'mariadb>=1.0.1; extra == "mariadb-connector"',
        ),
        (
            'mariadb>=1.0.1; python_version >= "3" and extra == "mariadb_connector"',
            'mariadb>=1.0.1; python_version >= "3" and extra == "mariadb-connector"',
        ),
    ],
)
def test_normalized_requirements(input_req: str, norm_req: str) -> None:
    req = Requirement(input_req)
    assert str(req) == norm_req


class TestRequirementParsing:
    @pytest.mark.parametrize(
        "marker",
        [
            "python_implementation == ''",
            "platform_python_implementation == ''",
            "os.name == 'linux'",
            "os_name == 'linux'",
            "'8' in platform.version",
            "'8' not in platform.version",
        ],
    )
    def test_valid_marker(self, marker: str) -> None:
        # GIVEN
        to_parse = f"name; {marker}"

        # WHEN
        Requirement(to_parse)

    @pytest.mark.parametrize(
        "url",
        [
            "file:///absolute/path",
            "file://.",
            "file:.",
            "file:/.",
        ],
    )
    def test_file_url(self, url: str) -> None:
        # GIVEN
        to_parse = f"name @ {url}"

        # WHEN
        req = Requirement(to_parse)

        # THEN
        assert req.url == url

    def test_empty_extras(self) -> None:
        # GIVEN
        to_parse = "name[]"

        # WHEN
        req = Requirement(to_parse)

        # THEN
        assert req.name == "name"
        assert req.extras == set()

    def test_empty_specifier(self) -> None:
        # GIVEN
        to_parse = "name()"

        # WHEN
        req = Requirement(to_parse)

        # THEN
        assert req.name == "name"
        assert req.specifier == ""

    # ----------------------------------------------------------------------------------
    # Everything below this (in this class) should be parsing failure modes
    # ----------------------------------------------------------------------------------
    # Start all method names with with `test_error_`
    # to make it easier to run these tests with `-k error`

    def test_error_when_empty_string(self) -> None:
        # GIVEN
        to_parse = ""

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected package name at the start of dependency specifier\n"
            "    \n"
            "    ^"
        )

    def test_error_no_name(self) -> None:
        # GIVEN
        to_parse = "==0.0"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected package name at the start of dependency specifier\n"
            "    ==0.0\n"
            "    ^"
        )

    def test_error_when_missing_comma_in_extras(self) -> None:
        # GIVEN
        to_parse = "name[bar baz]"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected comma between extra names\n"
            "    name[bar baz]\n"
            "             ^"
        )

    def test_error_when_trailing_comma_in_extras(self) -> None:
        # GIVEN
        to_parse = "name[bar, baz,]"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected extra name after comma\n"
            "    name[bar, baz,]\n"
            "                  ^"
        )

    def test_error_when_parens_not_closed_correctly(self) -> None:
        # GIVEN
        to_parse = "name (>= 1.0"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, "
            "after version specifier\n"
            "    name (>= 1.0\n"
            "         ~~~~~~~^"
        )

    def test_error_when_prefix_match_is_used_incorrectly(self) -> None:
        # GIVEN
        to_parse = "black (>=20.*) ; extra == 'format'"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            ".* suffix can only be used with `==` or `!=` operators\n"
            "    black (>=20.*) ; extra == 'format'\n"
            "           ~~~~~^"
        )

    @pytest.mark.parametrize("operator", [">=", "<=", ">", "<", "~="])
    def test_error_when_local_version_label_is_used_incorrectly(
        self, operator: str
    ) -> None:
        # GIVEN
        to_parse = f"name {operator} 1.0+local.version.label"
        op_tilde = len(operator) * "~"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Local version label can only be used with `==` or `!=` operators\n"
            f"    name {operator} 1.0+local.version.label\n"
            f"         {op_tilde}~~~~^"
        )

    def test_error_when_bracket_not_closed_correctly(self) -> None:
        # GIVEN
        to_parse = "name[bar, baz >= 1.0"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected matching RIGHT_BRACKET for LEFT_BRACKET, "
            "after extras\n"
            "    name[bar, baz >= 1.0\n"
            "        ~~~~~~~~~~^"
        )

    def test_error_when_extras_bracket_left_unclosed(self) -> None:
        # GIVEN
        to_parse = "name[bar, baz"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected matching RIGHT_BRACKET for LEFT_BRACKET, "
            "after extras\n"
            "    name[bar, baz\n"
            "        ~~~~~~~~~^"
        )

    def test_error_no_space_after_url(self) -> None:
        # GIVEN
        to_parse = "name @ https://example.com/; extra == 'example'"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected semicolon (after URL and whitespace) or end\n"
            "    name @ https://example.com/; extra == 'example'\n"
            "           ~~~~~~~~~~~~~~~~~~~~~~^"
        )

    def test_error_marker_bracket_unclosed(self) -> None:
        # GIVEN
        to_parse = "name; (extra == 'example'"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected matching RIGHT_PARENTHESIS for LEFT_PARENTHESIS, "
            "after marker expression\n"
            "    name; (extra == 'example'\n"
            "          ~~~~~~~~~~~~~~~~~~~^"
        )

    def test_error_no_url_after_at(self) -> None:
        # GIVEN
        to_parse = "name @ "

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected URL after @\n"
            "    name @ \n"
            "           ^"
        )

    def test_error_invalid_marker_lvalue(self) -> None:
        # GIVEN
        to_parse = "name; invalid_name"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected a marker variable or quoted string\n"
            "    name; invalid_name\n"
            "          ^"
        )

    def test_error_invalid_marker_rvalue(self) -> None:
        # GIVEN
        to_parse = "name; '3.7' <= invalid_name"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected a marker variable or quoted string\n"
            "    name; '3.7' <= invalid_name\n"
            "                   ^"
        )

    def test_error_invalid_marker_notin_without_whitespace(self) -> None:
        # GIVEN
        to_parse = "name; '3.7' notin python_version"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, "
            "in, not in\n"
            "    name; '3.7' notin python_version\n"
            "                ^"
        )

    def test_error_when_no_word_boundary(self) -> None:
        # GIVEN
        to_parse = "name; '3.6'inpython_version"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, "
            "in, not in\n"
            "    name; '3.6'inpython_version\n"
            "               ^"
        )

    def test_error_invalid_marker_not_without_in(self) -> None:
        # GIVEN
        to_parse = "name; '3.7' not python_version"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected 'in' after 'not'\n"
            "    name; '3.7' not python_version\n"
            "                    ^"
        )

    def test_error_invalid_marker_with_invalid_op(self) -> None:
        # GIVEN
        to_parse = "name; '3.7' ~ python_version"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, "
            "in, not in\n"
            "    name; '3.7' ~ python_version\n"
            "                ^"
        )

    def test_error_on_legacy_version_outside_triple_equals(self) -> None:
        # GIVEN
        to_parse = "name==1.0.org1"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected comma (within version specifier), "
            "semicolon (after version specifier) or end\n"
            "    name==1.0.org1\n"
            "        ~~~~~^"
        )

    def test_error_on_missing_version_after_op(self) -> None:
        # GIVEN
        to_parse = "name=="

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected semicolon (after name with no version specifier) or end\n"
            "    name==\n"
            "        ^"
        )

    def test_error_on_missing_op_after_name(self) -> None:
        # GIVEN
        to_parse = "name 1.0"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected semicolon (after name with no version specifier) or end\n"
            "    name 1.0\n"
            "         ^"
        )

    def test_error_on_random_char_after_specifier(self) -> None:
        # GIVEN
        to_parse = "name >= 1.0 #"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected comma (within version specifier), "
            "semicolon (after version specifier) or end\n"
            "    name >= 1.0 #\n"
            "         ~~~~~~~^"
        )

    def test_error_on_missing_comma_in_specifier(self) -> None:
        # GIVEN
        to_parse = "name >= 1.0 <= 2.0"

        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            "Expected comma (within version specifier), "
            "semicolon (after version specifier) or end\n"
            "    name >= 1.0 <= 2.0\n"
            "         ~~~~~~~^"
        )


class TestRequirementBehaviour:
    def test_types_with_nothing(self) -> None:
        # GIVEN
        to_parse = "foobar"

        # WHEN
        req = Requirement(to_parse)

        # THEN
        assert isinstance(req.name, str)
        assert isinstance(req.extras, set)
        assert req.url is None
        assert isinstance(req.specifier, SpecifierSet)
        assert req.marker is None

    def test_types_with_specifier_and_marker(self) -> None:
        # GIVEN
        to_parse = "foobar[quux]<2,>=3; os_name=='a'"

        # WHEN
        req = Requirement(to_parse)

        # THEN
        assert isinstance(req.name, str)
        assert isinstance(req.extras, set)
        assert req.url is None
        assert isinstance(req.specifier, SpecifierSet)
        assert isinstance(req.marker, Marker)

    def test_types_with_url(self) -> None:
        req = Requirement("foobar @ http://foo.com")
        assert isinstance(req.name, str)
        assert isinstance(req.extras, set)
        assert isinstance(req.url, str)
        assert isinstance(req.specifier, SpecifierSet)
        assert req.marker is None

    @pytest.mark.parametrize(
        "url_or_specifier",
        ["", " @ https://url ", "!=2.0", "==2.*"],
    )
    @pytest.mark.parametrize("extras", ["", "[a]", "[a,b]", "[a1,b1,b2]"])
    @pytest.mark.parametrize(
        "marker",
        ["", '; python_version == "3.11"', '; "3." not in python_version'],
    )
    def test_str_and_repr(
        self, extras: str, url_or_specifier: str, marker: str
    ) -> None:
        # GIVEN
        to_parse = f"name{extras}{url_or_specifier}{marker}"

        # WHEN
        req = Requirement(to_parse)

        # THEN
        assert str(req) == to_parse.strip()
        assert repr(req) == f""

    @pytest.mark.parametrize(("dep1", "dep2"), EQUAL_DEPENDENCIES)
    def test_equal_reqs_equal_hashes(self, dep1: str, dep2: str) -> None:
        """Requirement objects created from equal strings should be equal."""
        # GIVEN / WHEN
        req1, req2 = Requirement(dep1), Requirement(dep2)

        assert req1 == req2
        assert hash(req1) == hash(req2)

    @pytest.mark.parametrize(("dep1", "dep2"), EQUIVALENT_DEPENDENCIES)
    def test_equivalent_reqs_equal_hashes_unequal_strings(
        self, dep1: str, dep2: str
    ) -> None:
        """Requirement objects created from equivalent strings should be equal,
        even though their string representation will not."""
        # GIVEN / WHEN
        req1, req2 = Requirement(dep1), Requirement(dep2)

        assert req1 == req2
        assert hash(req1) == hash(req2)
        assert str(req1) != str(req2)

    @pytest.mark.parametrize(("dep1", "dep2"), DIFFERENT_DEPENDENCIES)
    def test_different_reqs_different_hashes(self, dep1: str, dep2: str) -> None:
        """Requirement objects created from non-equivalent strings should differ."""
        # GIVEN / WHEN
        req1, req2 = Requirement(dep1), Requirement(dep2)

        # THEN
        assert req1 != req2
        assert hash(req1) != hash(req2)

    def test_compare_with_string(self) -> None:
        assert Requirement("packaging>=21.3") != "packaging>=21.3"
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_specifiers.py0000644000000000000000000022711615133751156015242 0ustar00# 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 itertools
import operator
import re
import typing

import pytest

from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet
from packaging.version import Version, parse

from .test_version import VERSIONS

if typing.TYPE_CHECKING:
    from collections.abc import Callable

LEGACY_SPECIFIERS = [
    "==2.1.0.3",
    "!=2.2.0.5",
    "<=5",
    ">=7.9a1",
    "<1.0.dev1",
    ">2.0.post1",
]

SPECIFIERS = [
    "~=2.0",
    "==2.1.*",
    "==2.1.0.3",
    "!=2.2.*",
    "!=2.2.0.5",
    "<=5",
    ">=7.9a1",
    "<1.0.dev1",
    ">2.0.post1",
]


class TestSpecifier:
    @pytest.mark.parametrize("specifier", SPECIFIERS)
    def test_specifiers_valid(self, specifier: str) -> None:
        Specifier(specifier)

    def test_match_args(self) -> None:
        assert Specifier.__match_args__ == ("_str",)
        assert Specifier(">=1.0")._str == ">=1.0"

    @pytest.mark.parametrize(
        "specifier",
        [
            # Operator-less specifier
            "2.0",
            # Invalid operator
            "=>2.0",
            # Version-less specifier
            "==",
            # Local segment on operators which don't support them
            "~=1.0+5",
            ">=1.0+deadbeef",
            "<=1.0+abc123",
            ">1.0+watwat",
            "<1.0+1.0",
            # Prefix matching on operators which don't support them
            "~=1.0.*",
            ">=1.0.*",
            "<=1.0.*",
            ">1.0.*",
            "<1.0.*",
            # Combination of local and prefix matching on operators which do
            # support one or the other
            "==1.0.*+5",
            "!=1.0.*+deadbeef",
            # Prefix matching cannot be used with a pre-release, post-release,
            # dev or local version
            "==2.0a1.*",
            "!=2.0a1.*",
            "==2.0.post1.*",
            "!=2.0.post1.*",
            "==2.0.dev1.*",
            "!=2.0.dev1.*",
            "==1.0+5.*",
            "!=1.0+deadbeef.*",
            # Prefix matching must appear at the end
            "==1.0.*.5",
            # Compatible operator requires 2 digits in the release operator
            "~=1",
            # Cannot use a prefix matching after a .devN version
            "==1.0.dev1.*",
            "!=1.0.dev1.*",
        ],
    )
    def test_specifiers_invalid(self, specifier: str) -> None:
        with pytest.raises(InvalidSpecifier):
            Specifier(specifier)

    @pytest.mark.parametrize(
        "version",
        [
            # Various development release incarnations
            "1.0dev",
            "1.0.dev",
            "1.0dev1",
            "1.0-dev",
            "1.0-dev1",
            "1.0DEV",
            "1.0.DEV",
            "1.0DEV1",
            "1.0.DEV1",
            "1.0-DEV",
            "1.0-DEV1",
            # Various alpha incarnations
            "1.0a",
            "1.0.a",
            "1.0.a1",
            "1.0-a",
            "1.0-a1",
            "1.0alpha",
            "1.0.alpha",
            "1.0.alpha1",
            "1.0-alpha",
            "1.0-alpha1",
            "1.0A",
            "1.0.A",
            "1.0.A1",
            "1.0-A",
            "1.0-A1",
            "1.0ALPHA",
            "1.0.ALPHA",
            "1.0.ALPHA1",
            "1.0-ALPHA",
            "1.0-ALPHA1",
            # Various beta incarnations
            "1.0b",
            "1.0.b",
            "1.0.b1",
            "1.0-b",
            "1.0-b1",
            "1.0beta",
            "1.0.beta",
            "1.0.beta1",
            "1.0-beta",
            "1.0-beta1",
            "1.0B",
            "1.0.B",
            "1.0.B1",
            "1.0-B",
            "1.0-B1",
            "1.0BETA",
            "1.0.BETA",
            "1.0.BETA1",
            "1.0-BETA",
            "1.0-BETA1",
            # Various release candidate incarnations
            "1.0c",
            "1.0.c",
            "1.0.c1",
            "1.0-c",
            "1.0-c1",
            "1.0rc",
            "1.0.rc",
            "1.0.rc1",
            "1.0-rc",
            "1.0-rc1",
            "1.0C",
            "1.0.C",
            "1.0.C1",
            "1.0-C",
            "1.0-C1",
            "1.0RC",
            "1.0.RC",
            "1.0.RC1",
            "1.0-RC",
            "1.0-RC1",
            # Various post release incarnations
            "1.0post",
            "1.0.post",
            "1.0post1",
            "1.0-post",
            "1.0-post1",
            "1.0POST",
            "1.0.POST",
            "1.0POST1",
            "1.0.POST1",
            "1.0-POST",
            "1.0-POST1",
            "1.0-5",
            # Local version case insensitivity
            "1.0+AbC",
            # Integer Normalization
            "1.01",
            "1.0a05",
            "1.0b07",
            "1.0c056",
            "1.0rc09",
            "1.0.post000",
            "1.1.dev09000",
            "00!1.2",
            "0100!0.0",
            # Various other normalizations
            "v1.0",
            "  \r \f \v v1.0\t\n",
        ],
    )
    def test_specifiers_normalized(self, version: str) -> None:
        if "+" not in version:
            ops = ["~=", "==", "!=", "<=", ">=", "<", ">"]
        else:
            ops = ["==", "!="]

        for op in ops:
            Specifier(op + version)

    @pytest.mark.parametrize(
        ("specifier", "expected"),
        [
            # Single item specifiers should just be reflexive
            ("!=2.0", "!=2.0"),
            ("<2.0", "<2.0"),
            ("<=2.0", "<=2.0"),
            ("==2.0", "==2.0"),
            (">2.0", ">2.0"),
            (">=2.0", ">=2.0"),
            ("~=2.0", "~=2.0"),
            # Spaces should be removed
            ("< 2", "<2"),
        ],
    )
    def test_specifiers_str_and_repr(self, specifier: str, expected: str) -> None:
        spec = Specifier(specifier)

        assert str(spec) == expected
        assert repr(spec) == f""

    @pytest.mark.parametrize("specifier", SPECIFIERS)
    def test_specifiers_hash(self, specifier: str) -> None:
        assert hash(Specifier(specifier)) == hash(Specifier(specifier))

    @pytest.mark.parametrize(
        ("left", "right", "op"),
        itertools.chain.from_iterable(
            # Verify that the equal (==) operator works correctly
            [[(x, x, operator.eq) for x in SPECIFIERS]]
            +
            # Verify that the not equal (!=) operator works correctly
            [
                [(x, y, operator.ne) for j, y in enumerate(SPECIFIERS) if i != j]
                for i, x in enumerate(SPECIFIERS)
            ]
        ),
    )
    def test_comparison_true(
        self,
        left: str,
        right: str,
        op: typing.Callable[[Specifier | str, Specifier | str], bool],
    ) -> None:
        assert op(Specifier(left), Specifier(right))
        assert op(left, Specifier(right))
        assert op(Specifier(left), right)

    @pytest.mark.parametrize(("left", "right"), [("==2.8.0", "==2.8")])
    def test_comparison_canonicalizes(self, left: str, right: str) -> None:
        assert Specifier(left) == Specifier(right)
        assert left == Specifier(right)
        assert Specifier(left) == right

    @pytest.mark.parametrize(
        ("left", "right", "op"),
        itertools.chain.from_iterable(
            # Verify that the equal (==) operator works correctly
            [[(x, x, operator.ne) for x in SPECIFIERS]]
            +
            # Verify that the not equal (!=) operator works correctly
            [
                [(x, y, operator.eq) for j, y in enumerate(SPECIFIERS) if i != j]
                for i, x in enumerate(SPECIFIERS)
            ]
        ),
    )
    def test_comparison_false(
        self,
        left: str,
        right: str,
        op: typing.Callable[[Specifier | str, Specifier | str], bool],
    ) -> None:
        assert not op(Specifier(left), Specifier(right))
        assert not op(left, Specifier(right))
        assert not op(Specifier(left), right)

    def test_comparison_non_specifier(self) -> None:
        assert Specifier("==1.0") != 12
        assert not Specifier("==1.0") == 12
        assert Specifier("==1.0") != "12"
        assert not Specifier("==1.0") == "12"

    @pytest.mark.parametrize(
        ("version", "spec_str", "expected"),
        [
            (v, s, True)
            for v, s in [
                # Test the equality operation
                ("2.0", "==2"),
                ("2.0", "==2.0"),
                ("2.0", "==2.0.0"),
                ("2.0+deadbeef", "==2"),
                ("2.0+deadbeef", "==2.0"),
                ("2.0+deadbeef", "==2.0.0"),
                ("2.0+deadbeef", "==2+deadbeef"),
                ("2.0+deadbeef", "==2.0+deadbeef"),
                ("2.0+deadbeef", "==2.0.0+deadbeef"),
                ("2.0+deadbeef.0", "==2.0.0+deadbeef.00"),
                # Test the equality operation with a prefix
                ("2.dev1", "==2.*"),
                ("2a1", "==2.*"),
                ("2a1.post1", "==2.*"),
                ("2b1", "==2.*"),
                ("2b1.dev1", "==2.*"),
                ("2c1", "==2.*"),
                ("2c1.post1.dev1", "==2.*"),
                ("2c1.post1.dev1", "==2.0.*"),
                ("2rc1", "==2.*"),
                ("2rc1", "==2.0.*"),
                ("2", "==2.*"),
                ("2", "==2.0.*"),
                ("2", "==0!2.*"),
                ("0!2", "==2.*"),
                ("2.0", "==2.*"),
                ("2.0.0", "==2.*"),
                ("2.1+local.version", "==2.1.*"),
                # Test the in-equality operation
                ("2.1", "!=2"),
                ("2.1", "!=2.0"),
                ("2.0.1", "!=2"),
                ("2.0.1", "!=2.0"),
                ("2.0.1", "!=2.0.0"),
                ("2.0", "!=2.0+deadbeef"),
                # Test the in-equality operation with a prefix
                ("2.0", "!=3.*"),
                ("2.1", "!=2.0.*"),
                # Test the greater than equal operation
                ("2.0", ">=2"),
                ("2.0", ">=2.0"),
                ("2.0", ">=2.0.0"),
                ("2.0.post1", ">=2"),
                ("2.0.post1.dev1", ">=2"),
                ("3", ">=2"),
                ("3.0.0a8", ">=3.0.0a7"),
                # Test the less than equal operation
                ("2.0", "<=2"),
                ("2.0", "<=2.0"),
                ("2.0", "<=2.0.0"),
                ("2.0.dev1", "<=2"),
                ("2.0a1", "<=2"),
                ("2.0a1.dev1", "<=2"),
                ("2.0b1", "<=2"),
                ("2.0b1.post1", "<=2"),
                ("2.0c1", "<=2"),
                ("2.0c1.post1.dev1", "<=2"),
                ("2.0rc1", "<=2"),
                ("1", "<=2"),
                ("3.0.0a7", "<=3.0.0a8"),
                # Test the greater than operation
                ("3", ">2"),
                ("2.1", ">2.0"),
                ("2.0.1", ">2"),
                ("2.1.post1", ">2"),
                ("2.1+local.version", ">2"),
                ("3.0.0a8", ">3.0.0a7"),
                # Test the less than operation
                ("1", "<2"),
                ("2.0", "<2.1"),
                ("2.0.dev0", "<2.1"),
                ("3.0.0a7", "<3.0.0a8"),
                # Test the compatibility operation
                ("1", "~=1.0"),
                ("1.0.1", "~=1.0"),
                ("1.1", "~=1.0"),
                ("1.9999999", "~=1.0"),
                ("1.1", "~=1.0a1"),
                ("2022.01.01", "~=2022.01.01"),
                # Test that epochs are handled sanely
                ("2!1.0", "~=2!1.0"),
                ("2!1.0", "==2!1.*"),
                ("2!1.0", "==2!1.0"),
                ("2!1.0", "!=1.0"),
                ("2!1.0.0", "==2!1.0.0.0.*"),
                ("2!1.0.0", "==2!1.0.*"),
                ("2!1.0.0", "==2!1.*"),
                ("1.0", "!=2!1.0"),
                ("1.0", "<=2!0.1"),
                ("2!1.0", ">=2.0"),
                ("1.0", "<2!0.1"),
                ("2!1.0", ">2.0"),
                # Test some normalization rules
                ("2.0.5", ">2.0dev"),
            ]
        ]
        + [
            (v, s, False)
            for v, s in [
                # Test the equality operation
                ("2.1", "==2"),
                ("2.1", "==2.0"),
                ("2.1", "==2.0.0"),
                ("2.0", "==2.0+deadbeef"),
                # Test the equality operation with a prefix
                ("2.0", "==3.*"),
                ("2.1", "==2.0.*"),
                # Test the in-equality operation
                ("2.0", "!=2"),
                ("2.0", "!=2.0"),
                ("2.0", "!=2.0.0"),
                ("2.0+deadbeef", "!=2"),
                ("2.0+deadbeef", "!=2.0"),
                ("2.0+deadbeef", "!=2.0.0"),
                ("2.0+deadbeef", "!=2+deadbeef"),
                ("2.0+deadbeef", "!=2.0+deadbeef"),
                ("2.0+deadbeef", "!=2.0.0+deadbeef"),
                ("2.0+deadbeef.0", "!=2.0.0+deadbeef.00"),
                # Test the in-equality operation with a prefix
                ("2.dev1", "!=2.*"),
                ("2a1", "!=2.*"),
                ("2a1.post1", "!=2.*"),
                ("2b1", "!=2.*"),
                ("2b1.dev1", "!=2.*"),
                ("2c1", "!=2.*"),
                ("2c1.post1.dev1", "!=2.*"),
                ("2c1.post1.dev1", "!=2.0.*"),
                ("2rc1", "!=2.*"),
                ("2rc1", "!=2.0.*"),
                ("2", "!=2.*"),
                ("2", "!=2.0.*"),
                ("2.0", "!=2.*"),
                ("2.0.0", "!=2.*"),
                # Test the greater than equal operation
                ("2.0.dev1", ">=2"),
                ("2.0a1", ">=2"),
                ("2.0a1.dev1", ">=2"),
                ("2.0b1", ">=2"),
                ("2.0b1.post1", ">=2"),
                ("2.0c1", ">=2"),
                ("2.0c1.post1.dev1", ">=2"),
                ("2.0rc1", ">=2"),
                ("1", ">=2"),
                # Test the less than equal operation
                ("2.0.post1", "<=2"),
                ("2.0.post1.dev1", "<=2"),
                ("3", "<=2"),
                # Test the greater than operation
                ("1", ">2"),
                ("2.0.dev1", ">2"),
                ("2.0a1", ">2"),
                ("2.0a1.post1", ">2"),
                ("2.0b1", ">2"),
                ("2.0b1.dev1", ">2"),
                ("2.0c1", ">2"),
                ("2.0c1.post1.dev1", ">2"),
                ("2.0rc1", ">2"),
                ("2.0", ">2"),
                ("2.0.post1", ">2"),
                ("2.0.post1.dev1", ">2"),
                ("2.0+local.version", ">2"),
                ("1.0+local", ">1.0.dev1"),
                # Test the less than operation
                ("2.0.dev1", "<2"),
                ("2.0a1", "<2"),
                ("2.0a1.post1", "<2"),
                ("2.0b1", "<2"),
                ("2.0b2.dev1", "<2"),
                ("2.0c1", "<2"),
                ("2.0c1.post1.dev1", "<2"),
                ("2.0rc1", "<2"),
                ("2.0", "<2"),
                ("2.post1", "<2"),
                ("2.post1.dev1", "<2"),
                ("3", "<2"),
                # Test the compatibility operation
                ("2.0", "~=1.0"),
                ("1.1.0", "~=1.0.0"),
                ("1.1.post1", "~=1.0.0"),
                # Test that epochs are handled sanely
                ("1.0", "~=2!1.0"),
                ("2!1.0", "~=1.0"),
                ("2!1.0", "==1.0"),
                ("1.0", "==2!1.0"),
                ("2!1.0", "==1.0.0.*"),
                ("1.0", "==2!1.0.0.*"),
                ("2!1.0", "==1.*"),
                ("1.0", "==2!1.*"),
                ("2!1.0", "!=2!1.0"),
            ]
        ],
    )
    def test_specifiers(self, version: str, spec_str: str, expected: bool) -> None:
        spec = Specifier(spec_str, prereleases=True)

        if expected:
            # Test that the plain string form works
            assert version in spec
            assert spec.contains(version)

            # Test that the version instance form works
            assert Version(version) in spec
            assert spec.contains(Version(version))
        else:
            # Test that the plain string form works
            assert version not in spec
            assert not spec.contains(version)

            # Test that the version instance form works
            assert Version(version) not in spec
            assert not spec.contains(Version(version))

    @pytest.mark.parametrize(
        ("spec_str", "version", "expected"),
        [
            ("==1.0", "not a valid version", False),
            ("==1.*", "not a valid version", False),
            (">=1.0", "not a valid version", False),
            (">1.0", "not a valid version", False),
            ("<=1.0", "not a valid version", False),
            ("<1.0", "not a valid version", False),
            ("~=1.0", "not a valid version", False),
            ("!=1.0", "not a valid version", False),
            ("!=1.*", "not a valid version", False),
            # Test with arbitrary equality (===)
            ("===invalid", "invalid", True),
            ("===foobar", "invalid", False),
        ],
    )
    def test_invalid_version(self, spec_str: str, version: str, expected: bool) -> None:
        spec = Specifier(spec_str, prereleases=True)
        assert spec.contains(version) == expected

    @pytest.mark.parametrize(
        (
            "specifier",
            "initial_prereleases",
            "set_prereleases",
            "version",
            "initial_contains",
            "final_contains",
        ),
        [
            (">1.0", None, True, "1.0.dev1", False, False),
            # Setting prereleases to True explicitly includes prerelease versions
            (">1.0", None, True, "2.0.dev1", True, True),
            (">1.0", False, True, "2.0.dev1", False, True),
            # Setting prereleases to False explicitly excludes prerelease versions
            (">1.0", None, False, "2.0.dev1", True, False),
            # Setting prereleases to None falls back to default behavior
            (">1.0", True, None, "2.0.dev1", True, True),
            (">1.0", False, None, "2.0.dev1", False, True),
            # Different specifiers with prerelease versions
            (">=2.0.dev1", None, True, "2.0a1", True, True),
            (">=2.0.dev1", None, False, "2.0a1", True, False),
            # Alpha/beta/rc/dev variations
            (">1.0", None, True, "2.0a1", True, True),
            (">1.0", None, True, "2.0b1", True, True),
            (">1.0", None, True, "2.0rc1", True, True),
            # Edge cases
            ("==2.0.*", None, True, "2.0.dev1", True, True),
            ("==2.0.*", None, False, "2.0.dev1", True, False),
            # Specifiers that already include prereleases implicitly
            ("<1.0.dev1", None, False, "0.9.dev1", True, False),
            (">1.0.dev1", None, None, "1.1.dev1", True, True),
            # Multiple changes to the prereleases setting
            (">1.0", True, False, "2.0.dev1", True, False),
        ],
    )
    def test_specifier_prereleases_set(
        self,
        specifier: str,
        initial_prereleases: bool | None,
        set_prereleases: bool | None,
        version: str,
        initial_contains: bool,
        final_contains: bool,
    ) -> None:
        """Test setting prereleases property."""
        spec = Specifier(specifier, prereleases=initial_prereleases)

        assert (version in spec) == initial_contains
        assert spec.contains(version) == initial_contains

        spec.prereleases = set_prereleases

        assert (version in spec) == final_contains
        assert spec.contains(version) == final_contains

    @pytest.mark.parametrize(
        ("version", "spec_str", "expected"),
        [
            ("1.0.0", "===1.0", False),
            ("1.0.dev0", "===1.0", False),
            # Test identity comparison by itself
            ("1.0", "===1.0", True),
            ("1.0.dev0", "===1.0.dev0", True),
            # Test that local versions don't match
            ("1.0+downstream1", "===1.0", False),
            ("1.0", "===1.0+downstream1", False),
            # Test with arbitrary (non-version) strings
            ("foobar", "===foobar", True),
            ("foobar", "===baz", False),
            # Test case insensitivity for pre-release versions
            ("1.0a1", "===1.0a1", True),
            ("1.0A1", "===1.0A1", True),
            ("1.0a1", "===1.0A1", True),
            ("1.0A1", "===1.0a1", True),
            # Test case insensitivity for beta versions
            ("1.0b1", "===1.0b1", True),
            ("1.0B1", "===1.0B1", True),
            ("1.0b1", "===1.0B1", True),
            ("1.0B1", "===1.0b1", True),
            # Test case insensitivity for release candidate versions
            ("1.0rc1", "===1.0rc1", True),
            ("1.0RC1", "===1.0RC1", True),
            ("1.0rc1", "===1.0RC1", True),
            ("1.0RC1", "===1.0rc1", True),
            # Test case insensitivity for post-release versions
            ("1.0.post1", "===1.0.post1", True),
            ("1.0.POST1", "===1.0.POST1", True),
            ("1.0.post1", "===1.0.POST1", True),
            ("1.0.POST1", "===1.0.post1", True),
            # Test case insensitivity for dev versions
            ("1.0.dev1", "===1.0.dev1", True),
            ("1.0.DEV1", "===1.0.DEV1", True),
            ("1.0.dev1", "===1.0.DEV1", True),
            ("1.0.DEV1", "===1.0.dev1", True),
            # Test case insensitivity with local versions
            ("1.0+local", "===1.0+local", True),
            ("1.0+LOCAL", "===1.0+LOCAL", True),
            ("1.0+local", "===1.0+LOCAL", True),
            ("1.0+LOCAL", "===1.0+local", True),
            ("1.0+abc.def", "===1.0+abc.def", True),
            ("1.0+ABC.DEF", "===1.0+ABC.DEF", True),
            ("1.0+abc.def", "===1.0+ABC.DEF", True),
            ("1.0+ABC.DEF", "===1.0+abc.def", True),
            # Test case insensitivity with mixed case letters in local
            ("1.0+AbC", "===1.0+AbC", True),
            ("1.0+AbC", "===1.0+abc", True),
            ("1.0+AbC", "===1.0+ABC", True),
            # Test complex cases with multiple segments
            ("1.0a1.post2.dev3", "===1.0a1.post2.dev3", True),
            ("1.0A1.POST2.DEV3", "===1.0A1.POST2.DEV3", True),
            ("1.0a1.post2.dev3", "===1.0A1.POST2.DEV3", True),
            ("1.0A1.POST2.DEV3", "===1.0a1.post2.dev3", True),
            # Test case insensitivity of non-PEP 440 versions
            ("lolwat", "===LOLWAT", True),
            ("lolwat", "===LoLWaT", True),
            ("LOLWAT", "===lolwat", True),
            ("LoLWaT", "===lOlwAt", True),
        ],
    )
    def test_arbitrary_equality(
        self, version: str, spec_str: str, expected: bool
    ) -> None:
        spec = Specifier(spec_str)
        assert spec.contains(version) == expected

    @pytest.mark.parametrize(
        ("specifier", "expected"),
        [
            ("==1.0", False),
            (">=1.0", False),
            ("<=1.0", False),
            ("~=1.0", False),
            ("<1.0", False),
            (">1.0", False),
            ("<1.0.dev1", True),
            (">1.0.dev1", True),
            ("!=1.0.dev1", False),
            ("==1.0.*", False),
            ("==1.0.dev1", True),
            (">=1.0.dev1", True),
            ("<=1.0.dev1", True),
            ("~=1.0.dev1", True),
        ],
    )
    def test_specifier_prereleases_detection(
        self, specifier: str, expected: bool
    ) -> None:
        assert Specifier(specifier).prereleases == expected

    @pytest.mark.parametrize(
        ("specifier", "version", "spec_pre", "contains_pre", "expected"),
        [
            (">=1.0", "2.0.dev1", None, None, True),
            (">=2.0.dev1", "2.0a1", None, None, True),
            ("==2.0.*", "2.0a1.dev1", None, None, True),
            ("<=2.0", "1.0.dev1", None, None, True),
            ("<=2.0.dev1", "1.0a1", None, None, True),
            ("<2.0", "2.0a1", None, None, False),
            ("<2.0a2", "2.0a1", None, None, True),
            ("<=2.0", "1.0.dev1", False, None, False),
            ("<=2.0a1", "1.0.dev1", False, None, False),
            ("<=2.0", "1.0.dev1", None, False, False),
            ("<=2.0a1", "1.0.dev1", None, False, False),
            ("<=2.0", "1.0.dev1", True, False, False),
            ("<=2.0a1", "1.0.dev1", True, False, False),
            ("<=2.0", "1.0.dev1", False, True, True),
            ("<=2.0a1", "1.0.dev1", False, True, True),
        ],
    )
    def test_specifiers_prereleases(
        self,
        specifier: str,
        version: str,
        spec_pre: bool | None,
        contains_pre: bool | None,
        expected: bool,
    ) -> None:
        spec = Specifier(specifier, prereleases=spec_pre)

        assert spec.contains(version, prereleases=contains_pre) == expected

    @pytest.mark.parametrize(
        ("specifier", "specifier_prereleases", "prereleases", "input", "expected"),
        [
            # General test of the filter method
            (">=1.0.dev1", None, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            (">=1.2.3", None, None, ["1.2", "1.5a1"], ["1.5a1"]),
            (">=1.2.3", None, None, ["1.3", "1.5a1"], ["1.3"]),
            (">=1.0", None, None, ["2.0a1"], ["2.0a1"]),
            ("!=2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0"]),
            ("==2.0a1", None, None, ["2.0a1"], ["2.0a1"]),
            (">2.0a1", None, None, ["2.0a1", "3.0a2", "3.0"], ["3.0a2", "3.0"]),
            ("<2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0a2", "1.0"]),
            ("~=2.0a1", None, None, ["1.0", "2.0a1", "3.0a2", "3.0"], ["2.0a1"]),
            # Test overriding with the prereleases parameter on filter
            (">=1.0.dev1", None, False, ["1.0", "2.0a1"], ["1.0"]),
            # Test overriding with the overall specifier
            (">=1.0.dev1", True, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            (">=1.0.dev1", False, None, ["1.0", "2.0a1"], ["1.0"]),
            # Test when both specifier and filter have prerelease value
            (">=1.0", True, False, ["1.0", "2.0a1"], ["1.0"]),
            (">=1.0", False, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            (">=1.0", True, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            (">=1.0", False, False, ["1.0", "2.0a1"], ["1.0"]),
            # Test that invalid versions are discarded
            (">=1.0", None, None, ["not a valid version"], []),
            (">=1.0", None, None, ["1.0", "not a valid version"], ["1.0"]),
            # Test arbitrary equality (===)
            ("===foobar", None, None, ["foobar", "foo", "bar"], ["foobar"]),
            ("===foobar", None, None, ["foo", "bar"], []),
            # Test that === does not match with zero padding
            ("===1.0", None, None, ["1.0", "1.0.0", "2.0"], ["1.0"]),
            # Test that === does not match with local versions
            ("===1.0", None, None, ["1.0", "1.0+downstream1"], ["1.0"]),
            # Test === with mix of valid versions and arbitrary strings
            (
                "===foobar",
                None,
                None,
                ["foobar", "1.0", "2.0a1", "invalid"],
                ["foobar"],
            ),
            ("===1.0", None, None, ["1.0", "foobar", "invalid", "1.0.0"], ["1.0"]),
            # Test != with invalid versions (should not pass as versions are not valid)
            ("!=1.0", None, None, ["invalid", "foobar"], []),
            ("!=1.0", None, None, ["1.0", "invalid", "2.0"], ["2.0"]),
            ("!=2.0.*", None, None, ["invalid", "foobar", "2.0"], []),
            ("!=2.0.*", None, None, ["1.0", "invalid", "2.0.0"], ["1.0"]),
            # Test that !== ignores prereleases parameter for non-PEP 440 versions
            ("!=1.0", None, True, ["invalid", "foobar"], []),
            ("!=1.0", None, False, ["invalid", "foobar"], []),
            ("!=1.0", True, None, ["invalid", "foobar"], []),
            ("!=1.0", False, None, ["invalid", "foobar"], []),
            ("!=1.0", True, True, ["invalid", "foobar"], []),
            ("!=1.0", False, False, ["invalid", "foobar"], []),
            # Test that === ignores prereleases parameter for non-PEP 440 versions
            ("===foobar", None, True, ["foobar", "foo"], ["foobar"]),
            ("===foobar", None, False, ["foobar", "foo"], ["foobar"]),
            ("===foobar", True, None, ["foobar", "foo"], ["foobar"]),
            ("===foobar", False, None, ["foobar", "foo"], ["foobar"]),
            ("===foobar", True, True, ["foobar", "foo"], ["foobar"]),
            ("===foobar", False, False, ["foobar", "foo"], ["foobar"]),
        ],
    )
    def test_specifier_filter(
        self,
        specifier: str,
        specifier_prereleases: bool | None,
        prereleases: bool | None,
        input: list[str],
        expected: list[str],
    ) -> None:
        if specifier_prereleases is None:
            spec = Specifier(specifier)
        else:
            spec = Specifier(specifier, prereleases=specifier_prereleases)

        kwargs = {"prereleases": prereleases} if prereleases is not None else {}

        assert list(spec.filter(input, **kwargs)) == expected

    @pytest.mark.parametrize(
        ("spec", "op"),
        [
            ("~=2.0", "~="),
            ("==2.1.*", "=="),
            ("==2.1.0.3", "=="),
            ("!=2.2.*", "!="),
            ("!=2.2.0.5", "!="),
            ("<=5", "<="),
            (">=7.9a1", ">="),
            ("<1.0.dev1", "<"),
            (">2.0.post1", ">"),
            # === is an escape hatch in PEP 440
            ("===lolwat", "==="),
        ],
    )
    def test_specifier_operator_property(self, spec: str, op: str) -> None:
        assert Specifier(spec).operator == op

    @pytest.mark.parametrize(
        ("spec", "version"),
        [
            ("~=2.0", "2.0"),
            ("==2.1.*", "2.1.*"),
            ("==2.1.0.3", "2.1.0.3"),
            ("!=2.2.*", "2.2.*"),
            ("!=2.2.0.5", "2.2.0.5"),
            ("<=5", "5"),
            (">=7.9a1", "7.9a1"),
            ("<1.0.dev1", "1.0.dev1"),
            (">2.0.post1", "2.0.post1"),
            # === is an escape hatch in PEP 440
            ("===lolwat", "lolwat"),
        ],
    )
    def test_specifier_version_property(self, spec: str, version: str) -> None:
        assert Specifier(spec).version == version

    @pytest.mark.parametrize(
        ("spec_str", "expected_length"),
        [("", 0), ("==2.0", 1), (">=2.0", 1), (">=2.0,<3", 2), (">=2.0,<3,==2.4", 3)],
    )
    def test_length(self, spec_str: str, expected_length: int) -> None:
        spec = SpecifierSet(spec_str)
        assert len(spec) == expected_length

    @pytest.mark.parametrize(
        ("spec_str", "expected_items"),
        [
            ("", []),
            ("==2.0", ["==2.0"]),
            (">=2.0", [">=2.0"]),
            (">=2.0,<3", [">=2.0", "<3"]),
            (">=2.0,<3,==2.4", [">=2.0", "<3", "==2.4"]),
        ],
    )
    def test_iteration(self, spec_str: str, expected_items: list[str]) -> None:
        spec = SpecifierSet(spec_str)
        items = {str(item) for item in spec}
        assert items == set(expected_items)

    def test_specifier_equal_for_compatible_operator(self) -> None:
        assert Specifier("~=1.18.0") != Specifier("~=1.18")

    def test_specifier_hash_for_compatible_operator(self) -> None:
        assert hash(Specifier("~=1.18.0")) != hash(Specifier("~=1.18"))


class TestSpecifierInternal:
    """Tests for internal Specifier._spec_version cache behavior.

    Specifier._spec_version is a one-element cache that stores the parsed Version
    corresponding to Specifier.version after the first time it is needed for
    comparison, these tests validate that the cache is set and never changed.
    """

    @pytest.mark.parametrize(
        ("specifier", "test_versions"),
        [
            (">=1.0", ["0.9", "1.0", "1.1", "2.0"]),
            ("<=1.0", ["0.9", "1.0", "1.1", "2.0"]),
            (">1.0", ["0.9", "1.0", "1.1", "2.0"]),
            ("<1.0", ["0.9", "1.0", "1.1", "2.0"]),
            ("==1.0", ["0.9", "1.0", "1.1", "2.0"]),
            ("!=1.0", ["0.9", "1.0", "1.1", "2.0"]),
            ("~=1.0", ["0.9", "1.0", "1.1", "2.0"]),
            (">=1.0a1", ["0.9", "1.0a1", "1.0", "1.1"]),
            (">=1.0.post1", ["0.9", "1.0", "1.0.post1", "1.1"]),
            (">=1.0.dev1", ["0.9", "1.0.dev1", "1.0", "1.1"]),
            ("==1.0+local", ["1.0", "1.0+local", "1.0+other", "1.1"]),
            (">=1!1.0", ["0!2.0", "1!0.9", "1!1.0", "1!1.1"]),
        ],
    )
    def test_spec_version_cache_consistency(
        self, specifier: str, test_versions: list[str]
    ) -> None:
        """Cache is set on first contains and remains unchanged."""
        spec = Specifier(specifier, prereleases=True)
        assert spec._spec_version is None

        _ = test_versions[0] in spec
        assert spec._spec_version == (spec.version, Version(spec.version))
        initial_cache = spec._spec_version

        for v in test_versions[1:]:
            _ = v in spec
            assert spec._spec_version is initial_cache

        _ = hash(spec)
        assert spec._spec_version is initial_cache

        _ = spec.prereleases
        assert spec._spec_version is initial_cache

        _ = spec == Specifier(specifier)
        assert spec._spec_version is initial_cache

    @pytest.mark.parametrize(
        ("specifier", "test_versions"),
        [
            (
                "==1.0.*",
                ["0.9", "1.0", "1.0.1", "1.0a1", "1.0.dev1", "1.0.post1", "1.0+local"],
            ),
            (
                "!=1.0.*",
                ["0.9", "1.0", "1.0.1", "1.0a1", "1.0.dev1", "1.0.post1", "1.0+local"],
            ),
        ],
    )
    def test_spec_version_cache_with_wildcards(
        self, specifier: str, test_versions: list[str]
    ) -> None:
        """Wildcard specifiers use prefix matching, cache stays None."""
        spec = Specifier(specifier, prereleases=True)

        for v in test_versions:
            _ = v in spec
        _ = spec.prereleases
        _ = hash(spec)

        assert spec._spec_version is None

    @pytest.mark.parametrize(
        "specifier",
        [
            "===1.0",
            "===1.0.0+local",
            "===1.0.dev1",
        ],
    )
    def test_spec_version_cache_with_arbitrary_equality(self, specifier: str) -> None:
        spec = Specifier(specifier)

        _ = "1.0" in spec
        _ = spec.prereleases
        _ = hash(spec)

        assert spec._spec_version == (spec.version, Version(spec.version))

    @pytest.mark.parametrize(
        ("specifier", "versions"),
        [
            (
                "~=1.4.2",
                [
                    # Matching versions
                    "1.4.2",
                    "1.4.3.dev1",
                    "1.4.3a1",
                    "1.4.3",
                    "1.4.3.post1",
                    "1.4.3+local",
                    # Not matching versions
                    "1.4.1",
                    "1.4.1.post1",
                    "1.5.0.dev0",
                    "1.5.0a1",
                    "1.5.0",
                    "2.0",
                    "2.0+local",
                ],
            ),
        ],
    )
    def test_spec_version_cache_compatible_operator(
        self,
        specifier: str,
        versions: list[str],
    ) -> None:
        """~= caches the original spec version, not the prefix used for ==."""
        spec = Specifier(specifier, prereleases=True)
        assert spec._spec_version is None

        assert versions[0] in spec
        assert spec._spec_version == (spec.version, Version(spec.version))
        initial_cache = spec._spec_version

        for v in versions[1:]:
            _ = v in spec
            assert spec._spec_version is initial_cache

        _ = hash(spec)
        assert spec._spec_version is initial_cache

        _ = spec.prereleases
        assert spec._spec_version is initial_cache


class TestSpecifierSet:
    @pytest.mark.parametrize("version", VERSIONS)
    def test_empty_specifier(self, version: str) -> None:
        spec = SpecifierSet(prereleases=True)

        assert version in spec
        assert spec.contains(version)
        assert parse(version) in spec
        assert spec.contains(parse(version))

    @pytest.mark.parametrize(
        ("prereleases", "versions", "expected"),
        [
            # single arbitrary string
            (None, ["foobar"], ["foobar"]),
            (False, ["foobar"], ["foobar"]),
            (True, ["foobar"], ["foobar"]),
            # arbitrary string with a stable version present
            (None, ["foobar", "1.0"], ["foobar", "1.0"]),
            (False, ["foobar", "1.0"], ["foobar", "1.0"]),
            (True, ["foobar", "1.0"], ["foobar", "1.0"]),
            # arbitrary string with a prerelease only
            (None, ["foobar", "1.0a1"], ["foobar", "1.0a1"]),
            (False, ["foobar", "1.0a1"], ["foobar"]),
            (True, ["foobar", "1.0a1"], ["foobar", "1.0a1"]),
        ],
    )
    def test_empty_specifier_arbitrary_string(
        self, prereleases: bool | None, versions: list[str], expected: list[str]
    ) -> None:
        """Test empty SpecifierSet accepts arbitrary strings."""

        spec = SpecifierSet("", prereleases=prereleases)

        # basic behavior preserved
        assert spec.contains("foobar")

        # check filter behavior (no override of prereleases passed to filter)
        kwargs: dict[str, bool | None] = {}
        assert list(spec.filter(versions, **kwargs)) == expected

    def test_create_from_specifiers(self) -> None:
        spec_strs = [">=1.0", "!=1.1", "!=1.2", "<2.0"]
        specs = [Specifier(s) for s in spec_strs]
        spec = SpecifierSet(iter(specs))
        assert set(spec) == set(specs)

    def test_match_args(self) -> None:
        assert SpecifierSet.__match_args__ == ("_str",)
        assert SpecifierSet(">=1.0,<2")._str == str(SpecifierSet(">=1.0,<2"))

    @pytest.mark.parametrize(
        (
            "initial_prereleases",
            "set_prereleases",
            "version",
            "initial_contains",
            "final_contains",
            "spec_str",
        ),
        [
            (None, True, "1.0.dev1", True, True, ""),
            (False, True, "1.0.dev1", False, True, ""),
            # Setting prerelease from True to False
            (True, False, "1.0.dev1", True, False, ""),
            (True, False, "1.0.dev1", False, False, ">=1.0"),
            (True, False, "1.0.dev1", True, False, "==1.*"),
            # Setting prerelease from False to None
            (False, None, "1.0.dev1", False, True, ""),
            (False, None, "2.0.dev1", False, True, ">=1.0"),
            # Setting prerelease from True to None
            (True, None, "1.0.dev1", True, True, ""),
            (True, None, "2.0.dev1", True, True, ">=1.0"),
            # Various version patterns with different transitions
            (None, True, "2.0b1", True, True, ""),
            (None, False, "2.0a1", True, False, ""),
            (True, False, "1.0rc1", True, False, ""),
            (False, True, "1.0.post1.dev1", False, True, ""),
            # Specifiers that include prerelease versions explicitly
            (None, False, "2.0.dev1", True, False, "==2.0.dev1"),
            (True, False, "1.0.dev1", True, False, "==1.0.*"),
            (False, True, "1.0.dev1", False, True, "!=2.0"),
            # SpecifierSet with multiple specifiers
            (None, True, "1.5a1", True, True, ">=1.0,<2.0"),
            (False, True, "1.5b1", False, True, ">=1.0,<2.0"),
            (True, False, "1.5rc1", True, False, ">=1.0,<2.0"),
            # Test with dev/alpha/beta/rc variations
            (None, True, "1.0a1", True, True, ""),
            (None, True, "1.0b2", True, True, ""),
            (None, True, "1.0rc3", True, True, ""),
            (None, True, "1.0.dev4", True, True, ""),
            # Test with specifiers that have prereleases implicitly
            (None, False, "1.0a1", True, False, ">=1.0a1"),
            (None, False, "0.9.dev0", True, False, "<1.0.dev1"),
        ],
    )
    def test_specifier_prereleases_explicit(
        self,
        initial_prereleases: bool | None,
        set_prereleases: bool | None,
        version: str,
        initial_contains: bool,
        final_contains: bool,
        spec_str: str,
    ) -> None:
        """Test setting prereleases property with different initial states."""
        spec = SpecifierSet(spec_str, prereleases=initial_prereleases)

        assert (version in spec) == initial_contains
        assert spec.contains(version) == initial_contains

        spec.prereleases = set_prereleases

        assert (version in spec) == final_contains
        assert spec.contains(version) == final_contains

    def test_specifier_contains_prereleases(self) -> None:
        spec = SpecifierSet()
        assert spec.prereleases is None
        assert spec.contains("1.0.dev1")
        assert spec.contains("1.0.dev1", prereleases=True)

        spec = SpecifierSet(prereleases=True)
        assert spec.prereleases
        assert spec.contains("1.0.dev1")
        assert not spec.contains("1.0.dev1", prereleases=False)

    @pytest.mark.parametrize(
        (
            "specifier",
            "version",
            "spec_prereleases",
            "contains_prereleases",
            "installed",
            "expected",
        ),
        [
            ("~=1.0", "1.1.0.dev1", None, None, True, True),
            ("~=1.0", "1.1.0.dev1", False, False, True, True),
            ("~=1.0", "1.1.0.dev1", True, False, True, True),
            ("~=1.0", "1.1.0.dev1", None, False, True, True),
            # Case when installed=False:
            ("~=1.0", "1.1.0.dev1", None, True, False, True),
            ("~=1.0", "1.1.0.dev1", False, True, False, True),
            ("~=1.0", "1.1.0.dev1", False, False, False, False),
            ("~=1.0", "1.1.0.dev1", None, False, False, False),
            # Test with different version types
            ("~=1.0", "1.1.0a1", None, None, True, True),
            ("~=1.0", "1.1.0b1", None, None, True, True),
            ("~=1.0", "1.1.0rc1", None, None, True, True),
            ("~=1.0", "1.1.0.post1.dev1", None, None, True, True),
            # Test with different specifiers
            (">=1.0", "2.0.dev1", None, None, True, True),
            ("==1.*", "1.5.0a1", None, None, True, True),
            (">=1.0,<3.0", "2.0.dev1", None, None, True, True),
            ("!=2.0", "2.0.dev1", None, None, True, True),
            # Test with non-matching versions (regardless of installed)
            ("~=1.0", "3.0.0.dev1", None, None, True, False),
            ("~=1.0", "3.0.0.dev1", True, None, True, False),
            ("~=1.0", "3.0.0.dev1", None, True, True, False),
            ("~=1.0", "3.0.0.dev1", True, True, True, False),
            ("~=1.0", "3.0.0.dev1", False, False, True, False),
            ("~=1.0", "3.0.0.dev1", None, None, False, False),
            # Test with versions outside specifier but with prereleases
            (">=2.0", "1.9.0.dev1", True, None, True, False),
            (">=2.0", "1.9.0.dev1", None, True, True, False),
            (">=2.0", "1.9.0.dev1", True, True, True, False),
            (">=2.0", "1.9.0.dev1", None, None, False, False),
            # Test with edge versions
            (">=1.0", "1.0.0.dev1", None, None, True, False),
            ("<=1.0", "1.0.0.dev1", None, None, True, True),
            ("<1.0", "1.0.0.dev1", None, None, True, False),
            ("<1.0", "0.9.0.dev1", None, None, True, True),
            # Test with specifiers that have explicit prereleases
            (">=1.0.dev1", "1.0.0.dev1", None, None, True, True),
            (">=1.0.dev1", "1.0.0.dev1", False, False, False, False),
            ("==1.0.0.dev1", "1.0.0.dev1", False, False, False, False),
            # Test with stable versions
            ("~=1.0", "1.1.0", None, None, True, True),
            ("~=1.0", "1.1.0", False, False, False, True),
            ("~=1.0", "1.1.0", True, False, False, True),
            # Test combinations of prereleases=True/False and installed=True/False
            ("~=1.0", "1.1.0.dev1", True, None, False, True),
            ("~=1.0", "1.1.0.dev1", False, None, False, False),
            # Test conflicting prereleases and contain_prereleases
            ("~=1.0", "1.1.0.dev1", True, False, False, False),
            # Test with specifiers that explicitly have prereleases overridden
            (">=1.0.dev1", "1.0.0.dev1", None, False, False, False),
            (">=1.0.dev1", "1.0.0.dev1", False, None, False, False),
        ],
    )
    def test_specifier_contains_installed_prereleases(
        self,
        specifier: str,
        version: str,
        spec_prereleases: bool | None,
        contains_prereleases: bool | None,
        installed: bool | None,
        expected: bool,
    ) -> None:
        """Test the behavior of SpecifierSet.contains with installed and prereleases."""
        spec = SpecifierSet(specifier, prereleases=spec_prereleases)

        kwargs = {}
        if contains_prereleases is not None:
            kwargs["prereleases"] = contains_prereleases
        if installed is not None:
            kwargs["installed"] = installed

        assert spec.contains(version, **kwargs) == expected

        spec = SpecifierSet("~=1.0", prereleases=False)
        assert spec.contains("1.1.0.dev1", installed=True)
        assert not spec.contains("1.1.0.dev1", prereleases=False, installed=False)

    @pytest.mark.parametrize(
        ("specifier", "specifier_prereleases", "prereleases", "input", "expected"),
        [
            # General test of the filter method
            ("", None, None, ["1.0", "2.0a1"], ["1.0"]),
            (">=1.0.dev1", None, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            ("", None, None, ["1.0a1"], ["1.0a1"]),
            (">=1.2.3", None, None, ["1.2", "1.5a1"], ["1.5a1"]),
            (">=1.2.3", None, None, ["1.3", "1.5a1"], ["1.3"]),
            ("", None, None, ["1.0", Version("2.0")], ["1.0", Version("2.0")]),
            (">=1.0", None, None, ["2.0a1"], ["2.0a1"]),
            ("!=2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0"]),
            ("==2.0a1", None, None, ["2.0a1"], ["2.0a1"]),
            (">2.0a1", None, None, ["2.0a1", "3.0a2", "3.0"], ["3.0a2", "3.0"]),
            ("<2.0a1", None, None, ["1.0a2", "1.0", "2.0a1"], ["1.0a2", "1.0"]),
            ("~=2.0a1", None, None, ["1.0", "2.0a1", "3.0a2", "3.0"], ["2.0a1"]),
            # Test overriding with the prereleases parameter on filter
            ("", None, False, ["1.0a1"], []),
            (">=1.0.dev1", None, False, ["1.0", "2.0a1"], ["1.0"]),
            ("", None, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            # Test overriding with the overall specifier
            ("", True, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            ("", False, None, ["1.0", "2.0a1"], ["1.0"]),
            (">=1.0.dev1", True, None, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            (">=1.0.dev1", False, None, ["1.0", "2.0a1"], ["1.0"]),
            ("", True, None, ["1.0a1"], ["1.0a1"]),
            ("", False, None, ["1.0a1"], []),
            # Test when both specifier and filter have prerelease value
            (">=1.0", True, False, ["1.0", "2.0a1"], ["1.0"]),
            (">=1.0", False, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            (">=1.0", True, True, ["1.0", "2.0a1"], ["1.0", "2.0a1"]),
            (">=1.0", False, False, ["1.0", "2.0a1"], ["1.0"]),
            # Test when there are multiple specifiers
            (">=1.0,<=2.0", None, None, ["1.0", "1.5a1"], ["1.0"]),
            (">=1.0,<=2.0dev", None, None, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
            (">=1.0,<=2.0", True, None, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
            (">=1.0,<=2.0", False, None, ["1.0", "1.5a1"], ["1.0"]),
            (">=1.0,<=2.0dev", False, None, ["1.0", "1.5a1"], ["1.0"]),
            (">=1.0,<=2.0dev", True, None, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
            (">=1.0,<=2.0", None, False, ["1.0", "1.5a1"], ["1.0"]),
            (">=1.0,<=2.0", None, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
            (">=1.0,<=2.0dev", None, False, ["1.0", "1.5a1"], ["1.0"]),
            (">=1.0,<=2.0dev", None, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
            (">=1.0,<=2.0", True, False, ["1.0", "1.5a1"], ["1.0"]),
            (">=1.0,<=2.0", False, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
            (">=1.0,<=2.0dev", True, False, ["1.0", "1.5a1"], ["1.0"]),
            (">=1.0,<=2.0dev", False, True, ["1.0", "1.5a1"], ["1.0", "1.5a1"]),
            # Test that invalid versions are accepted by empty SpecifierSet
            ("", None, None, ["invalid version"], ["invalid version"]),
            ("", None, False, ["invalid version"], ["invalid version"]),
            ("", False, None, ["invalid version"], ["invalid version"]),
            ("", None, None, ["1.0", "invalid version"], ["1.0", "invalid version"]),
            ("", None, False, ["1.0", "invalid version"], ["1.0", "invalid version"]),
            ("", False, None, ["1.0", "invalid version"], ["1.0", "invalid version"]),
            # Test arbitrary equality (===)
            ("===foobar", None, None, ["foobar", "foo", "bar"], ["foobar"]),
            ("===foobar", None, None, ["foo", "bar"], []),
            # Test that === does not match with zero padding
            ("===1.0", None, None, ["1.0", "1.0.0", "2.0"], ["1.0"]),
            # Test that === does not match with local versions
            ("===1.0", None, None, ["1.0", "1.0+downstream1"], ["1.0"]),
            # Test === combined with other operators (arbitrary string)
            (">=1.0,===foobar", None, None, ["foobar", "1.0", "2.0"], []),
            ("!=2.0,===foobar", None, None, ["foobar", "2.0", "bar"], []),
            # Test === combined with other operators (version string)
            (">=1.0,===1.5", None, None, ["1.0", "1.5", "2.0"], ["1.5"]),
            (">=2.0,===1.5", None, None, ["1.0", "1.5", "2.0"], []),
            # Test === with mix of valid and invalid versions
            (
                "===foobar",
                None,
                None,
                ["foobar", "1.0", "invalid", "2.0a1"],
                ["foobar"],
            ),
            ("===1.0", None, None, ["1.0", "foobar", "invalid", "1.0.0"], ["1.0"]),
            (">=1.0,===1.5", None, None, ["1.5", "foobar", "invalid"], ["1.5"]),
            # Test != with invalid versions (should pass through as "not equal")
            ("!=1.0", None, None, ["invalid", "foobar"], []),
            ("!=1.0", None, None, ["1.0", "invalid", "2.0"], ["2.0"]),
            (
                "!=2.0.*",
                None,
                None,
                ["invalid", "foobar", "2.0"],
                [],
            ),
            ("!=2.0.*", None, None, ["1.0", "invalid", "2.0.0"], ["1.0"]),
            # Test != with invalid versions combined with other operators
            (
                "!=1.0,!=2.0",
                None,
                None,
                ["invalid", "1.0", "2.0", "3.0"],
                ["3.0"],
            ),
            (
                ">=1.0,!=2.0",
                None,
                None,
                ["invalid", "1.0", "2.0", "3.0"],
                ["1.0", "3.0"],
            ),
            # Test that === ignores prereleases parameter for non-PEP 440 versions
            ("===foobar", None, True, ["foobar", "foo"], ["foobar"]),
            ("===foobar", None, False, ["foobar", "foo"], ["foobar"]),
            ("===foobar", True, None, ["foobar", "foo"], ["foobar"]),
            ("===foobar", False, None, ["foobar", "foo"], ["foobar"]),
            ("===foobar", True, True, ["foobar", "foo"], ["foobar"]),
            ("===foobar", False, False, ["foobar", "foo"], ["foobar"]),
        ],
    )
    def test_specifier_filter(
        self,
        specifier: str,
        specifier_prereleases: bool | None,
        prereleases: bool | None,
        input: list[str],
        expected: list[str],
    ) -> None:
        if specifier_prereleases is None:
            spec = SpecifierSet(specifier)
        else:
            spec = SpecifierSet(specifier, prereleases=specifier_prereleases)

        kwargs = {"prereleases": prereleases} if prereleases is not None else {}

        assert list(spec.filter(input, **kwargs)) == expected

    @pytest.mark.parametrize(
        ("specifier", "prereleases", "input", "expected"),
        [
            # !=1.*, !=2.*, !=3.0 leaves gap at 3.0 prereleases
            (
                ">=1,!=1.*,!=2.*,!=3.0,<=3.0",
                None,
                ["3.0.dev0", "3.0a1"],
                ["3.0.dev0", "3.0a1"],
            ),
            (
                ">=1,!=1.*,!=2.*,!=3.0,<=3.0",
                None,
                ["0.9", "3.0.dev0", "3.0a1", "4.0"],
                ["3.0.dev0", "3.0a1"],
            ),
            (
                ">=1,!=1.*,!=2.*,!=3.0,<=3.0",
                True,
                ["0.9", "3.0.dev0", "3.0a1", "4.0"],
                ["3.0.dev0", "3.0a1"],
            ),
            (
                ">=1,!=1.*,!=2.*,!=3.0,<=3.0",
                False,
                ["0.9", "3.0.dev0", "3.0a1", "4.0"],
                [],
            ),
            # >=1.0a1,!=1.*,!=2.*,<3.0 has no matching versions
            # because <3.0 excludes 3.0 prereleases
            (
                ">=1.0a1,!=1.*,!=2.*,<3.0",
                None,
                ["1.0a1", "2.0a1", "3.0a1"],
                [],
            ),
            (
                ">=1.0a1,!=1.*,!=2.*,<3.0",
                True,
                ["1.0a1", "2.0a1", "3.0a1"],
                [],
            ),
            (
                ">=1.0a1,!=1.*,!=2.*,<3.0",
                False,
                ["1.0a1", "2.0a1", "3.0a1"],
                [],
            ),
            # >=1.0.dev0,!=1.*,!=2.*,<3.0.dev0 has no matching versions
            (
                ">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0",
                None,
                ["1.0.dev0", "2.0.dev0", "3.0.dev0"],
                [],
            ),
            (
                ">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0",
                True,
                ["1.0.dev0", "2.0.dev0", "3.0.dev0"],
                [],
            ),
            (
                ">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0",
                False,
                ["1.0.dev0", "2.0.dev0", "3.0.dev0"],
                [],
            ),
            # Gaps with post-releases
            (
                ">=1.0,!=1.0,!=1.1,<2.0",
                None,
                ["1.0.post1", "1.1.post1"],
                ["1.0.post1", "1.1.post1"],
            ),
            (
                ">=1.0,!=1.0,!=1.1,<2.0",
                None,
                ["0.9", "1.0.post1", "1.1.post1", "2.0"],
                ["1.0.post1", "1.1.post1"],
            ),
            (
                ">=1.0,!=1.0,!=1.1,<2.0",
                True,
                ["0.9", "1.0.post1", "1.1.post1", "2.0"],
                ["1.0.post1", "1.1.post1"],
            ),
            (
                ">=1.0,!=1.0,!=1.1,<2.0",
                False,
                ["0.9", "1.0.post1", "1.1.post1", "2.0"],
                ["1.0.post1", "1.1.post1"],
            ),
            # Dev version gaps
            (
                ">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
                None,
                ["3.0.dev0", "3.1.dev0"],
                ["3.0.dev0", "3.1.dev0"],
            ),
            (
                ">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
                None,
                ["0.5", "3.0.dev0", "3.1.dev0", "5.0"],
                ["3.0.dev0", "3.1.dev0"],
            ),
            (
                ">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
                True,
                ["0.5", "3.0.dev0", "3.1.dev0", "5.0"],
                ["3.0.dev0", "3.1.dev0"],
            ),
            (
                ">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4",
                False,
                ["0.5", "3.0.dev0", "3.1.dev0", "5.0"],
                [],
            ),
            # Test that < (exclusive) excludes prereleases of the specified version
            # but allows prereleases of earlier versions.
            # <1.1 excludes 1.1.dev0, 1.1a1, etc. but allows 1.0a1, 1.0b1
            (
                ">=1.0a1,!=1.0,<1.1",
                None,
                ["1.0a1", "1.0b1"],
                ["1.0a1", "1.0b1"],
            ),
            (
                ">=1.0a1,!=1.0,<1.1",
                None,
                ["0.9", "1.0a1", "1.0b1", "1.1"],
                ["1.0a1", "1.0b1"],
            ),
            (
                ">=1.0a1,!=1.0,<1.1",
                None,
                ["1.0a1", "1.0b1", "1.1.dev0", "1.1a1"],
                ["1.0a1", "1.0b1"],
            ),
            (
                ">=1.0a1,!=1.0,<1.1",
                True,
                ["0.9", "1.0a1", "1.0b1", "1.1"],
                ["1.0a1", "1.0b1"],
            ),
            (
                ">=1.0a1,!=1.0,<1.1",
                True,
                ["1.0a1", "1.0b1", "1.1.dev0", "1.1a1"],
                ["1.0a1", "1.0b1"],
            ),
            (
                ">=1.0a1,!=1.0,<1.1",
                False,
                ["0.9", "1.0a1", "1.0b1", "1.1"],
                [],
            ),
            # Test that <= (inclusive) allows prereleases of the specified version
            # when explicitly requested, but follows default prerelease filtering
            # when prereleases=None (excludes them if final releases present)
            (
                ">=0.9,!=0.9,<=1.0",
                None,
                ["0.9.post1", "1.0.dev0", "1.0a1", "1.0"],
                [
                    "0.9.post1",
                    "1.0",
                ],  # prereleases filtered out due to presence of final release
            ),
            (
                ">=0.9,!=0.9,<=1.0",
                None,
                ["0.9.post1", "1.0.dev0", "1.0a1", "1.0", "1.0.post1"],
                [
                    "0.9.post1",
                    "1.0",
                ],  # dev/alpha filtered out; post-releases not included with <=
            ),
            (
                ">=0.9,!=0.9,<=1.0",
                True,
                ["0.9.post1", "1.0.dev0", "1.0a1", "1.0", "1.1"],
                [
                    "0.9.post1",
                    "1.0.dev0",
                    "1.0a1",
                    "1.0",
                ],  # includes prereleases when explicitly True
            ),
            (
                ">=0.9,!=0.9,<=1.0",
                False,
                ["0.9.post1", "1.0.dev0", "1.0a1", "1.0", "1.1"],
                ["0.9.post1", "1.0"],
            ),
            # Epoch-based gaps
            (
                ">=1!0,!=1!1.*,!=1!2.*,<1!3",
                None,
                ["1!0.5", "1!2.5"],
                ["1!0.5"],
            ),
            (
                ">=1!0,!=1!1.*,!=1!2.*,<1!3",
                None,
                ["0!5.0", "1!0.5", "1!2.5", "2!0.0"],
                ["1!0.5"],
            ),
            (
                ">=1!0,!=1!1.*,!=1!2.*,<1!3",
                True,
                ["0!5.0", "1!0.5", "1!2.5", "2!0.0"],
                ["1!0.5"],
            ),
            (
                ">=1!0,!=1!1.*,!=1!2.*,<1!3",
                False,
                ["0!5.0", "1!0.5", "1!2.5", "2!0.0"],
                ["1!0.5"],
            ),
        ],
    )
    def test_filter_exclusionary_bridges(
        self,
        specifier: str,
        prereleases: bool | None,
        input: list[str],
        expected: list[str],
    ) -> None:
        """
        Test that filter correctly handles exclusionary bridges.

        When specifiers exclude certain version ranges (e.g., !=1.*, !=2.*),
        there may be "gaps" where only prerelease, dev, or post versions match.
        The filter should return these matching versions regardless of whether
        non-matching non-prerelease versions are present in the input.
        """
        spec = SpecifierSet(specifier)
        kwargs = {"prereleases": prereleases} if prereleases is not None else {}
        assert list(spec.filter(input, **kwargs)) == expected

    @pytest.mark.parametrize(
        ("specifier", "prereleases", "version", "expected"),
        [
            # !=1.*, !=2.*, !=3.0 leaves gap at 3.0 prereleases
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "3.0.dev0", True),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "3.0a1", True),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", True, "3.0.dev0", True),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", True, "3.0a1", True),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", False, "3.0.dev0", False),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", False, "3.0a1", False),
            # Versions outside the gap should not match
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "0.9", False),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "1.0", False),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "2.0", False),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "3.0", False),
            (">=1,!=1.*,!=2.*,!=3.0,<=3.0", None, "4.0", False),
            # >=1.0a1,!=1.*,!=2.*,<3.0 has no matching versions
            # because <3.0 excludes 3.0 prereleases
            (">=1.0a1,!=1.*,!=2.*,<3.0", None, "1.0a1", False),
            (">=1.0a1,!=1.*,!=2.*,<3.0", None, "2.0a1", False),
            (">=1.0a1,!=1.*,!=2.*,<3.0", None, "3.0a1", False),
            (">=1.0a1,!=1.*,!=2.*,<3.0", True, "1.0a1", False),
            (">=1.0a1,!=1.*,!=2.*,<3.0", True, "2.0a1", False),
            (">=1.0a1,!=1.*,!=2.*,<3.0", False, "1.0a1", False),
            (">=1.0a1,!=1.*,!=2.*,<3.0", False, "2.0a1", False),
            # >=1.0.dev0,!=1.*,!=2.*,<3.0.dev0 has no matching versions
            (">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", None, "1.0.dev0", False),
            (">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", None, "2.0.dev0", False),
            (">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", None, "3.0.dev0", False),
            (">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", True, "1.0.dev0", False),
            (">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", True, "2.0.dev0", False),
            (">=1.0.dev0,!=1.*,!=2.*,<3.0.dev0", False, "1.0.dev0", False),
            # Gaps with post-releases
            (">=1.0,!=1.0,!=1.1,<2.0", None, "1.0.post1", True),
            (">=1.0,!=1.0,!=1.1,<2.0", None, "1.1.post1", True),
            (">=1.0,!=1.0,!=1.1,<2.0", None, "1.0", False),
            (">=1.0,!=1.0,!=1.1,<2.0", None, "1.1", False),
            (">=1.0,!=1.0,!=1.1,<2.0", None, "2.0", False),
            (">=1.0,!=1.0,!=1.1,<2.0", True, "1.0.post1", True),
            (">=1.0,!=1.0,!=1.1,<2.0", True, "1.1.post1", True),
            (">=1.0,!=1.0,!=1.1,<2.0", False, "1.0.post1", True),
            (">=1.0,!=1.0,!=1.1,<2.0", False, "1.1.post1", True),
            # Dev version gaps
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.0.dev0", True),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.1.dev0", True),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "0.5", False),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.0", False),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "3.1", False),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", None, "5.0", False),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", True, "3.0.dev0", True),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", True, "3.1.dev0", True),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", False, "3.0.dev0", False),
            (">=1,!=1.*,!=2.*,!=3.0,!=3.1,<4", False, "3.1.dev0", False),
            # Test that < (exclusive) excludes prereleases of the specified version
            # but allows prereleases of earlier versions
            (">=1.0a1,!=1.0,<1.1", None, "1.0a1", True),
            (">=1.0a1,!=1.0,<1.1", None, "1.0b1", True),
            (">=1.0a1,!=1.0,<1.1", None, "0.9", False),
            (">=1.0a1,!=1.0,<1.1", None, "1.0", False),
            (">=1.0a1,!=1.0,<1.1", None, "1.1", False),
            (">=1.0a1,!=1.0,<1.1", None, "1.1.dev0", False),
            (">=1.0a1,!=1.0,<1.1", None, "1.1a1", False),
            (">=1.0a1,!=1.0,<1.1", True, "1.0a1", True),
            (">=1.0a1,!=1.0,<1.1", True, "1.0b1", True),
            (">=1.0a1,!=1.0,<1.1", True, "1.1.dev0", False),
            (">=1.0a1,!=1.0,<1.1", True, "1.1a1", False),
            (">=1.0a1,!=1.0,<1.1", False, "1.0a1", False),
            (">=1.0a1,!=1.0,<1.1", False, "1.0b1", False),
            # Test that <= (inclusive) allows prereleases of the specified version
            # when explicitly requested, but follows default prerelease filtering
            (">=0.9,!=0.9,<=1.0", None, "0.9.post1", True),
            (">=0.9,!=0.9,<=1.0", None, "1.0", True),
            (
                ">=0.9,!=0.9,<=1.0",
                None,
                "1.0.dev0",
                True,
            ),  # <= allows prereleases of specified version
            (
                ">=0.9,!=0.9,<=1.0",
                None,
                "1.0a1",
                True,
            ),  # <= allows prereleases of specified version
            (
                ">=0.9,!=0.9,<=1.0",
                None,
                "1.0.post1",
                False,
            ),  # 1.0.post1 > 1.0 so excluded by <=1.0
            (">=0.9,!=0.9,<=1.0", True, "0.9.post1", True),
            (">=0.9,!=0.9,<=1.0", True, "1.0.dev0", True),
            (">=0.9,!=0.9,<=1.0", True, "1.0a1", True),
            (">=0.9,!=0.9,<=1.0", True, "1.0", True),
            (">=0.9,!=0.9,<=1.0", False, "0.9.post1", True),
            (">=0.9,!=0.9,<=1.0", False, "1.0.dev0", False),
            (">=0.9,!=0.9,<=1.0", False, "1.0a1", False),
            (">=0.9,!=0.9,<=1.0", False, "1.0", True),
            # Epoch-based gaps
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "1!0.5", True),
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "1!2.5", False),
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "0!5.0", False),
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", None, "2!0.0", False),
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", True, "1!0.5", True),
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", True, "0!5.0", False),
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", False, "1!0.5", True),
            (">=1!0,!=1!1.*,!=1!2.*,<1!3", False, "0!5.0", False),
        ],
    )
    def test_contains_exclusionary_bridges(
        self, specifier: str, prereleases: bool | None, version: str, expected: bool
    ) -> None:
        """
        Test that contains correctly handles exclusionary bridges.

        When specifiers exclude certain version ranges (e.g., !=1.*, !=2.*),
        there may be "gaps" where only prerelease, dev, or post versions match.
        The contains method should return True for versions in these gaps
        when prereleases=None, following PEP 440 logic.
        """
        spec = SpecifierSet(specifier)
        kwargs = {"prereleases": prereleases} if prereleases is not None else {}
        assert spec.contains(version, **kwargs) == expected

    @pytest.mark.parametrize(
        ("specifier", "input"),
        [
            (">=1.0", "not a valid version"),
        ],
    )
    def test_contains_rejects_invalid_specifier(
        self, specifier: str, input: str
    ) -> None:
        spec = SpecifierSet(specifier, prereleases=True)
        assert not spec.contains(input)

    @pytest.mark.parametrize(
        ("version", "specifier", "expected"),
        [
            # Test arbitrary equality (===) with arbitrary strings
            ("foobar", "===foobar", True),
            ("foo", "===foobar", False),
            ("bar", "===foobar", False),
            # Test that === does not match with zero padding
            ("1.0", "===1.0", True),
            ("1.0.0", "===1.0", False),
            # Test that === does not match with local versions
            ("1.0", "===1.0+downstream1", False),
            ("1.0+downstream1", "===1.0", False),
            # Test === combined with other operators (arbitrary string)
            ("foobar", "===foobar,!=1.0", False),
            ("1.0", "===foobar,!=1.0", False),
            ("foobar", ">=1.0,===foobar", False),
            # Test === combined with other operators (version string)
            ("1.5", ">=1.0,===1.5", True),
            ("1.5", ">=2.0,===1.5", False),  # Doesn't meet >=2.0
            ("2.5", ">=1.0,===2.5", True),
            # Test != with invalid versions (should not pass as not valid versions)
            ("invalid", "!=1.0", False),
            ("foobar", "!=1.0", False),
            ("invalid", "!=2.0.*", False),
            # Test != with invalid versions combined with other operators
            ("invalid", "!=1.0,!=2.0", False),
            ("foobar", ">=1.0,!=2.0", False),
            ("1.5", ">=1.0,!=2.0", True),
        ],
    )
    def test_contains_arbitrary_equality_contains(
        self, version: str, specifier: str, expected: bool
    ) -> None:
        spec = SpecifierSet(specifier)
        assert spec.contains(version) == expected

    @pytest.mark.parametrize(
        ("specifier", "expected"),
        [
            # Single item specifiers should just be reflexive
            ("!=2.0", "!=2.0"),
            ("<2.0", "<2.0"),
            ("<=2.0", "<=2.0"),
            ("==2.0", "==2.0"),
            (">2.0", ">2.0"),
            (">=2.0", ">=2.0"),
            ("~=2.0", "~=2.0"),
            # Spaces should be removed
            ("< 2", "<2"),
            # Multiple item specifiers should work
            ("!=2.0,>1.0", "!=2.0,>1.0"),
            ("!=2.0 ,>1.0", "!=2.0,>1.0"),
        ],
    )
    def test_specifiers_str_and_repr(self, specifier: str, expected: str) -> None:
        spec = SpecifierSet(specifier)

        assert str(spec) == expected
        assert repr(spec) == f""

    @pytest.mark.parametrize("specifier", SPECIFIERS + LEGACY_SPECIFIERS)
    def test_specifiers_hash(self, specifier: str) -> None:
        assert hash(SpecifierSet(specifier)) == hash(SpecifierSet(specifier))

    @pytest.mark.parametrize(
        ("left", "right", "expected"), [(">2.0", "<5.0", ">2.0,<5.0")]
    )
    def test_specifiers_combine(self, left: str, right: str, expected: str) -> None:
        result = SpecifierSet(left) & SpecifierSet(right)
        assert result == SpecifierSet(expected)

        result = SpecifierSet(left) & right
        assert result == SpecifierSet(expected)

        result = SpecifierSet(left, prereleases=True) & SpecifierSet(right)
        assert result == SpecifierSet(expected)
        assert result.prereleases

        result = SpecifierSet(left, prereleases=False) & SpecifierSet(right)
        assert result == SpecifierSet(expected)
        assert not result.prereleases

        result = SpecifierSet(left) & SpecifierSet(right, prereleases=True)
        assert result == SpecifierSet(expected)
        assert result.prereleases

        result = SpecifierSet(left) & SpecifierSet(right, prereleases=False)
        assert result == SpecifierSet(expected)
        assert not result.prereleases

        result = SpecifierSet(left, prereleases=True) & SpecifierSet(
            right, prereleases=True
        )
        assert result == SpecifierSet(expected)
        assert result.prereleases

        result = SpecifierSet(left, prereleases=False) & SpecifierSet(
            right, prereleases=False
        )
        assert result == SpecifierSet(expected)
        assert not result.prereleases

        with pytest.raises(
            ValueError,
            match=re.escape(
                "Cannot combine SpecifierSets with True and False prerelease overrides."
            ),
        ):
            result = SpecifierSet(left, prereleases=True) & SpecifierSet(
                right, prereleases=False
            )

        with pytest.raises(
            ValueError,
            match=re.escape(
                "Cannot combine SpecifierSets with True and False prerelease overrides."
            ),
        ):
            result = SpecifierSet(left, prereleases=False) & SpecifierSet(
                right, prereleases=True
            )

    def test_specifiers_combine_not_implemented(self) -> None:
        with pytest.raises(TypeError):
            SpecifierSet() & 12  # type: ignore[operator]

    @pytest.mark.parametrize(
        ("left", "right", "op"),
        itertools.chain.from_iterable(
            # Verify that the equal (==) operator works correctly
            [[(x, x, operator.eq) for x in SPECIFIERS]]
            +
            # Verify that the not equal (!=) operator works correctly
            [
                [(x, y, operator.ne) for j, y in enumerate(SPECIFIERS) if i != j]
                for i, x in enumerate(SPECIFIERS)
            ]
        ),
    )
    def test_comparison_true(
        self, left: str, right: str, op: Callable[[object, object], bool]
    ) -> None:
        assert op(SpecifierSet(left), SpecifierSet(right))
        assert op(SpecifierSet(left), Specifier(right))
        assert op(Specifier(left), SpecifierSet(right))
        assert op(left, SpecifierSet(right))
        assert op(SpecifierSet(left), right)

    @pytest.mark.parametrize(
        ("left", "right", "op"),
        itertools.chain.from_iterable(
            # Verify that the equal (==) operator works correctly
            [[(x, x, operator.ne) for x in SPECIFIERS]]
            +
            # Verify that the not equal (!=) operator works correctly
            [
                [(x, y, operator.eq) for j, y in enumerate(SPECIFIERS) if i != j]
                for i, x in enumerate(SPECIFIERS)
            ]
        ),
    )
    def test_comparison_false(
        self, left: str, right: str, op: Callable[[object, object], bool]
    ) -> None:
        assert not op(SpecifierSet(left), SpecifierSet(right))
        assert not op(SpecifierSet(left), Specifier(right))
        assert not op(Specifier(left), SpecifierSet(right))
        assert not op(left, SpecifierSet(right))
        assert not op(SpecifierSet(left), right)

    @pytest.mark.parametrize(("left", "right"), [("==2.8.0", "==2.8")])
    def test_comparison_canonicalizes(self, left: str, right: str) -> None:
        assert SpecifierSet(left) == SpecifierSet(right)
        assert left == SpecifierSet(right)
        assert SpecifierSet(left) == right

    def test_comparison_non_specifier(self) -> None:
        assert SpecifierSet("==1.0") != 12
        assert not SpecifierSet("==1.0") == 12

    @pytest.mark.parametrize(
        ("version", "specifier", "expected"),
        [
            ("1.0.0+local", "==1.0.0", True),
            ("1.0.0+local", "!=1.0.0", False),
            ("1.0.0+local", "<=1.0.0", True),
            ("1.0.0+local", ">=1.0.0", True),
            ("1.0.0+local", "<1.0.0", False),
            ("1.0.0+local", ">1.0.0", False),
        ],
    )
    def test_comparison_ignores_local(
        self, version: str, specifier: str, expected: bool
    ) -> None:
        assert (Version(version) in SpecifierSet(specifier)) == expected

    def test_contains_with_compatible_operator(self) -> None:
        combination = SpecifierSet("~=1.18.0") & SpecifierSet("~=1.18")
        assert "1.19.5" not in combination
        assert "1.18.0" in combination

    @pytest.mark.parametrize(
        ("spec1", "spec2", "input_versions"),
        [
            # Test zero padding
            ("===1.0", "===1.0.0", ["1.0", "1.0.0"]),
            ("===1.0.0", "===1.0", ["1.0", "1.0.0"]),
            ("===1.0", "===1.0.0", ["1.0.0", "1.0"]),
            ("===1.0.0", "===1.0", ["1.0.0", "1.0"]),
            # Test local versions
            ("===1.0", "===1.0+local", ["1.0", "1.0+local"]),
            ("===1.0+local", "===1.0", ["1.0", "1.0+local"]),
            ("===1.0", "===1.0+local", ["1.0+local", "1.0"]),
            ("===1.0+local", "===1.0", ["1.0+local", "1.0"]),
        ],
    )
    def test_arbitrary_equality_is_intersection_preserving(
        self, spec1: str, spec2: str, input_versions: list[str]
    ) -> None:
        """
        In general we expect for two specifiers s1 and s2, that the two statements
        are equivalent:
         * set((s1, s2).filter(versions))
         * set(s1.filter(versions)) & set(s2.filter(versions)).

        This is tricky with the arbitrary equality operator (===) since it does
        not follow normal version comparison rules.
        """
        s1 = Specifier(spec1)
        s2 = Specifier(spec2)
        versions1 = set(s1.filter(input_versions))
        versions2 = set(s2.filter(input_versions))
        combined_versions = set(SpecifierSet(f"{spec1},{spec2}").filter(input_versions))

        assert versions1 & versions2 == combined_versions
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8193686
packaging-26.0/tests/test_structures.py0000644000000000000000000000322315133751156015320 0ustar00# 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 pytest

from packaging._structures import Infinity, NegativeInfinity


def test_infinity_repr() -> None:
    assert repr(Infinity) == "Infinity"


def test_negative_infinity_repr() -> None:
    assert repr(NegativeInfinity) == "-Infinity"


def test_infinity_hash() -> None:
    assert hash(Infinity) == hash(Infinity)


def test_negative_infinity_hash() -> None:
    assert hash(NegativeInfinity) == hash(NegativeInfinity)


@pytest.mark.parametrize("left", [1, "a", ("b", 4)])
def test_infinity_comparison(left: int | str | tuple[str, int]) -> None:
    assert left < Infinity
    assert left <= Infinity
    assert not left == Infinity
    assert left != Infinity
    assert not left > Infinity
    assert not left >= Infinity


@pytest.mark.parametrize("left", [1, "a", ("b", 4)])
def test_negative_infinity_lesser(left: int | str | tuple[str, int]) -> None:
    assert not left < NegativeInfinity
    assert not left <= NegativeInfinity
    assert not left == NegativeInfinity
    assert left != NegativeInfinity
    assert left > NegativeInfinity
    assert left >= NegativeInfinity


def test_infinity_equal() -> None:
    assert Infinity == Infinity


def test_negative_infinity_equal() -> None:
    assert NegativeInfinity == NegativeInfinity


def test_negate_infinity() -> None:
    assert isinstance(-Infinity, NegativeInfinity.__class__)


def test_negate_negative_infinity() -> None:
    assert isinstance(-NegativeInfinity, Infinity.__class__)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8203685
packaging-26.0/tests/test_tags.py0000644000000000000000000020354715133751156014046 0ustar00# 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 collections.abc
import subprocess

try:
    import ctypes
except ImportError:
    ctypes = None  # type: ignore[assignment]
import importlib
import os
import pathlib
import pickle
import platform
import struct
import sys
import sysconfig
import types
import typing

import pretend
import pytest

from packaging import tags
from packaging._manylinux import _GLibCVersion
from packaging._musllinux import _MuslVersion

if typing.TYPE_CHECKING:
    from collections.abc import Callable


@pytest.fixture
def example_tag() -> tags.Tag:
    return tags.Tag("py3", "none", "any")


@pytest.fixture
def manylinux_module(monkeypatch: pytest.MonkeyPatch) -> types.ModuleType:
    monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda *args: (2, 20))  # type: ignore[attr-defined]
    module_name = "_manylinux"
    module = types.ModuleType(module_name)
    monkeypatch.setitem(sys.modules, module_name, module)
    return module


@pytest.fixture
def mock_interpreter_name(monkeypatch: pytest.MonkeyPatch) -> Callable[[str], bool]:
    def mock(name: str) -> bool:
        name = name.lower()
        if sys.implementation.name != name:
            monkeypatch.setattr(sys.implementation, "name", name)
            return True
        return False

    return mock


@pytest.fixture
def mock_ios(monkeypatch: pytest.MonkeyPatch) -> None:
    # Monkeypatch the platform to be iOS
    monkeypatch.setattr(sys, "platform", "ios")

    # Mock a fake architecture that will fit the expected pattern, but
    # won't actually be a legal multiarch.
    monkeypatch.setattr(
        sys.implementation,
        "_multiarch",
        "gothic-iphoneos",
        raising=False,
    )

    # Mock the return value of platform.ios_ver.
    def mock_ios_ver(*args: object) -> tuple[str, str, str, bool]:
        return ("iOS", "13.2", "iPhone15,2", False)

    if sys.version_info < (3, 13):
        platform.ios_ver = mock_ios_ver  # type: ignore[attr-defined]
    else:
        monkeypatch.setattr(platform, "ios_ver", mock_ios_ver)


@pytest.fixture
def mock_android(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(sys, "platform", "android")
    monkeypatch.setattr(platform, "system", lambda: "Android")
    monkeypatch.setattr(sysconfig, "get_platform", lambda: "android-21-arm64_v8a")

    AndroidVer = collections.namedtuple(
        "AndroidVer", "release api_level manufacturer model device is_emulator"
    )
    monkeypatch.setattr(
        platform,
        "android_ver",
        lambda: AndroidVer("5.0", 21, "Google", "sdk_gphone64_arm64", "emu64a", True),
        raising=False,  # This function was added in Python 3.13.
    )


class TestTag:
    def test_lowercasing(self) -> None:
        tag = tags.Tag("PY3", "None", "ANY")
        assert tag.interpreter == "py3"
        assert tag.abi == "none"
        assert tag.platform == "any"

    def test_equality(self) -> None:
        args = "py3", "none", "any"
        assert tags.Tag(*args) == tags.Tag(*args)

    def test_equality_fails_with_non_tag(self) -> None:
        assert not tags.Tag("py3", "none", "any") == "non-tag"

    def test_hashing(self, example_tag: tags.Tag) -> None:
        tags = {example_tag}  # Should not raise TypeError.
        assert example_tag in tags

    def test_hash_equality(self, example_tag: tags.Tag) -> None:
        equal_tag = tags.Tag("py3", "none", "any")
        assert example_tag == equal_tag  # Sanity check.
        assert example_tag.__hash__() == equal_tag.__hash__()

    def test_str(self, example_tag: tags.Tag) -> None:
        assert str(example_tag) == "py3-none-any"

    def test_repr(self, example_tag: tags.Tag) -> None:
        assert repr(example_tag) == f""

    def test_attribute_access(self, example_tag: tags.Tag) -> None:
        assert example_tag.interpreter == "py3"
        assert example_tag.abi == "none"
        assert example_tag.platform == "any"


class TestParseTag:
    def test_simple(self, example_tag: tags.Tag) -> None:
        parsed_tags = tags.parse_tag(str(example_tag))
        assert parsed_tags == {example_tag}

    def test_multi_interpreter(self, example_tag: tags.Tag) -> None:
        expected = {example_tag, tags.Tag("py2", "none", "any")}
        given = tags.parse_tag("py2.py3-none-any")
        assert given == expected

    def test_multi_platform(self) -> None:
        expected = {
            tags.Tag("cp37", "cp37m", platform)
            for platform in (
                "macosx_10_6_intel",
                "macosx_10_9_intel",
                "macosx_10_9_x86_64",
                "macosx_10_10_intel",
                "macosx_10_10_x86_64",
            )
        }
        given = tags.parse_tag(
            "cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64."
            "macosx_10_10_intel.macosx_10_10_x86_64"
        )
        assert given == expected


class TestInterpreterName:
    def test_sys_implementation_name(self, monkeypatch: pytest.MonkeyPatch) -> None:
        class MockImplementation:
            pass

        mock_implementation = MockImplementation()
        mock_implementation.name = "sillywalk"  # type: ignore[attr-defined]
        monkeypatch.setattr(sys, "implementation", mock_implementation, raising=False)
        assert tags.interpreter_name() == "sillywalk"

    def test_interpreter_short_names(
        self, mock_interpreter_name: Callable[[str], bool]
    ) -> None:
        mock_interpreter_name("cpython")
        assert tags.interpreter_name() == "cp"


class TestInterpreterVersion:
    def test_warn(self, monkeypatch: pytest.MonkeyPatch) -> None:
        class MockConfigVar:
            def __init__(self, return_: str) -> None:
                self.warn: bool | None = None
                self._return = return_

            def __call__(self, _name: str, warn: bool = False) -> str:
                self.warn = warn
                return self._return

        mock_config_var = MockConfigVar("38")
        monkeypatch.setattr(tags, "_get_config_var", mock_config_var)
        tags.interpreter_version(warn=True)
        assert mock_config_var.warn

    def test_python_version_nodot(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(tags, "_get_config_var", lambda _var, warn: "NN")  # noqa: ARG005
        assert tags.interpreter_version() == "NN"

    @pytest.mark.parametrize(
        ("version_info", "version_str"),
        [
            ((1, 2, 3), "12"),
            ((1, 12, 3), "112"),
            ((11, 2, 3), "112"),
            ((11, 12, 3), "1112"),
            ((1, 2, 13), "12"),
        ],
    )
    def test_sys_version_info(
        self,
        version_info: tuple[int, int, int],
        version_str: str,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        monkeypatch.setattr(tags, "_get_config_var", lambda *args, **kwargs: None)
        monkeypatch.setattr(sys, "version_info", version_info)
        assert tags.interpreter_version() == version_str


class TestMacOSPlatforms:
    @pytest.mark.parametrize(
        ("arch", "is_32bit", "expected"),
        [
            ("i386", True, "i386"),
            ("ppc", True, "ppc"),
            ("x86_64", False, "x86_64"),
            ("x86_64", True, "i386"),
            ("ppc64", False, "ppc64"),
            ("ppc64", True, "ppc"),
        ],
    )
    def test_architectures(self, arch: str, is_32bit: bool, expected: str) -> None:
        assert tags._mac_arch(arch, is_32bit=is_32bit) == expected

    @pytest.mark.parametrize(
        ("version", "arch", "expected"),
        [
            (
                (10, 15),
                "x86_64",
                ["x86_64", "intel", "fat64", "fat32", "universal2", "universal"],
            ),
            (
                (10, 4),
                "x86_64",
                ["x86_64", "intel", "fat64", "fat32", "universal2", "universal"],
            ),
            ((10, 3), "x86_64", []),
            ((10, 15), "i386", ["i386", "intel", "fat32", "fat", "universal"]),
            ((10, 4), "i386", ["i386", "intel", "fat32", "fat", "universal"]),
            ((10, 3), "intel", ["intel", "universal"]),
            ((10, 5), "intel", ["intel", "universal"]),
            ((10, 15), "intel", ["intel", "universal"]),
            ((10, 3), "i386", []),
            ((10, 15), "ppc64", []),
            ((10, 6), "ppc64", []),
            ((10, 5), "ppc64", ["ppc64", "fat64", "universal"]),
            ((10, 3), "ppc64", []),
            ((10, 15), "ppc", []),
            ((10, 7), "ppc", []),
            ((10, 6), "ppc", ["ppc", "fat32", "fat", "universal"]),
            ((10, 0), "ppc", ["ppc", "fat32", "fat", "universal"]),
            ((11, 0), "riscv", ["riscv"]),
            (
                (11, 0),
                "x86_64",
                ["x86_64", "intel", "fat64", "fat32", "universal2", "universal"],
            ),
            ((11, 0), "arm64", ["arm64", "universal2"]),
            ((11, 1), "arm64", ["arm64", "universal2"]),
            ((12, 0), "arm64", ["arm64", "universal2"]),
        ],
    )
    def test_binary_formats(
        self, version: tuple[int, int], arch: str, expected: list[str]
    ) -> None:
        assert tags._mac_binary_formats(version, arch) == expected

    def test_version_detection(self, monkeypatch: pytest.MonkeyPatch) -> None:
        if platform.system() != "Darwin":
            monkeypatch.setattr(
                platform, "mac_ver", lambda: ("10.14", ("", "", ""), "x86_64")
            )
        version = platform.mac_ver()[0].split(".")
        major = version[0]
        minor = version[1] if major == "10" else "0"

        platforms = list(tags.mac_platforms(arch="x86_64"))
        if (major, minor) == ("10", "16"):
            # For 10.16, the real version is at least 11.0.
            prefix, major, minor, _ = platforms[0].split("_", maxsplit=3)
            assert prefix == "macosx"
            assert int(major) >= 11
            assert minor == "0"
        else:
            expected = f"macosx_{major}_{minor}_"
            assert platforms[0].startswith(expected)

    def test_version_detection_10_15(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            platform, "mac_ver", lambda: ("10.15", ("", "", ""), "x86_64")
        )
        expected = "macosx_10_15_"

        platforms = list(tags.mac_platforms(arch="x86_64"))
        assert platforms[0].startswith(expected)

    def test_version_detection_compatibility(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        if platform.system() != "Darwin":
            monkeypatch.setattr(
                subprocess,
                "run",
                lambda *args, **kwargs: subprocess.CompletedProcess(
                    [], 0, stdout="10.15"
                ),
            )
        monkeypatch.setattr(
            platform, "mac_ver", lambda: ("10.16", ("", "", ""), "x86_64")
        )
        unexpected = "macosx_10_16_"

        platforms = list(tags.mac_platforms(arch="x86_64"))
        assert not platforms[0].startswith(unexpected)

    @pytest.mark.parametrize("arch", ["x86_64", "i386"])
    def test_arch_detection(self, arch: str, monkeypatch: pytest.MonkeyPatch) -> None:
        if platform.system() != "Darwin" or platform.mac_ver()[2] != arch:
            monkeypatch.setattr(
                platform, "mac_ver", lambda: ("10.14", ("", "", ""), arch)
            )
            monkeypatch.setattr(tags, "_mac_arch", lambda *args: arch)
        assert next(tags.mac_platforms((10, 14))).endswith(arch)

    def test_mac_platforms(self) -> None:
        platforms = list(tags.mac_platforms((10, 5), "x86_64"))
        assert platforms == [
            "macosx_10_5_x86_64",
            "macosx_10_5_intel",
            "macosx_10_5_fat64",
            "macosx_10_5_fat32",
            "macosx_10_5_universal2",
            "macosx_10_5_universal",
            "macosx_10_4_x86_64",
            "macosx_10_4_intel",
            "macosx_10_4_fat64",
            "macosx_10_4_fat32",
            "macosx_10_4_universal2",
            "macosx_10_4_universal",
        ]

        assert len(list(tags.mac_platforms((10, 17), "x86_64"))) == 14 * 6

        assert not list(tags.mac_platforms((10, 0), "x86_64"))

    @pytest.mark.parametrize(("major", "minor"), [(11, 0), (11, 3), (12, 0), (12, 3)])
    def test_macos_11(self, major: int, minor: int) -> None:
        platforms = list(tags.mac_platforms((major, minor), "x86_64"))
        assert "macosx_11_0_arm64" not in platforms
        assert "macosx_11_0_x86_64" in platforms
        assert "macosx_11_3_x86_64" not in platforms
        assert "macosx_11_0_universal" in platforms
        assert "macosx_11_0_universal2" in platforms
        # Mac OS "10.16" is the version number that binaries compiled against an old
        # (pre 11.0) SDK will see.   It can also be enabled explicitly for a process
        # with the environment variable SYSTEM_VERSION_COMPAT=1.
        assert "macosx_10_16_x86_64" in platforms
        assert "macosx_10_15_x86_64" in platforms
        assert "macosx_10_15_universal2" in platforms
        assert "macosx_10_4_x86_64" in platforms
        assert "macosx_10_3_x86_64" not in platforms
        if major >= 12:
            assert "macosx_12_0_x86_64" in platforms
            assert "macosx_12_0_universal" in platforms
            assert "macosx_12_0_universal2" in platforms

        platforms = list(tags.mac_platforms((major, minor), "arm64"))
        assert "macosx_11_0_arm64" in platforms
        assert "macosx_11_3_arm64" not in platforms
        assert "macosx_11_0_universal" not in platforms
        assert "macosx_11_0_universal2" in platforms
        assert "macosx_10_15_universal2" in platforms
        assert "macosx_10_15_x86_64" not in platforms
        assert "macosx_10_4_x86_64" not in platforms
        assert "macosx_10_3_x86_64" not in platforms
        if major >= 12:
            assert "macosx_12_0_arm64" in platforms
            assert "macosx_12_0_universal2" in platforms


class TestIOSPlatforms:
    @pytest.mark.usefixtures("mock_ios")
    def test_version_detection(self) -> None:
        platforms = list(tags.ios_platforms(multiarch="arm64-iphoneos"))
        assert platforms == [
            "ios_13_2_arm64_iphoneos",
            "ios_13_1_arm64_iphoneos",
            "ios_13_0_arm64_iphoneos",
            "ios_12_9_arm64_iphoneos",
            "ios_12_8_arm64_iphoneos",
            "ios_12_7_arm64_iphoneos",
            "ios_12_6_arm64_iphoneos",
            "ios_12_5_arm64_iphoneos",
            "ios_12_4_arm64_iphoneos",
            "ios_12_3_arm64_iphoneos",
            "ios_12_2_arm64_iphoneos",
            "ios_12_1_arm64_iphoneos",
            "ios_12_0_arm64_iphoneos",
        ]

    @pytest.mark.usefixtures("mock_ios")
    def test_multiarch_detection(self) -> None:
        platforms = list(tags.ios_platforms(version=(12, 0)))
        assert platforms == ["ios_12_0_gothic_iphoneos"]

    @pytest.mark.usefixtures("mock_ios")
    def test_ios_platforms(self) -> None:
        # Pre-iOS 12.0 releases won't match anything
        platforms = list(tags.ios_platforms((7, 0), "arm64-iphoneos"))
        assert platforms == []

        # iOS 12.0 returns exactly 1 match
        platforms = list(tags.ios_platforms((12, 0), "arm64-iphoneos"))
        assert platforms == ["ios_12_0_arm64_iphoneos"]

        # iOS 13.0 returns a match for 13.0, plus every 12.X
        platforms = list(tags.ios_platforms((13, 0), "x86_64-iphonesimulator"))
        assert platforms == [
            "ios_13_0_x86_64_iphonesimulator",
            "ios_12_9_x86_64_iphonesimulator",
            "ios_12_8_x86_64_iphonesimulator",
            "ios_12_7_x86_64_iphonesimulator",
            "ios_12_6_x86_64_iphonesimulator",
            "ios_12_5_x86_64_iphonesimulator",
            "ios_12_4_x86_64_iphonesimulator",
            "ios_12_3_x86_64_iphonesimulator",
            "ios_12_2_x86_64_iphonesimulator",
            "ios_12_1_x86_64_iphonesimulator",
            "ios_12_0_x86_64_iphonesimulator",
        ]

        # iOS 14.3 returns a match for 14.3-14.0, plus every 13.X and every 12.X
        platforms = list(tags.ios_platforms((14, 3), "arm64-iphoneos"))
        assert platforms == [
            "ios_14_3_arm64_iphoneos",
            "ios_14_2_arm64_iphoneos",
            "ios_14_1_arm64_iphoneos",
            "ios_14_0_arm64_iphoneos",
            "ios_13_9_arm64_iphoneos",
            "ios_13_8_arm64_iphoneos",
            "ios_13_7_arm64_iphoneos",
            "ios_13_6_arm64_iphoneos",
            "ios_13_5_arm64_iphoneos",
            "ios_13_4_arm64_iphoneos",
            "ios_13_3_arm64_iphoneos",
            "ios_13_2_arm64_iphoneos",
            "ios_13_1_arm64_iphoneos",
            "ios_13_0_arm64_iphoneos",
            "ios_12_9_arm64_iphoneos",
            "ios_12_8_arm64_iphoneos",
            "ios_12_7_arm64_iphoneos",
            "ios_12_6_arm64_iphoneos",
            "ios_12_5_arm64_iphoneos",
            "ios_12_4_arm64_iphoneos",
            "ios_12_3_arm64_iphoneos",
            "ios_12_2_arm64_iphoneos",
            "ios_12_1_arm64_iphoneos",
            "ios_12_0_arm64_iphoneos",
        ]


class TestAndroidPlatforms:
    def test_non_android(self) -> None:
        non_android_error = pytest.raises(TypeError)
        with non_android_error:
            list(tags.android_platforms())
        with non_android_error:
            list(tags.android_platforms(api_level=18))
        with non_android_error:
            list(tags.android_platforms(abi="x86_64"))

        # The function can only be called on non-Android platforms if both arguments are
        # provided.
        assert list(tags.android_platforms(api_level=18, abi="x86_64")) == [
            "android_18_x86_64",
            "android_17_x86_64",
            "android_16_x86_64",
        ]

    @pytest.mark.usefixtures("mock_android")
    def test_detection(self) -> None:
        assert list(tags.android_platforms()) == [
            "android_21_arm64_v8a",
            "android_20_arm64_v8a",
            "android_19_arm64_v8a",
            "android_18_arm64_v8a",
            "android_17_arm64_v8a",
            "android_16_arm64_v8a",
        ]

    def test_api_level(self) -> None:
        # API levels below the minimum should return nothing.
        assert list(tags.android_platforms(api_level=14, abi="x86")) == []
        assert list(tags.android_platforms(api_level=15, abi="x86")) == []

        assert list(tags.android_platforms(api_level=16, abi="x86")) == [
            "android_16_x86",
        ]
        assert list(tags.android_platforms(api_level=17, abi="x86")) == [
            "android_17_x86",
            "android_16_x86",
        ]
        assert list(tags.android_platforms(api_level=18, abi="x86")) == [
            "android_18_x86",
            "android_17_x86",
            "android_16_x86",
        ]

    def test_abi(self) -> None:
        # Real ABI, normalized.
        assert list(tags.android_platforms(api_level=16, abi="armeabi_v7a")) == [
            "android_16_armeabi_v7a",
        ]

        # Real ABI, not normalized.
        assert list(tags.android_platforms(api_level=16, abi="armeabi-v7a")) == [
            "android_16_armeabi_v7a",
        ]

        # Nonexistent ABIs should still be accepted and normalized.
        assert list(tags.android_platforms(api_level=16, abi="myarch-4.2")) == [
            "android_16_myarch_4_2",
        ]


class TestManylinuxPlatform:
    def teardown_method(self) -> None:
        # Clear the version cache
        tags._manylinux._get_glibc_version.cache_clear()  # type: ignore[attr-defined]

    def test_get_config_var_does_not_log(self, monkeypatch: pytest.MonkeyPatch) -> None:
        debug = pretend.call_recorder(lambda *a: None)
        monkeypatch.setattr(tags.logger, "debug", debug)
        tags._get_config_var("missing")
        assert debug.calls == []

    def test_get_config_var_does_log(self, monkeypatch: pytest.MonkeyPatch) -> None:
        debug = pretend.call_recorder(lambda *a: None)
        monkeypatch.setattr(tags.logger, "debug", debug)
        tags._get_config_var("missing", warn=True)
        assert debug.calls == [
            pretend.call(
                "Config variable '%s' is unset, Python ABI tag may be incorrect",
                "missing",
            )
        ]

    @pytest.mark.parametrize(
        ("arch", "is_32bit", "expected"),
        [
            ("linux-x86_64", False, ["linux_x86_64"]),
            ("linux-x86_64", True, ["linux_i686"]),
            ("linux-aarch64", False, ["linux_aarch64"]),
            ("linux-aarch64", True, ["linux_armv8l", "linux_armv7l"]),
        ],
    )
    def test_linux_platforms_32_64bit_on_64bit_os(
        self,
        arch: str,
        is_32bit: bool,
        expected: list[str],
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: arch)
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
        monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: False)  # type: ignore[attr-defined]
        linux_platform = list(tags._linux_platforms(is_32bit=is_32bit))[
            -len(expected) :
        ]
        assert linux_platform == expected

    def test_linux_platforms_manylinux_unsupported(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
        monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: False)  # type: ignore[attr-defined]
        linux_platform = list(tags._linux_platforms(is_32bit=False))
        assert linux_platform == ["linux_x86_64"]

    def test_linux_platforms_manylinux1(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            tags._manylinux,  # type: ignore[attr-defined]
            "_is_compatible",
            lambda _, glibc_version: glibc_version == _GLibCVersion(2, 5),
        )
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
        monkeypatch.setattr(platform, "machine", lambda: "x86_64")
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
        platforms = list(tags._linux_platforms(is_32bit=False))
        assert platforms == [
            "manylinux_2_5_x86_64",
            "manylinux1_x86_64",
            "linux_x86_64",
        ]

    def test_linux_platforms_manylinux2010(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
        monkeypatch.setattr(platform, "machine", lambda: "x86_64")
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.12", raising=False)
        platforms = list(tags._linux_platforms(is_32bit=False))
        expected = [
            "manylinux_2_12_x86_64",
            "manylinux2010_x86_64",
            "manylinux_2_11_x86_64",
            "manylinux_2_10_x86_64",
            "manylinux_2_9_x86_64",
            "manylinux_2_8_x86_64",
            "manylinux_2_7_x86_64",
            "manylinux_2_6_x86_64",
            "manylinux_2_5_x86_64",
            "manylinux1_x86_64",
            "linux_x86_64",
        ]
        assert platforms == expected

    def test_linux_platforms_manylinux2014(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
        monkeypatch.setattr(platform, "machine", lambda: "x86_64")
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.17", raising=False)
        platforms = list(tags._linux_platforms(is_32bit=False))
        arch = platform.machine()
        expected = [
            "manylinux_2_17_" + arch,
            "manylinux2014_" + arch,
            "manylinux_2_16_" + arch,
            "manylinux_2_15_" + arch,
            "manylinux_2_14_" + arch,
            "manylinux_2_13_" + arch,
            "manylinux_2_12_" + arch,
            "manylinux2010_" + arch,
            "manylinux_2_11_" + arch,
            "manylinux_2_10_" + arch,
            "manylinux_2_9_" + arch,
            "manylinux_2_8_" + arch,
            "manylinux_2_7_" + arch,
            "manylinux_2_6_" + arch,
            "manylinux_2_5_" + arch,
            "manylinux1_" + arch,
            "linux_" + arch,
        ]
        assert platforms == expected

    @pytest.mark.parametrize(
        ("native_arch", "cross_arch"),
        [("armv7l", "armv7l"), ("armv8l", "armv8l"), ("aarch64", "armv8l")],
    )
    def test_linux_platforms_manylinux2014_armhf_abi(
        self, native_arch: str, cross_arch: str, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(tags._manylinux, "_glibc_version_string", lambda: "2.30")  # type: ignore[attr-defined]
        monkeypatch.setattr(
            tags._manylinux,  # type: ignore[attr-defined]
            "_is_compatible",
            lambda _, glibc_version: glibc_version == _GLibCVersion(2, 17),
        )
        monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{native_arch}")
        monkeypatch.setattr(
            sys,
            "executable",
            os.path.join(
                os.path.dirname(__file__),
                "manylinux",
                "hello-world-armv7l-armhf",
            ),
        )
        platforms = list(tags._linux_platforms(is_32bit=True))
        archs = {"armv8l": ["armv8l", "armv7l"]}.get(cross_arch, [cross_arch])
        expected = []
        for arch in archs:
            expected.extend([f"manylinux_2_17_{arch}", f"manylinux2014_{arch}"])
        expected.extend(f"linux_{arch}" for arch in archs)
        assert platforms == expected

    def test_linux_platforms_manylinux2014_i386_abi(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(tags._manylinux, "_glibc_version_string", lambda: "2.17")  # type: ignore[attr-defined]
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
        monkeypatch.setattr(
            sys,
            "executable",
            os.path.join(
                os.path.dirname(__file__),
                "manylinux",
                "hello-world-x86_64-i386",
            ),
        )
        platforms = list(tags._linux_platforms(is_32bit=True))
        expected = [
            "manylinux_2_17_i686",
            "manylinux2014_i686",
            "manylinux_2_16_i686",
            "manylinux_2_15_i686",
            "manylinux_2_14_i686",
            "manylinux_2_13_i686",
            "manylinux_2_12_i686",
            "manylinux2010_i686",
            "manylinux_2_11_i686",
            "manylinux_2_10_i686",
            "manylinux_2_9_i686",
            "manylinux_2_8_i686",
            "manylinux_2_7_i686",
            "manylinux_2_6_i686",
            "manylinux_2_5_i686",
            "manylinux1_i686",
            "linux_i686",
        ]
        assert platforms == expected

    def test_linux_platforms_manylinux_glibc3(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # test for a future glic 3.x version
        monkeypatch.setattr(tags._manylinux, "_glibc_version_string", lambda: "3.2")  # type: ignore[attr-defined]
        monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: True)  # type: ignore[attr-defined]
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_aarch64")
        monkeypatch.setattr(
            sys,
            "executable",
            os.path.join(
                os.path.dirname(__file__),
                "manylinux",
                "hello-world-aarch64",
            ),
        )
        platforms = list(tags._linux_platforms(is_32bit=False))
        expected = (
            ["manylinux_3_2_aarch64", "manylinux_3_1_aarch64", "manylinux_3_0_aarch64"]
            + [f"manylinux_2_{i}_aarch64" for i in range(50, 16, -1)]
            + ["manylinux2014_aarch64", "linux_aarch64"]
        )
        assert platforms == expected

    @pytest.mark.parametrize(
        ("native_arch", "cross32_arch", "musl_version"),
        [
            ("armv7l", "armv7l", _MuslVersion(1, 1)),
            ("aarch64", "armv8l", _MuslVersion(1, 1)),
            ("i386", "i386", _MuslVersion(1, 2)),
            ("x86_64", "i686", _MuslVersion(1, 2)),
        ],
    )
    @pytest.mark.parametrize("cross32", [True, False], ids=["cross", "native"])
    def test_linux_platforms_musllinux(
        self,
        monkeypatch: pytest.MonkeyPatch,
        native_arch: str,
        cross32_arch: str,
        musl_version: _MuslVersion,
        cross32: bool,
    ) -> None:
        fake_executable = str(
            pathlib.Path(__file__)
            .parent.joinpath("musllinux", f"musl-{native_arch}")
            .resolve()
        )
        monkeypatch.setattr(tags._musllinux.sys, "executable", fake_executable)  # type: ignore[attr-defined]
        monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{native_arch}")
        monkeypatch.setattr(tags._manylinux, "platform_tags", lambda *_: ())  # type: ignore[attr-defined]

        recorder = pretend.call_recorder(lambda _: musl_version)
        monkeypatch.setattr(tags._musllinux, "_get_musl_version", recorder)  # type: ignore[attr-defined]

        platforms = list(tags._linux_platforms(is_32bit=cross32))
        target_arch = cross32_arch if cross32 else native_arch
        archs = {"armv8l": ["armv8l", "armv7l"]}.get(target_arch, [target_arch])
        expected: list[str] = []
        for arch in archs:
            expected.extend(
                f"musllinux_{musl_version[0]}_{minor}_{arch}"
                for minor in range(musl_version[1], -1, -1)
            )
        expected.extend(f"linux_{arch}" for arch in archs)
        assert platforms == expected

        assert recorder.calls == [pretend.call(fake_executable)]

    def test_linux_platforms_manylinux2014_armv6l(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(
            tags._manylinux,  # type: ignore[attr-defined]
            "_is_compatible",
            lambda _, glibc_version: glibc_version == _GLibCVersion(2, 17),
        )
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_armv6l")
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
        platforms = list(tags._linux_platforms(is_32bit=True))
        expected = ["linux_armv6l"]
        assert platforms == expected

    @pytest.mark.parametrize(
        ("machine", "abi", "alt_machine"),
        [("x86_64", "x32", "i686"), ("armv7l", "armel", "armv7l")],
    )
    def test_linux_platforms_not_manylinux_abi(
        self, monkeypatch: pytest.MonkeyPatch, machine: str, abi: str, alt_machine: str
    ) -> None:
        monkeypatch.setattr(tags._manylinux, "_is_compatible", lambda *args: False)  # type: ignore[attr-defined]
        monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}")
        monkeypatch.setattr(
            sys,
            "executable",
            os.path.join(
                os.path.dirname(__file__),
                "manylinux",
                f"hello-world-{machine}-{abi}",
            ),
        )
        platforms = list(tags._linux_platforms(is_32bit=True))
        expected = [f"linux_{alt_machine}"]
        assert platforms == expected

    def test_linux_not_linux(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "not_linux_x86_64")
        monkeypatch.setattr(platform, "machine", lambda: "x86_64")
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.17", raising=False)
        platforms = list(tags._linux_platforms(is_32bit=False))
        assert platforms == ["not_linux_x86_64"]


@pytest.mark.parametrize(
    ("platform_name", "dispatch_func"),
    [
        ("Darwin", "mac_platforms"),
        ("iOS", "ios_platforms"),
        ("Android", "android_platforms"),
        ("Linux", "_linux_platforms"),
        ("Generic", "_generic_platforms"),
    ],
)
def test_platform_tags(
    platform_name: str, dispatch_func: str, monkeypatch: pytest.MonkeyPatch
) -> None:
    expected = ["sillywalk"]
    monkeypatch.setattr(platform, "system", lambda: platform_name)
    monkeypatch.setattr(tags, dispatch_func, lambda: expected)
    assert list(tags.platform_tags()) == expected


def test_platform_tags_space(monkeypatch: pytest.MonkeyPatch) -> None:
    """Ensure spaces in platform tags are normalized to underscores."""
    monkeypatch.setattr(platform, "system", lambda: "Isilon OneFS")
    monkeypatch.setattr(sysconfig, "get_platform", lambda: "isilon onefs")
    assert list(tags.platform_tags()) == ["isilon_onefs"]


class TestCPythonABI:
    @pytest.mark.parametrize(
        ("py_debug", "gettotalrefcount", "result"),
        [(1, False, True), (0, False, False), (None, True, True)],
    )
    def test_debug(
        self,
        py_debug: int | None,
        gettotalrefcount: bool,
        result: bool,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        config = {"Py_DEBUG": py_debug, "WITH_PYMALLOC": 0, "Py_UNICODE_SIZE": 2}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        if gettotalrefcount:
            monkeypatch.setattr(sys, "gettotalrefcount", 1, raising=False)
        expected = ["cp37d" if result else "cp37"]
        assert tags._cpython_abis((3, 7)) == expected

    def test_debug_file_extension(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {"Py_DEBUG": None}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        monkeypatch.delattr(sys, "gettotalrefcount", raising=False)
        monkeypatch.setattr(tags, "EXTENSION_SUFFIXES", {"_d.pyd"})
        assert tags._cpython_abis((3, 8)) == ["cp38d", "cp38"]

    @pytest.mark.parametrize(
        ("debug", "expected"), [(True, ["cp38d", "cp38"]), (False, ["cp38"])]
    )
    def test__debug_cp38(
        self, debug: int | None, expected: list[str], monkeypatch: pytest.MonkeyPatch
    ) -> None:
        config = {"Py_DEBUG": debug}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        assert tags._cpython_abis((3, 8)) == expected

    @pytest.mark.parametrize(
        ("pymalloc", "version", "result"),
        [
            (1, (3, 7), True),
            (0, (3, 7), False),
            (None, (3, 7), True),
            (1, (3, 8), False),
        ],
    )
    def test_pymalloc(
        self,
        pymalloc: int | None,
        version: tuple[int, int],
        result: bool,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        config = {"Py_DEBUG": 0, "WITH_PYMALLOC": pymalloc, "Py_UNICODE_SIZE": 2}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        base_abi = f"cp{version[0]}{version[1]}"
        expected = [base_abi + "m" if result else base_abi]
        assert tags._cpython_abis(version) == expected

    @pytest.mark.parametrize(
        ("unicode_size", "maxunicode", "version", "result"),
        [
            (4, 0x10FFFF, (3, 2), True),
            (2, 0xFFFF, (3, 2), False),
            (None, 0x10FFFF, (3, 2), True),
            (None, 0xFFFF, (3, 2), False),
            (4, 0x10FFFF, (3, 3), False),
        ],
    )
    def test_wide_unicode(
        self,
        unicode_size: int | None,
        maxunicode: int,
        version: tuple[int, int],
        result: bool,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        config = {"Py_DEBUG": 0, "WITH_PYMALLOC": 0, "Py_UNICODE_SIZE": unicode_size}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        monkeypatch.setattr(sys, "maxunicode", maxunicode)
        base_abi = "cp" + tags._version_nodot(version)
        expected = [base_abi + "u" if result else base_abi]
        assert tags._cpython_abis(version) == expected


class TestCPythonTags:
    def test_iterator_returned(self) -> None:
        result_iterator = tags.cpython_tags(
            (3, 8), ["cp38d", "cp38"], ["plat1", "plat2"]
        )
        assert isinstance(result_iterator, collections.abc.Iterator)

    def test_all_args(self) -> None:
        result_iterator = tags.cpython_tags(
            (3, 11), ["cp311d", "cp311"], ["plat1", "plat2"]
        )
        result = list(result_iterator)
        assert result == [
            tags.Tag("cp311", "cp311d", "plat1"),
            tags.Tag("cp311", "cp311d", "plat2"),
            tags.Tag("cp311", "cp311", "plat1"),
            tags.Tag("cp311", "cp311", "plat2"),
            tags.Tag("cp311", "abi3", "plat1"),
            tags.Tag("cp311", "abi3", "plat2"),
            tags.Tag("cp311", "none", "plat1"),
            tags.Tag("cp311", "none", "plat2"),
            tags.Tag("cp310", "abi3", "plat1"),
            tags.Tag("cp310", "abi3", "plat2"),
            tags.Tag("cp39", "abi3", "plat1"),
            tags.Tag("cp39", "abi3", "plat2"),
            tags.Tag("cp38", "abi3", "plat1"),
            tags.Tag("cp38", "abi3", "plat2"),
            tags.Tag("cp37", "abi3", "plat1"),
            tags.Tag("cp37", "abi3", "plat2"),
            tags.Tag("cp36", "abi3", "plat1"),
            tags.Tag("cp36", "abi3", "plat2"),
            tags.Tag("cp35", "abi3", "plat1"),
            tags.Tag("cp35", "abi3", "plat2"),
            tags.Tag("cp34", "abi3", "plat1"),
            tags.Tag("cp34", "abi3", "plat2"),
            tags.Tag("cp33", "abi3", "plat1"),
            tags.Tag("cp33", "abi3", "plat2"),
            tags.Tag("cp32", "abi3", "plat1"),
            tags.Tag("cp32", "abi3", "plat2"),
        ]
        result_iterator = tags.cpython_tags(
            (3, 8), ["cp38d", "cp38"], ["plat1", "plat2"]
        )
        result = list(result_iterator)
        assert result == [
            tags.Tag("cp38", "cp38d", "plat1"),
            tags.Tag("cp38", "cp38d", "plat2"),
            tags.Tag("cp38", "cp38", "plat1"),
            tags.Tag("cp38", "cp38", "plat2"),
            tags.Tag("cp38", "abi3", "plat1"),
            tags.Tag("cp38", "abi3", "plat2"),
            tags.Tag("cp38", "none", "plat1"),
            tags.Tag("cp38", "none", "plat2"),
            tags.Tag("cp37", "abi3", "plat1"),
            tags.Tag("cp37", "abi3", "plat2"),
            tags.Tag("cp36", "abi3", "plat1"),
            tags.Tag("cp36", "abi3", "plat2"),
            tags.Tag("cp35", "abi3", "plat1"),
            tags.Tag("cp35", "abi3", "plat2"),
            tags.Tag("cp34", "abi3", "plat1"),
            tags.Tag("cp34", "abi3", "plat2"),
            tags.Tag("cp33", "abi3", "plat1"),
            tags.Tag("cp33", "abi3", "plat2"),
            tags.Tag("cp32", "abi3", "plat1"),
            tags.Tag("cp32", "abi3", "plat2"),
        ]

        result = list(tags.cpython_tags((3, 3), ["cp33m"], ["plat1", "plat2"]))
        assert result == [
            tags.Tag("cp33", "cp33m", "plat1"),
            tags.Tag("cp33", "cp33m", "plat2"),
            tags.Tag("cp33", "abi3", "plat1"),
            tags.Tag("cp33", "abi3", "plat2"),
            tags.Tag("cp33", "none", "plat1"),
            tags.Tag("cp33", "none", "plat2"),
            tags.Tag("cp32", "abi3", "plat1"),
            tags.Tag("cp32", "abi3", "plat2"),
        ]

        result = list(tags.cpython_tags((3, 13), ["cp313t"], ["plat1", "plat2"]))
        assert result == [
            tags.Tag("cp313", "cp313t", "plat1"),
            tags.Tag("cp313", "cp313t", "plat2"),
            tags.Tag("cp313", "none", "plat1"),
            tags.Tag("cp313", "none", "plat2"),
        ]

    def test_python_version_defaults(self) -> None:
        tag = next(tags.cpython_tags(abis=["abi3"], platforms=["any"]))
        interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
        assert interpreter == tag.interpreter

    def test_abi_defaults(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(tags, "_cpython_abis", lambda _1, _2: ["cp38"])
        result = list(tags.cpython_tags((3, 8), platforms=["any"]))
        assert tags.Tag("cp38", "cp38", "any") in result
        assert tags.Tag("cp38", "abi3", "any") in result
        assert tags.Tag("cp38", "none", "any") in result

    def test_abi_defaults_needs_underscore(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(tags, "_cpython_abis", lambda _1, _2: ["cp311"])
        result = list(tags.cpython_tags((3, 11), platforms=["any"]))
        assert tags.Tag("cp311", "cp311", "any") in result
        assert tags.Tag("cp311", "abi3", "any") in result
        assert tags.Tag("cp311", "none", "any") in result

    def test_platforms_defaults(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(tags, "platform_tags", lambda: ["plat1"])
        result = list(tags.cpython_tags((3, 8), abis=["whatever"]))
        assert tags.Tag("cp38", "whatever", "plat1") in result

    def test_platforms_defaults_needs_underscore(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(tags, "platform_tags", lambda: ["plat1"])
        result = list(tags.cpython_tags((3, 11), abis=["whatever"]))
        assert tags.Tag("cp311", "whatever", "plat1") in result

    def test_platform_name_space_normalization(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        """Ensure that spaces are translated to underscores in platform names."""
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "isilon onefs")
        for tag in tags.cpython_tags():
            assert " " not in tag.platform

    def test_major_only_python_version(self) -> None:
        result = list(tags.cpython_tags((3,), ["abi"], ["plat"]))
        assert result == [
            tags.Tag("cp3", "abi", "plat"),
            tags.Tag("cp3", "none", "plat"),
        ]

    def test_major_only_python_version_with_default_abis(self) -> None:
        result = list(tags.cpython_tags((3,), platforms=["plat"]))
        assert result == [tags.Tag("cp3", "none", "plat")]

    @pytest.mark.parametrize("abis", [[], ["abi3"], ["none"]])
    def test_skip_redundant_abis(self, abis: list[str]) -> None:
        results = list(tags.cpython_tags((3, 0), abis=abis, platforms=["any"]))
        assert results == [tags.Tag("cp30", "none", "any")]

    def test_abi3_python33(self) -> None:
        results = list(tags.cpython_tags((3, 3), abis=["cp33"], platforms=["plat"]))
        assert results == [
            tags.Tag("cp33", "cp33", "plat"),
            tags.Tag("cp33", "abi3", "plat"),
            tags.Tag("cp33", "none", "plat"),
            tags.Tag("cp32", "abi3", "plat"),
        ]

    def test_no_excess_abi3_python32(self) -> None:
        results = list(tags.cpython_tags((3, 2), abis=["cp32"], platforms=["plat"]))
        assert results == [
            tags.Tag("cp32", "cp32", "plat"),
            tags.Tag("cp32", "abi3", "plat"),
            tags.Tag("cp32", "none", "plat"),
        ]

    def test_no_abi3_python31(self) -> None:
        results = list(tags.cpython_tags((3, 1), abis=["cp31"], platforms=["plat"]))
        assert results == [
            tags.Tag("cp31", "cp31", "plat"),
            tags.Tag("cp31", "none", "plat"),
        ]

    def test_no_abi3_python27(self) -> None:
        results = list(tags.cpython_tags((2, 7), abis=["cp27"], platforms=["plat"]))
        assert results == [
            tags.Tag("cp27", "cp27", "plat"),
            tags.Tag("cp27", "none", "plat"),
        ]


class TestGenericTags:
    def test__generic_abi_macos(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            sysconfig, "get_config_var", lambda _: ".cpython-37m-darwin.so"
        )
        monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
        assert tags._generic_abi() == ["cp37m"]

    def test__generic_abi_linux_cpython(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {
            "Py_DEBUG": False,
            "WITH_PYMALLOC": True,
            "EXT_SUFFIX": ".cpython-37m-x86_64-linux-gnu.so",
        }
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")
        # They are identical
        assert tags._cpython_abis((3, 7)) == ["cp37m"]
        assert tags._generic_abi() == ["cp37m"]

    def test__generic_abi_jp(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {"EXT_SUFFIX": ".return_exactly_this.so"}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        assert tags._generic_abi() == ["return_exactly_this"]

    def test__generic_abi_graal(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {"EXT_SUFFIX": ".graalpy-38-native-x86_64-darwin.so"}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        assert tags._generic_abi() == ["graalpy_38_native"]

    def test__generic_abi_disable_gil(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {
            "Py_DEBUG": False,
            "EXT_SUFFIX": ".cpython-313t-x86_64-linux-gnu.so",
            "WITH_PYMALLOC": 0,
            "Py_GIL_DISABLED": 1,
        }
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        assert tags._generic_abi() == ["cp313t"]
        assert tags._generic_abi() == tags._cpython_abis((3, 13))

    def test__generic_abi_none(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {"EXT_SUFFIX": "..so"}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        assert tags._generic_abi() == []

    @pytest.mark.parametrize("ext_suffix", ["invalid", None])
    def test__generic_abi_error(
        self, ext_suffix: str | None, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        config = {"EXT_SUFFIX": ext_suffix}
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        with pytest.raises(SystemError) as e:
            tags._generic_abi()
        assert "EXT_SUFFIX" in str(e.value)

    def test__generic_abi_linux_pypy(self, monkeypatch: pytest.MonkeyPatch) -> None:
        # issue gh-606
        config = {
            "Py_DEBUG": False,
            "EXT_SUFFIX": ".pypy39-pp73-x86_64-linux-gnu.so",
        }
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")
        assert tags._generic_abi() == ["pypy39_pp73"]

    def test__generic_abi_old_windows(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {
            "EXT_SUFFIX": ".pyd",
            "Py_DEBUG": 0,
            "WITH_PYMALLOC": 0,
            "Py_GIL_DISABLED": 0,
        }
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        assert tags._generic_abi() == tags._cpython_abis(sys.version_info[:2])

    def test__generic_abi_windows(self, monkeypatch: pytest.MonkeyPatch) -> None:
        config = {
            "EXT_SUFFIX": ".cp310-win_amd64.pyd",
        }
        monkeypatch.setattr(sysconfig, "get_config_var", config.__getitem__)
        assert tags._generic_abi() == ["cp310"]

    @pytest.mark.skipif(sys.implementation.name != "cpython", reason="CPython-only")
    def test__generic_abi_agree(self) -> None:
        """Test that the two methods of finding the abi tag agree"""
        assert tags._generic_abi() == tags._cpython_abis(sys.version_info[:2])

    def test_generic_platforms(self) -> None:
        platform = sysconfig.get_platform().replace("-", "_")
        platform = platform.replace(".", "_")
        assert list(tags._generic_platforms()) == [platform]

    def test_generic_platforms_space(self, monkeypatch: pytest.MonkeyPatch) -> None:
        """Ensure platform tags normalize spaces to underscores."""
        platform_ = "isilon onefs"
        monkeypatch.setattr(sysconfig, "get_platform", lambda: platform_)
        assert list(tags._generic_platforms()) == [platform_.replace(" ", "_")]

    def test_iterator_returned(self) -> None:
        result_iterator = tags.generic_tags("sillywalk33", ["abi"], ["plat1", "plat2"])
        assert isinstance(result_iterator, collections.abc.Iterator)

    def test_all_args(self) -> None:
        result_iterator = tags.generic_tags("sillywalk33", ["abi"], ["plat1", "plat2"])
        result = list(result_iterator)
        assert result == [
            tags.Tag("sillywalk33", "abi", "plat1"),
            tags.Tag("sillywalk33", "abi", "plat2"),
            tags.Tag("sillywalk33", "none", "plat1"),
            tags.Tag("sillywalk33", "none", "plat2"),
        ]

    @pytest.mark.parametrize("abi", [[], ["none"]])
    def test_abi_unspecified(self, abi: list[str]) -> None:
        no_abi = list(tags.generic_tags("sillywalk34", abi, ["plat1", "plat2"]))
        assert no_abi == [
            tags.Tag("sillywalk34", "none", "plat1"),
            tags.Tag("sillywalk34", "none", "plat2"),
        ]

    def test_interpreter_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(tags, "interpreter_name", lambda: "sillywalk")
        monkeypatch.setattr(tags, "interpreter_version", lambda warn: "NN")  # noqa: ARG005
        result = list(tags.generic_tags(abis=["none"], platforms=["any"]))
        assert result == [tags.Tag("sillywalkNN", "none", "any")]

    def test_abis_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(tags, "_generic_abi", lambda: ["abi"])
        result = list(tags.generic_tags(interpreter="sillywalk", platforms=["any"]))
        assert result == [
            tags.Tag("sillywalk", "abi", "any"),
            tags.Tag("sillywalk", "none", "any"),
        ]

    def test_platforms_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(tags, "platform_tags", lambda: ["plat"])
        result = list(tags.generic_tags(interpreter="sillywalk", abis=["none"]))
        assert result == [tags.Tag("sillywalk", "none", "plat")]


class TestCompatibleTags:
    def test_all_args(self) -> None:
        result = list(tags.compatible_tags((3, 3), "cp33", ["plat1", "plat2"]))
        assert result == [
            tags.Tag("py33", "none", "plat1"),
            tags.Tag("py33", "none", "plat2"),
            tags.Tag("py3", "none", "plat1"),
            tags.Tag("py3", "none", "plat2"),
            tags.Tag("py32", "none", "plat1"),
            tags.Tag("py32", "none", "plat2"),
            tags.Tag("py31", "none", "plat1"),
            tags.Tag("py31", "none", "plat2"),
            tags.Tag("py30", "none", "plat1"),
            tags.Tag("py30", "none", "plat2"),
            tags.Tag("cp33", "none", "any"),
            tags.Tag("py33", "none", "any"),
            tags.Tag("py3", "none", "any"),
            tags.Tag("py32", "none", "any"),
            tags.Tag("py31", "none", "any"),
            tags.Tag("py30", "none", "any"),
        ]

    def test_all_args_needs_underscore(self) -> None:
        result = list(tags.compatible_tags((3, 11), "cp311", ["plat1", "plat2"]))
        assert result == [
            tags.Tag("py311", "none", "plat1"),
            tags.Tag("py311", "none", "plat2"),
            tags.Tag("py3", "none", "plat1"),
            tags.Tag("py3", "none", "plat2"),
            tags.Tag("py310", "none", "plat1"),
            tags.Tag("py310", "none", "plat2"),
            tags.Tag("py39", "none", "plat1"),
            tags.Tag("py39", "none", "plat2"),
            tags.Tag("py38", "none", "plat1"),
            tags.Tag("py38", "none", "plat2"),
            tags.Tag("py37", "none", "plat1"),
            tags.Tag("py37", "none", "plat2"),
            tags.Tag("py36", "none", "plat1"),
            tags.Tag("py36", "none", "plat2"),
            tags.Tag("py35", "none", "plat1"),
            tags.Tag("py35", "none", "plat2"),
            tags.Tag("py34", "none", "plat1"),
            tags.Tag("py34", "none", "plat2"),
            tags.Tag("py33", "none", "plat1"),
            tags.Tag("py33", "none", "plat2"),
            tags.Tag("py32", "none", "plat1"),
            tags.Tag("py32", "none", "plat2"),
            tags.Tag("py31", "none", "plat1"),
            tags.Tag("py31", "none", "plat2"),
            tags.Tag("py30", "none", "plat1"),
            tags.Tag("py30", "none", "plat2"),
            tags.Tag("cp311", "none", "any"),
            tags.Tag("py311", "none", "any"),
            tags.Tag("py3", "none", "any"),
            tags.Tag("py310", "none", "any"),
            tags.Tag("py39", "none", "any"),
            tags.Tag("py38", "none", "any"),
            tags.Tag("py37", "none", "any"),
            tags.Tag("py36", "none", "any"),
            tags.Tag("py35", "none", "any"),
            tags.Tag("py34", "none", "any"),
            tags.Tag("py33", "none", "any"),
            tags.Tag("py32", "none", "any"),
            tags.Tag("py31", "none", "any"),
            tags.Tag("py30", "none", "any"),
        ]

    def test_major_only_python_version(self) -> None:
        result = list(tags.compatible_tags((3,), "cp33", ["plat"]))
        assert result == [
            tags.Tag("py3", "none", "plat"),
            tags.Tag("cp33", "none", "any"),
            tags.Tag("py3", "none", "any"),
        ]

    def test_default_python_version(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(sys, "version_info", (3, 1))
        result = list(tags.compatible_tags(interpreter="cp31", platforms=["plat"]))
        assert result == [
            tags.Tag("py31", "none", "plat"),
            tags.Tag("py3", "none", "plat"),
            tags.Tag("py30", "none", "plat"),
            tags.Tag("cp31", "none", "any"),
            tags.Tag("py31", "none", "any"),
            tags.Tag("py3", "none", "any"),
            tags.Tag("py30", "none", "any"),
        ]

    def test_default_python_version_needs_underscore(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(sys, "version_info", (3, 11))
        result = list(tags.compatible_tags(interpreter="cp311", platforms=["plat"]))
        assert result == [
            tags.Tag("py311", "none", "plat"),
            tags.Tag("py3", "none", "plat"),
            tags.Tag("py310", "none", "plat"),
            tags.Tag("py39", "none", "plat"),
            tags.Tag("py38", "none", "plat"),
            tags.Tag("py37", "none", "plat"),
            tags.Tag("py36", "none", "plat"),
            tags.Tag("py35", "none", "plat"),
            tags.Tag("py34", "none", "plat"),
            tags.Tag("py33", "none", "plat"),
            tags.Tag("py32", "none", "plat"),
            tags.Tag("py31", "none", "plat"),
            tags.Tag("py30", "none", "plat"),
            tags.Tag("cp311", "none", "any"),
            tags.Tag("py311", "none", "any"),
            tags.Tag("py3", "none", "any"),
            tags.Tag("py310", "none", "any"),
            tags.Tag("py39", "none", "any"),
            tags.Tag("py38", "none", "any"),
            tags.Tag("py37", "none", "any"),
            tags.Tag("py36", "none", "any"),
            tags.Tag("py35", "none", "any"),
            tags.Tag("py34", "none", "any"),
            tags.Tag("py33", "none", "any"),
            tags.Tag("py32", "none", "any"),
            tags.Tag("py31", "none", "any"),
            tags.Tag("py30", "none", "any"),
        ]

    def test_default_interpreter(self) -> None:
        result = list(tags.compatible_tags((3, 1), platforms=["plat"]))
        assert result == [
            tags.Tag("py31", "none", "plat"),
            tags.Tag("py3", "none", "plat"),
            tags.Tag("py30", "none", "plat"),
            tags.Tag("py31", "none", "any"),
            tags.Tag("py3", "none", "any"),
            tags.Tag("py30", "none", "any"),
        ]

    def test_default_platforms(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(tags, "platform_tags", lambda: iter(["plat", "plat2"]))
        result = list(tags.compatible_tags((3, 1), "cp31"))
        assert result == [
            tags.Tag("py31", "none", "plat"),
            tags.Tag("py31", "none", "plat2"),
            tags.Tag("py3", "none", "plat"),
            tags.Tag("py3", "none", "plat2"),
            tags.Tag("py30", "none", "plat"),
            tags.Tag("py30", "none", "plat2"),
            tags.Tag("cp31", "none", "any"),
            tags.Tag("py31", "none", "any"),
            tags.Tag("py3", "none", "any"),
            tags.Tag("py30", "none", "any"),
        ]


class TestSysTags:
    def teardown_method(self) -> None:
        # Clear the version cache
        tags._glibc_version = []  # type: ignore[attr-defined]

    @pytest.mark.parametrize(
        ("name", "expected"),
        [("CPython", "cp"), ("PyPy", "pp"), ("Jython", "jy"), ("IronPython", "ip")],
    )
    def test_interpreter_name(
        self, name: str, expected: str, mock_interpreter_name: Callable[[str], bool]
    ) -> None:
        mock_interpreter_name(name)
        assert tags.interpreter_name() == expected

    def test_iterator(self) -> None:
        assert isinstance(tags.sys_tags(), collections.abc.Iterator)

    def test_mac_cpython(
        self,
        mock_interpreter_name: Callable[[str], bool],
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        if mock_interpreter_name("CPython"):
            monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"])
        if platform.system() != "Darwin":
            monkeypatch.setattr(platform, "system", lambda: "Darwin")
            monkeypatch.setattr(tags, "mac_platforms", lambda: ["macosx_10_5_x86_64"])
        abis = tags._cpython_abis(sys.version_info[:2])
        platforms = list(tags.mac_platforms())
        result = list(tags.sys_tags())
        assert len(abis) == 1
        assert result[0] == tags.Tag(
            "cp" + tags._version_nodot(sys.version_info[:2]), abis[0], platforms[0]
        )
        assert result[-1] == tags.Tag(
            "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
        )

    def test_windows_cpython(
        self,
        mock_interpreter_name: Callable[[str], bool],
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        if mock_interpreter_name("CPython"):
            monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"])
        if platform.system() != "Windows":
            monkeypatch.setattr(platform, "system", lambda: "Windows")
            monkeypatch.setattr(tags, "_generic_platforms", lambda: ["win_amd64"])
        abis = list(tags._cpython_abis(sys.version_info[:2]))
        platforms = list(tags._generic_platforms())
        result = list(tags.sys_tags())
        interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
        assert len(abis) == 1
        expected = tags.Tag(interpreter, abis[0], platforms[0])
        assert result[0] == expected
        expected = tags.Tag(
            "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
        )
        assert result[-1] == expected

    def test_linux_cpython(
        self,
        mock_interpreter_name: Callable[[str], bool],
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        if mock_interpreter_name("CPython"):
            monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"])
        if platform.system() != "Linux":
            monkeypatch.setattr(platform, "system", lambda: "Linux")
            monkeypatch.setattr(tags, "_linux_platforms", lambda: ["linux_x86_64"])
        abis = list(tags._cpython_abis(sys.version_info[:2]))
        platforms = list(tags._linux_platforms())
        result = list(tags.sys_tags())
        expected_interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
        assert len(abis) == 1
        assert result[0] == tags.Tag(expected_interpreter, abis[0], platforms[0])
        expected = tags.Tag(
            "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
        )
        assert result[-1] == expected

    def test_generic(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(platform, "system", lambda: "Generic")
        monkeypatch.setattr(tags, "interpreter_name", lambda: "generic")

        result = list(tags.sys_tags())
        expected = tags.Tag(
            "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any"
        )
        assert result[-1] == expected

    @pytest.mark.usefixtures("manylinux_module")
    def test_linux_platforms_manylinux2014_armv6l(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_armv6l")
        monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False)
        platforms = list(tags._linux_platforms(is_32bit=True))
        expected = ["linux_armv6l"]
        assert platforms == expected

    def test_skip_manylinux_2014(
        self, monkeypatch: pytest.MonkeyPatch, manylinux_module: types.ModuleType
    ) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_ppc64")
        monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda: (2, 20))  # type: ignore[attr-defined]
        monkeypatch.setattr(
            manylinux_module, "manylinux2014_compatible", False, raising=False
        )
        expected = [
            "manylinux_2_20_ppc64",
            "manylinux_2_19_ppc64",
            "manylinux_2_18_ppc64",
            # "manylinux2014_ppc64",  # this one is skipped
            # "manylinux_2_17_ppc64", # this one is also skipped
            "linux_ppc64",
        ]
        platforms = list(tags._linux_platforms())
        assert platforms == expected

    @pytest.mark.usefixtures("manylinux_module")
    @pytest.mark.parametrize(
        ("machine", "abi", "alt_machine"),
        [("x86_64", "x32", "i686"), ("armv7l", "armel", "armv7l")],
    )
    def test_linux_platforms_not_manylinux_abi(
        self, monkeypatch: pytest.MonkeyPatch, machine: str, abi: str, alt_machine: str
    ) -> None:
        monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}")
        monkeypatch.setattr(
            sys,
            "executable",
            os.path.join(
                os.path.dirname(__file__),
                "manylinux",
                f"hello-world-{machine}-{abi}",
            ),
        )
        platforms = list(tags._linux_platforms(is_32bit=True))
        expected = [f"linux_{alt_machine}"]
        assert platforms == expected

    @pytest.mark.parametrize(
        ("machine", "major", "minor", "tf"),
        [("x86_64", 2, 20, False), ("s390x", 2, 22, True)],
    )
    def test_linux_use_manylinux_compatible(
        self,
        monkeypatch: pytest.MonkeyPatch,
        manylinux_module: types.ModuleType,
        machine: str,
        major: int,
        minor: int,
        tf: bool,
    ) -> None:
        def manylinux_compatible(tag_major: int, tag_minor: int, tag_arch: str) -> bool:
            if tag_major == 2 and tag_minor == 22:
                return tag_arch == "s390x"
            return False

        monkeypatch.setattr(
            tags._manylinux,  # type: ignore[attr-defined]
            "_get_glibc_version",
            lambda: (major, minor),
        )
        monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}")
        monkeypatch.setattr(
            manylinux_module,
            "manylinux_compatible",
            manylinux_compatible,
            raising=False,
        )
        platforms = list(tags._linux_platforms(is_32bit=False))
        expected = [f"manylinux_2_22_{machine}"] if tf else []
        expected.append(f"linux_{machine}")
        assert platforms == expected

    def test_linux_use_manylinux_compatible_none(
        self, monkeypatch: pytest.MonkeyPatch, manylinux_module: types.ModuleType
    ) -> None:
        def manylinux_compatible(
            tag_major: int,
            tag_minor: int,
            tag_arch: str,  # noqa: ARG001
        ) -> bool | None:
            if tag_major == 2 and tag_minor < 25:
                return False
            return None

        monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda: (2, 30))  # type: ignore[attr-defined]
        monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64")
        monkeypatch.setattr(
            manylinux_module,
            "manylinux_compatible",
            manylinux_compatible,
            raising=False,
        )
        platforms = list(tags._linux_platforms(is_32bit=False))
        expected = [
            "manylinux_2_30_x86_64",
            "manylinux_2_29_x86_64",
            "manylinux_2_28_x86_64",
            "manylinux_2_27_x86_64",
            "manylinux_2_26_x86_64",
            "manylinux_2_25_x86_64",
            "linux_x86_64",
        ]
        assert platforms == expected

    def test_pypy_first_none_any_tag(self, monkeypatch: pytest.MonkeyPatch) -> None:
        # When building the complete list of pypy tags, make sure the first
        # -none-any one is pp3-none-any
        monkeypatch.setattr(tags, "interpreter_name", lambda: "pp")

        for tag in tags.sys_tags():
            if tag.abi == "none" and tag.platform == "any":
                break

        assert tag == tags.Tag("pp3", "none", "any")

    def test_cpython_first_none_any_tag(self, monkeypatch: pytest.MonkeyPatch) -> None:
        # When building the complete list of cpython tags, make sure the first
        # -none-any one is cpxx-none-any
        monkeypatch.setattr(tags, "interpreter_name", lambda: "cp")

        # Find the first tag that is ABI- and platform-agnostic.
        for tag in tags.sys_tags():
            if tag.abi == "none" and tag.platform == "any":
                break

        interpreter = f"cp{tags.interpreter_version()}"
        assert tag == tags.Tag(interpreter, "none", "any")


class TestBitness:
    def teardown_method(self) -> None:
        importlib.reload(tags)

    @pytest.mark.parametrize(
        ("maxsize", "sizeof_voidp", "expected"),
        [
            # 64-bit
            (9223372036854775807, 8, False),
            # 32-bit
            (2147483647, 4, True),
            # 64-bit w/ 32-bit sys.maxsize: GraalPy, IronPython, Jython
            (2147483647, 8, False),
        ],
    )
    def test_32bit_interpreter(
        self,
        maxsize: int,
        sizeof_voidp: int,
        expected: bool,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        def _calcsize(fmt: str) -> int:
            assert fmt == "P"
            return sizeof_voidp

        monkeypatch.setattr(sys, "maxsize", maxsize)
        monkeypatch.setattr(struct, "calcsize", _calcsize)
        importlib.reload(tags)
        assert expected == tags._32_BIT_INTERPRETER


def test_pickle() -> None:
    # Make sure equality works between a pickle/unpickle round trip.
    tag = tags.Tag("py3", "none", "any")
    assert pickle.loads(pickle.dumps(tag)) == tag
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8203685
packaging-26.0/tests/test_utils.py0000644000000000000000000001275415133751156014246 0ustar00# 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 pytest

from packaging.tags import Tag
from packaging.utils import (
    InvalidName,
    InvalidSdistFilename,
    InvalidWheelFilename,
    canonicalize_name,
    canonicalize_version,
    is_normalized_name,
    parse_sdist_filename,
    parse_wheel_filename,
)
from packaging.version import Version


@pytest.mark.parametrize(
    ("name", "expected"),
    [
        ("foo", "foo"),
        ("Foo", "foo"),
        ("fOo", "foo"),
        ("foo.bar", "foo-bar"),
        ("Foo.Bar", "foo-bar"),
        ("Foo.....Bar", "foo-bar"),
        ("foo_bar", "foo-bar"),
        ("foo___bar", "foo-bar"),
        ("foo-bar", "foo-bar"),
        ("foo----bar", "foo-bar"),
    ],
)
def test_canonicalize_name(name: str, expected: str) -> None:
    assert canonicalize_name(name) == expected


@pytest.mark.parametrize(
    ("name", "expected"),
    [
        ("_not_legal", "-not-legal"),
        ("hi\n", "hi\n"),
        ("\nhi", "\nhi"),
        ("h\ni", "h\ni"),
        ("hi\r", "hi\r"),
        ("\rhi", "\rhi"),
        ("h\ri", "h\ri"),
    ],
)
def test_canonicalize_name_invalid(name: str, expected: str) -> None:
    with pytest.raises(InvalidName):
        canonicalize_name(name, validate=True)
    assert canonicalize_name(name) == expected


@pytest.mark.parametrize(
    ("name", "expected"),
    [
        ("foo", "foo"),
        ("Foo", "foo"),
        ("fOo", "foo"),
        ("foo.bar", "foo-bar"),
        ("Foo.Bar", "foo-bar"),
        ("Foo.....Bar", "foo-bar"),
        ("foo_bar", "foo-bar"),
        ("foo___bar", "foo-bar"),
        ("foo-bar", "foo-bar"),
        ("foo----bar", "foo-bar"),
    ],
)
def test_is_normalized_name(name: str, expected: str) -> None:
    assert is_normalized_name(expected)
    if name != expected:
        assert not is_normalized_name(name)


@pytest.mark.parametrize(
    ("version", "expected"),
    [
        (Version("1.4.0"), "1.4"),
        ("1.4.0", "1.4"),
        ("1.40.0", "1.40"),
        ("1.4.0.0.00.000.0000", "1.4"),
        ("1.0", "1"),
        ("1.0+abc", "1+abc"),
        ("1.0.dev0", "1.dev0"),
        ("1.0.post0", "1.post0"),
        ("1.0a0", "1a0"),
        ("1.0rc0", "1rc0"),
        ("100!0.0", "100!0"),
        # improper version strings are unchanged
        ("lolwat", "lolwat"),
        ("1.0.1-test7", "1.0.1-test7"),
    ],
)
def test_canonicalize_version(version: str, expected: str) -> None:
    assert canonicalize_version(version) == expected


@pytest.mark.parametrize(("version"), ["1.4.0", "1.0"])
def test_canonicalize_version_no_strip_trailing_zero(version: str) -> None:
    assert canonicalize_version(version, strip_trailing_zero=False) == version


@pytest.mark.parametrize(
    ("filename", "name", "version", "build", "tags"),
    [
        (
            "foo-1.0-py3-none-any.whl",
            "foo",
            Version("1.0"),
            (),
            {Tag("py3", "none", "any")},
        ),
        (
            "some_PACKAGE-1.0-py3-none-any.whl",
            "some-package",
            Version("1.0"),
            (),
            {Tag("py3", "none", "any")},
        ),
        (
            "foo-1.0-1000-py3-none-any.whl",
            "foo",
            Version("1.0"),
            (1000, ""),
            {Tag("py3", "none", "any")},
        ),
        (
            "foo-1.0-1000abc-py3-none-any.whl",
            "foo",
            Version("1.0"),
            (1000, "abc"),
            {Tag("py3", "none", "any")},
        ),
        (
            "foo_bár-1.0-py3-none-any.whl",
            "foo-bár",
            Version("1.0"),
            (),
            {Tag("py3", "none", "any")},
        ),
        (
            "foo_bár-1.0-1000-py3-none-any.whl",
            "foo-bár",
            Version("1.0"),
            (1000, ""),
            {Tag("py3", "none", "any")},
        ),
    ],
)
def test_parse_wheel_filename(
    filename: str, name: str, version: Version, build: tuple[int, str], tags: set[Tag]
) -> None:
    assert parse_wheel_filename(filename) == (name, version, build, frozenset(tags))


@pytest.mark.parametrize(
    ("filename"),
    [
        ("foo-1.0.whl"),  # Missing tags
        ("foo-1.0-py3-none-any.wheel"),  # Incorrect file extension (`.wheel`)
        ("foo__bar-1.0-py3-none-any.whl"),  # Invalid name (`__`)
        ("foo#bar-1.0-py3-none-any.whl"),  # Invalid name (`#`)
        ("foobar-1.x-py3-none-any.whl"),  # Invalid version (`1.x`)
        # Build number doesn't start with a digit (`abc`)
        ("foo-1.0-abc-py3-none-any.whl"),
        ("foo-1.0-200-py3-none-any-junk.whl"),  # Too many dashes (`-junk`)
    ],
)
def test_parse_wheel_invalid_filename(filename: str) -> None:
    with pytest.raises(InvalidWheelFilename):
        parse_wheel_filename(filename)


@pytest.mark.parametrize(
    ("filename", "name", "version"),
    [("foo-1.0.tar.gz", "foo", Version("1.0")), ("foo-1.0.zip", "foo", Version("1.0"))],
)
def test_parse_sdist_filename(filename: str, name: str, version: Version) -> None:
    assert parse_sdist_filename(filename) == (name, version)


@pytest.mark.parametrize(
    ("filename"),
    [
        ("foo-1.0.xz"),  # Incorrect extension
        ("foo1.0.tar.gz"),  # Missing separator
        ("foo-1.x.tar.gz"),  # Invalid version
    ],
)
def test_parse_sdist_invalid_filename(filename: str) -> None:
    with pytest.raises(InvalidSdistFilename):
        parse_sdist_filename(filename)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1768936045.8203685
packaging-26.0/tests/test_version.py0000644000000000000000000010740015133751156014564 0ustar00# 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 itertools
import operator
import sys
import typing

import pretend
import pytest

from packaging.version import InvalidVersion, Version, _VersionReplace, parse

if typing.TYPE_CHECKING:
    from collections.abc import Callable

    from typing_extensions import Self, Unpack

if sys.version_info >= (3, 13):
    from copy import replace
else:
    T = typing.TypeVar("T")

    class SupportsReplace(typing.Protocol):
        def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self: ...

    S = typing.TypeVar("S", bound="SupportsReplace")

    def replace(item: S, **kwargs: Unpack[_VersionReplace]) -> S:
        return item.__replace__(**kwargs)


def test_parse() -> None:
    assert isinstance(parse("1.0"), Version)


def test_parse_raises() -> None:
    with pytest.raises(InvalidVersion):
        parse("lolwat")


# This list must be in the correct sorting order
VERSIONS = [
    # Implicit epoch of 0
    "1.0.dev456",
    "1.0a1",
    "1.0a2.dev456",
    "1.0a12.dev456",
    "1.0a12",
    "1.0b1.dev456",
    "1.0b2",
    "1.0b2.post345.dev456",
    "1.0b2.post345",
    "1.0b2-346",
    "1.0c1.dev456",
    "1.0c1",
    "1.0rc2",
    "1.0c3",
    "1.0",
    "1.0.post456.dev34",
    "1.0.post456",
    "1.1.dev1",
    "1.2+123abc",
    "1.2+123abc456",
    "1.2+abc",
    "1.2+abc123",
    "1.2+abc123def",
    "1.2+1234.abc",
    "1.2+123456",
    "1.2.r32+123456",
    "1.2.rev33+123456",
    # Explicit epoch of 1
    "1!1.0.dev456",
    "1!1.0a1",
    "1!1.0a2.dev456",
    "1!1.0a12.dev456",
    "1!1.0a12",
    "1!1.0b1.dev456",
    "1!1.0b2",
    "1!1.0b2.post345.dev456",
    "1!1.0b2.post345",
    "1!1.0b2-346",
    "1!1.0c1.dev456",
    "1!1.0c1",
    "1!1.0rc2",
    "1!1.0c3",
    "1!1.0",
    "1!1.0.post456.dev34",
    "1!1.0.post456",
    "1!1.1.dev1",
    "1!1.2+123abc",
    "1!1.2+123abc456",
    "1!1.2+abc",
    "1!1.2+abc123",
    "1!1.2+abc123def",
    "1!1.2+1234.abc",
    "1!1.2+123456",
    "1!1.2.r32+123456",
    "1!1.2.rev33+123456",
]


class TestVersion:
    @pytest.mark.parametrize("version", VERSIONS)
    def test_valid_versions(self, version: str) -> None:
        Version(version)

    def test_match_args(self) -> None:
        assert Version.__match_args__ == ("_str",)
        assert Version("1.2")._str == "1.2"

    @pytest.mark.parametrize(
        "version",
        [
            # Non sensical versions should be invalid
            "french toast",
            # Versions with invalid local versions
            "1.0+a+",
            "1.0++",
            "1.0+_foobar",
            "1.0+foo&asd",
            "1.0+1+1",
        ],
    )
    def test_invalid_versions(self, version: str) -> None:
        with pytest.raises(InvalidVersion):
            Version(version)

    @pytest.mark.parametrize(
        ("version", "normalized"),
        [
            # Various development release incarnations
            ("1.0dev", "1.0.dev0"),
            ("1.0.dev", "1.0.dev0"),
            ("1.0dev1", "1.0.dev1"),
            ("1.0-dev", "1.0.dev0"),
            ("1.0-dev1", "1.0.dev1"),
            ("1.0DEV", "1.0.dev0"),
            ("1.0.DEV", "1.0.dev0"),
            ("1.0DEV1", "1.0.dev1"),
            ("1.0.DEV1", "1.0.dev1"),
            ("1.0-DEV", "1.0.dev0"),
            ("1.0-DEV1", "1.0.dev1"),
            # Various alpha incarnations
            ("1.0a", "1.0a0"),
            ("1.0.a", "1.0a0"),
            ("1.0.a1", "1.0a1"),
            ("1.0-a", "1.0a0"),
            ("1.0-a1", "1.0a1"),
            ("1.0alpha", "1.0a0"),
            ("1.0.alpha", "1.0a0"),
            ("1.0.alpha1", "1.0a1"),
            ("1.0-alpha", "1.0a0"),
            ("1.0-alpha1", "1.0a1"),
            ("1.0A", "1.0a0"),
            ("1.0.A", "1.0a0"),
            ("1.0.A1", "1.0a1"),
            ("1.0-A", "1.0a0"),
            ("1.0-A1", "1.0a1"),
            ("1.0ALPHA", "1.0a0"),
            ("1.0.ALPHA", "1.0a0"),
            ("1.0.ALPHA1", "1.0a1"),
            ("1.0-ALPHA", "1.0a0"),
            ("1.0-ALPHA1", "1.0a1"),
            # Various beta incarnations
            ("1.0b", "1.0b0"),
            ("1.0.b", "1.0b0"),
            ("1.0.b1", "1.0b1"),
            ("1.0-b", "1.0b0"),
            ("1.0-b1", "1.0b1"),
            ("1.0beta", "1.0b0"),
            ("1.0.beta", "1.0b0"),
            ("1.0.beta1", "1.0b1"),
            ("1.0-beta", "1.0b0"),
            ("1.0-beta1", "1.0b1"),
            ("1.0B", "1.0b0"),
            ("1.0.B", "1.0b0"),
            ("1.0.B1", "1.0b1"),
            ("1.0-B", "1.0b0"),
            ("1.0-B1", "1.0b1"),
            ("1.0BETA", "1.0b0"),
            ("1.0.BETA", "1.0b0"),
            ("1.0.BETA1", "1.0b1"),
            ("1.0-BETA", "1.0b0"),
            ("1.0-BETA1", "1.0b1"),
            # Various release candidate incarnations
            ("1.0c", "1.0rc0"),
            ("1.0.c", "1.0rc0"),
            ("1.0.c1", "1.0rc1"),
            ("1.0-c", "1.0rc0"),
            ("1.0-c1", "1.0rc1"),
            ("1.0rc", "1.0rc0"),
            ("1.0.rc", "1.0rc0"),
            ("1.0.rc1", "1.0rc1"),
            ("1.0-rc", "1.0rc0"),
            ("1.0-rc1", "1.0rc1"),
            ("1.0C", "1.0rc0"),
            ("1.0.C", "1.0rc0"),
            ("1.0.C1", "1.0rc1"),
            ("1.0-C", "1.0rc0"),
            ("1.0-C1", "1.0rc1"),
            ("1.0RC", "1.0rc0"),
            ("1.0.RC", "1.0rc0"),
            ("1.0.RC1", "1.0rc1"),
            ("1.0-RC", "1.0rc0"),
            ("1.0-RC1", "1.0rc1"),
            # Various post release incarnations
            ("1.0post", "1.0.post0"),
            ("1.0.post", "1.0.post0"),
            ("1.0post1", "1.0.post1"),
            ("1.0-post", "1.0.post0"),
            ("1.0-post1", "1.0.post1"),
            ("1.0POST", "1.0.post0"),
            ("1.0.POST", "1.0.post0"),
            ("1.0POST1", "1.0.post1"),
            ("1.0r", "1.0.post0"),
            ("1.0rev", "1.0.post0"),
            ("1.0.POST1", "1.0.post1"),
            ("1.0.r1", "1.0.post1"),
            ("1.0.rev1", "1.0.post1"),
            ("1.0-POST", "1.0.post0"),
            ("1.0-POST1", "1.0.post1"),
            ("1.0-5", "1.0.post5"),
            ("1.0-r5", "1.0.post5"),
            ("1.0-rev5", "1.0.post5"),
            # Local version case insensitivity
            ("1.0+AbC", "1.0+abc"),
            # Integer Normalization
            ("1.01", "1.1"),
            ("1.0a05", "1.0a5"),
            ("1.0b07", "1.0b7"),
            ("1.0c056", "1.0rc56"),
            ("1.0rc09", "1.0rc9"),
            ("1.0.post000", "1.0.post0"),
            ("1.1.dev09000", "1.1.dev9000"),
            ("00!1.2", "1.2"),
            ("0100!0.0", "100!0.0"),
            # Various other normalizations
            ("v1.0", "1.0"),
            ("   v1.0\t\n", "1.0"),
        ],
    )
    def test_normalized_versions(self, version: str, normalized: str) -> None:
        assert str(Version(version)) == normalized

    @pytest.mark.parametrize(
        ("version", "expected"),
        [
            ("1.0.dev456", "1.0.dev456"),
            ("1.0a1", "1.0a1"),
            ("1.0a2.dev456", "1.0a2.dev456"),
            ("1.0a12.dev456", "1.0a12.dev456"),
            ("1.0a12", "1.0a12"),
            ("1.0b1.dev456", "1.0b1.dev456"),
            ("1.0b2", "1.0b2"),
            ("1.0b2.post345.dev456", "1.0b2.post345.dev456"),
            ("1.0b2.post345", "1.0b2.post345"),
            ("1.0rc1.dev456", "1.0rc1.dev456"),
            ("1.0rc1", "1.0rc1"),
            ("1.0", "1.0"),
            ("1.0.post456.dev34", "1.0.post456.dev34"),
            ("1.0.post456", "1.0.post456"),
            ("1.0.1", "1.0.1"),
            ("0!1.0.2", "1.0.2"),
            ("1.0.3+7", "1.0.3+7"),
            ("0!1.0.4+8.0", "1.0.4+8.0"),
            ("1.0.5+9.5", "1.0.5+9.5"),
            ("1.2+1234.abc", "1.2+1234.abc"),
            ("1.2+123456", "1.2+123456"),
            ("1.2+123abc", "1.2+123abc"),
            ("1.2+123abc456", "1.2+123abc456"),
            ("1.2+abc", "1.2+abc"),
            ("1.2+abc123", "1.2+abc123"),
            ("1.2+abc123def", "1.2+abc123def"),
            ("1.1.dev1", "1.1.dev1"),
            ("7!1.0.dev456", "7!1.0.dev456"),
            ("7!1.0a1", "7!1.0a1"),
            ("7!1.0a2.dev456", "7!1.0a2.dev456"),
            ("7!1.0a12.dev456", "7!1.0a12.dev456"),
            ("7!1.0a12", "7!1.0a12"),
            ("7!1.0b1.dev456", "7!1.0b1.dev456"),
            ("7!1.0b2", "7!1.0b2"),
            ("7!1.0b2.post345.dev456", "7!1.0b2.post345.dev456"),
            ("7!1.0b2.post345", "7!1.0b2.post345"),
            ("7!1.0rc1.dev456", "7!1.0rc1.dev456"),
            ("7!1.0rc1", "7!1.0rc1"),
            ("7!1.0", "7!1.0"),
            ("7!1.0.post456.dev34", "7!1.0.post456.dev34"),
            ("7!1.0.post456", "7!1.0.post456"),
            ("7!1.0.1", "7!1.0.1"),
            ("7!1.0.2", "7!1.0.2"),
            ("7!1.0.3+7", "7!1.0.3+7"),
            ("7!1.0.4+8.0", "7!1.0.4+8.0"),
            ("7!1.0.5+9.5", "7!1.0.5+9.5"),
            ("7!1.1.dev1", "7!1.1.dev1"),
        ],
    )
    def test_version_str_repr(self, version: str, expected: str) -> None:
        assert str(Version(version)) == expected
        assert repr(Version(version)) == f""

    def test_version_rc_and_c_equals(self) -> None:
        assert Version("1.0rc1") == Version("1.0c1")

    @pytest.mark.parametrize("version", VERSIONS)
    def test_version_hash(self, version: str) -> None:
        assert hash(Version(version)) == hash(Version(version))

    @pytest.mark.parametrize(
        ("version", "public"),
        [
            ("1.0", "1.0"),
            ("1.0.dev0", "1.0.dev0"),
            ("1.0.dev6", "1.0.dev6"),
            ("1.0a1", "1.0a1"),
            ("1.0a1.post5", "1.0a1.post5"),
            ("1.0a1.post5.dev6", "1.0a1.post5.dev6"),
            ("1.0rc4", "1.0rc4"),
            ("1.0.post5", "1.0.post5"),
            ("1!1.0", "1!1.0"),
            ("1!1.0.dev6", "1!1.0.dev6"),
            ("1!1.0a1", "1!1.0a1"),
            ("1!1.0a1.post5", "1!1.0a1.post5"),
            ("1!1.0a1.post5.dev6", "1!1.0a1.post5.dev6"),
            ("1!1.0rc4", "1!1.0rc4"),
            ("1!1.0.post5", "1!1.0.post5"),
            ("1.0+deadbeef", "1.0"),
            ("1.0.dev6+deadbeef", "1.0.dev6"),
            ("1.0a1+deadbeef", "1.0a1"),
            ("1.0a1.post5+deadbeef", "1.0a1.post5"),
            ("1.0a1.post5.dev6+deadbeef", "1.0a1.post5.dev6"),
            ("1.0rc4+deadbeef", "1.0rc4"),
            ("1.0.post5+deadbeef", "1.0.post5"),
            ("1!1.0+deadbeef", "1!1.0"),
            ("1!1.0.dev6+deadbeef", "1!1.0.dev6"),
            ("1!1.0a1+deadbeef", "1!1.0a1"),
            ("1!1.0a1.post5+deadbeef", "1!1.0a1.post5"),
            ("1!1.0a1.post5.dev6+deadbeef", "1!1.0a1.post5.dev6"),
            ("1!1.0rc4+deadbeef", "1!1.0rc4"),
            ("1!1.0.post5+deadbeef", "1!1.0.post5"),
        ],
    )
    def test_version_public(self, version: str, public: str) -> None:
        assert Version(version).public == public

    @pytest.mark.parametrize(
        ("version", "base_version"),
        [
            ("1.0", "1.0"),
            ("1.0.dev0", "1.0"),
            ("1.0.dev6", "1.0"),
            ("1.0a1", "1.0"),
            ("1.0a1.post5", "1.0"),
            ("1.0a1.post5.dev6", "1.0"),
            ("1.0rc4", "1.0"),
            ("1.0.post5", "1.0"),
            ("1!1.0", "1!1.0"),
            ("1!1.0.dev6", "1!1.0"),
            ("1!1.0a1", "1!1.0"),
            ("1!1.0a1.post5", "1!1.0"),
            ("1!1.0a1.post5.dev6", "1!1.0"),
            ("1!1.0rc4", "1!1.0"),
            ("1!1.0.post5", "1!1.0"),
            ("1.0+deadbeef", "1.0"),
            ("1.0.dev6+deadbeef", "1.0"),
            ("1.0a1+deadbeef", "1.0"),
            ("1.0a1.post5+deadbeef", "1.0"),
            ("1.0a1.post5.dev6+deadbeef", "1.0"),
            ("1.0rc4+deadbeef", "1.0"),
            ("1.0.post5+deadbeef", "1.0"),
            ("1!1.0+deadbeef", "1!1.0"),
            ("1!1.0.dev6+deadbeef", "1!1.0"),
            ("1!1.0a1+deadbeef", "1!1.0"),
            ("1!1.0a1.post5+deadbeef", "1!1.0"),
            ("1!1.0a1.post5.dev6+deadbeef", "1!1.0"),
            ("1!1.0rc4+deadbeef", "1!1.0"),
            ("1!1.0.post5+deadbeef", "1!1.0"),
        ],
    )
    def test_version_base_version(self, version: str, base_version: str) -> None:
        assert Version(version).base_version == base_version

    @pytest.mark.parametrize(
        ("version", "epoch"),
        [
            ("1.0", 0),
            ("1.0.dev0", 0),
            ("1.0.dev6", 0),
            ("1.0a1", 0),
            ("1.0a1.post5", 0),
            ("1.0a1.post5.dev6", 0),
            ("1.0rc4", 0),
            ("1.0.post5", 0),
            ("1!1.0", 1),
            ("1!1.0.dev6", 1),
            ("1!1.0a1", 1),
            ("1!1.0a1.post5", 1),
            ("1!1.0a1.post5.dev6", 1),
            ("1!1.0rc4", 1),
            ("1!1.0.post5", 1),
            ("1.0+deadbeef", 0),
            ("1.0.dev6+deadbeef", 0),
            ("1.0a1+deadbeef", 0),
            ("1.0a1.post5+deadbeef", 0),
            ("1.0a1.post5.dev6+deadbeef", 0),
            ("1.0rc4+deadbeef", 0),
            ("1.0.post5+deadbeef", 0),
            ("1!1.0+deadbeef", 1),
            ("1!1.0.dev6+deadbeef", 1),
            ("1!1.0a1+deadbeef", 1),
            ("1!1.0a1.post5+deadbeef", 1),
            ("1!1.0a1.post5.dev6+deadbeef", 1),
            ("1!1.0rc4+deadbeef", 1),
            ("1!1.0.post5+deadbeef", 1),
        ],
    )
    def test_version_epoch(self, version: str, epoch: int) -> None:
        assert Version(version).epoch == epoch

    @pytest.mark.parametrize(
        ("version", "release"),
        [
            ("1.0", (1, 0)),
            ("1.0.dev0", (1, 0)),
            ("1.0.dev6", (1, 0)),
            ("1.0a1", (1, 0)),
            ("1.0a1.post5", (1, 0)),
            ("1.0a1.post5.dev6", (1, 0)),
            ("1.0rc4", (1, 0)),
            ("1.0.post5", (1, 0)),
            ("1!1.0", (1, 0)),
            ("1!1.0.dev6", (1, 0)),
            ("1!1.0a1", (1, 0)),
            ("1!1.0a1.post5", (1, 0)),
            ("1!1.0a1.post5.dev6", (1, 0)),
            ("1!1.0rc4", (1, 0)),
            ("1!1.0.post5", (1, 0)),
            ("1.0+deadbeef", (1, 0)),
            ("1.0.dev6+deadbeef", (1, 0)),
            ("1.0a1+deadbeef", (1, 0)),
            ("1.0a1.post5+deadbeef", (1, 0)),
            ("1.0a1.post5.dev6+deadbeef", (1, 0)),
            ("1.0rc4+deadbeef", (1, 0)),
            ("1.0.post5+deadbeef", (1, 0)),
            ("1!1.0+deadbeef", (1, 0)),
            ("1!1.0.dev6+deadbeef", (1, 0)),
            ("1!1.0a1+deadbeef", (1, 0)),
            ("1!1.0a1.post5+deadbeef", (1, 0)),
            ("1!1.0a1.post5.dev6+deadbeef", (1, 0)),
            ("1!1.0rc4+deadbeef", (1, 0)),
            ("1!1.0.post5+deadbeef", (1, 0)),
        ],
    )
    def test_version_release(self, version: str, release: tuple[int, int]) -> None:
        assert Version(version).release == release

    @pytest.mark.parametrize(
        ("version", "local"),
        [
            ("1.0", None),
            ("1.0.dev0", None),
            ("1.0.dev6", None),
            ("1.0a1", None),
            ("1.0a1.post5", None),
            ("1.0a1.post5.dev6", None),
            ("1.0rc4", None),
            ("1.0.post5", None),
            ("1!1.0", None),
            ("1!1.0.dev6", None),
            ("1!1.0a1", None),
            ("1!1.0a1.post5", None),
            ("1!1.0a1.post5.dev6", None),
            ("1!1.0rc4", None),
            ("1!1.0.post5", None),
            ("1.0+deadbeef", "deadbeef"),
            ("1.0.dev6+deadbeef", "deadbeef"),
            ("1.0a1+deadbeef", "deadbeef"),
            ("1.0a1.post5+deadbeef", "deadbeef"),
            ("1.0a1.post5.dev6+deadbeef", "deadbeef"),
            ("1.0rc4+deadbeef", "deadbeef"),
            ("1.0.post5+deadbeef", "deadbeef"),
            ("1!1.0+deadbeef", "deadbeef"),
            ("1!1.0.dev6+deadbeef", "deadbeef"),
            ("1!1.0a1+deadbeef", "deadbeef"),
            ("1!1.0a1.post5+deadbeef", "deadbeef"),
            ("1!1.0a1.post5.dev6+deadbeef", "deadbeef"),
            ("1!1.0rc4+deadbeef", "deadbeef"),
            ("1!1.0.post5+deadbeef", "deadbeef"),
        ],
    )
    def test_version_local(self, version: str, local: str | None) -> None:
        assert Version(version).local == local

    @pytest.mark.parametrize(
        ("version", "pre"),
        [
            ("1.0", None),
            ("1.0.dev0", None),
            ("1.0.dev6", None),
            ("1.0a1", ("a", 1)),
            ("1.0a1.post5", ("a", 1)),
            ("1.0a1.post5.dev6", ("a", 1)),
            ("1.0rc4", ("rc", 4)),
            ("1.0.post5", None),
            ("1!1.0", None),
            ("1!1.0.dev6", None),
            ("1!1.0a1", ("a", 1)),
            ("1!1.0a1.post5", ("a", 1)),
            ("1!1.0a1.post5.dev6", ("a", 1)),
            ("1!1.0rc4", ("rc", 4)),
            ("1!1.0.post5", None),
            ("1.0+deadbeef", None),
            ("1.0.dev6+deadbeef", None),
            ("1.0a1+deadbeef", ("a", 1)),
            ("1.0a1.post5+deadbeef", ("a", 1)),
            ("1.0a1.post5.dev6+deadbeef", ("a", 1)),
            ("1.0rc4+deadbeef", ("rc", 4)),
            ("1.0.post5+deadbeef", None),
            ("1!1.0+deadbeef", None),
            ("1!1.0.dev6+deadbeef", None),
            ("1!1.0a1+deadbeef", ("a", 1)),
            ("1!1.0a1.post5+deadbeef", ("a", 1)),
            ("1!1.0a1.post5.dev6+deadbeef", ("a", 1)),
            ("1!1.0rc4+deadbeef", ("rc", 4)),
            ("1!1.0.post5+deadbeef", None),
        ],
    )
    def test_version_pre(self, version: str, pre: None | tuple[str, int]) -> None:
        assert Version(version).pre == pre

    @pytest.mark.parametrize(
        ("version", "expected"),
        [
            ("1.0.dev0", True),
            ("1.0.dev1", True),
            ("1.0a1.dev1", True),
            ("1.0b1.dev1", True),
            ("1.0c1.dev1", True),
            ("1.0rc1.dev1", True),
            ("1.0a1", True),
            ("1.0b1", True),
            ("1.0c1", True),
            ("1.0rc1", True),
            ("1.0a1.post1.dev1", True),
            ("1.0b1.post1.dev1", True),
            ("1.0c1.post1.dev1", True),
            ("1.0rc1.post1.dev1", True),
            ("1.0a1.post1", True),
            ("1.0b1.post1", True),
            ("1.0c1.post1", True),
            ("1.0rc1.post1", True),
            ("1.0", False),
            ("1.0+dev", False),
            ("1.0.post1", False),
            ("1.0.post1+dev", False),
        ],
    )
    def test_version_is_prerelease(self, version: str, expected: bool) -> None:
        assert Version(version).is_prerelease is expected

    @pytest.mark.parametrize(
        ("version", "dev"),
        [
            ("1.0", None),
            ("1.0.dev0", 0),
            ("1.0.dev6", 6),
            ("1.0a1", None),
            ("1.0a1.post5", None),
            ("1.0a1.post5.dev6", 6),
            ("1.0rc4", None),
            ("1.0.post5", None),
            ("1!1.0", None),
            ("1!1.0.dev6", 6),
            ("1!1.0a1", None),
            ("1!1.0a1.post5", None),
            ("1!1.0a1.post5.dev6", 6),
            ("1!1.0rc4", None),
            ("1!1.0.post5", None),
            ("1.0+deadbeef", None),
            ("1.0.dev6+deadbeef", 6),
            ("1.0a1+deadbeef", None),
            ("1.0a1.post5+deadbeef", None),
            ("1.0a1.post5.dev6+deadbeef", 6),
            ("1.0rc4+deadbeef", None),
            ("1.0.post5+deadbeef", None),
            ("1!1.0+deadbeef", None),
            ("1!1.0.dev6+deadbeef", 6),
            ("1!1.0a1+deadbeef", None),
            ("1!1.0a1.post5+deadbeef", None),
            ("1!1.0a1.post5.dev6+deadbeef", 6),
            ("1!1.0rc4+deadbeef", None),
            ("1!1.0.post5+deadbeef", None),
        ],
    )
    def test_version_dev(self, version: str, dev: int | None) -> None:
        assert Version(version).dev == dev

    @pytest.mark.parametrize(
        ("version", "expected"),
        [
            ("1.0", False),
            ("1.0.dev0", True),
            ("1.0.dev6", True),
            ("1.0a1", False),
            ("1.0a1.post5", False),
            ("1.0a1.post5.dev6", True),
            ("1.0rc4", False),
            ("1.0.post5", False),
            ("1!1.0", False),
            ("1!1.0.dev6", True),
            ("1!1.0a1", False),
            ("1!1.0a1.post5", False),
            ("1!1.0a1.post5.dev6", True),
            ("1!1.0rc4", False),
            ("1!1.0.post5", False),
            ("1.0+deadbeef", False),
            ("1.0.dev6+deadbeef", True),
            ("1.0a1+deadbeef", False),
            ("1.0a1.post5+deadbeef", False),
            ("1.0a1.post5.dev6+deadbeef", True),
            ("1.0rc4+deadbeef", False),
            ("1.0.post5+deadbeef", False),
            ("1!1.0+deadbeef", False),
            ("1!1.0.dev6+deadbeef", True),
            ("1!1.0a1+deadbeef", False),
            ("1!1.0a1.post5+deadbeef", False),
            ("1!1.0a1.post5.dev6+deadbeef", True),
            ("1!1.0rc4+deadbeef", False),
            ("1!1.0.post5+deadbeef", False),
        ],
    )
    def test_version_is_devrelease(self, version: str, expected: bool) -> None:
        assert Version(version).is_devrelease is expected

    @pytest.mark.parametrize(
        ("version", "post"),
        [
            ("1.0", None),
            ("1.0.dev0", None),
            ("1.0.dev6", None),
            ("1.0a1", None),
            ("1.0a1.post5", 5),
            ("1.0a1.post5.dev6", 5),
            ("1.0rc4", None),
            ("1.0.post5", 5),
            ("1!1.0", None),
            ("1!1.0.dev6", None),
            ("1!1.0a1", None),
            ("1!1.0a1.post5", 5),
            ("1!1.0a1.post5.dev6", 5),
            ("1!1.0rc4", None),
            ("1!1.0.post5", 5),
            ("1.0+deadbeef", None),
            ("1.0.dev6+deadbeef", None),
            ("1.0a1+deadbeef", None),
            ("1.0a1.post5+deadbeef", 5),
            ("1.0a1.post5.dev6+deadbeef", 5),
            ("1.0rc4+deadbeef", None),
            ("1.0.post5+deadbeef", 5),
            ("1!1.0+deadbeef", None),
            ("1!1.0.dev6+deadbeef", None),
            ("1!1.0a1+deadbeef", None),
            ("1!1.0a1.post5+deadbeef", 5),
            ("1!1.0a1.post5.dev6+deadbeef", 5),
            ("1!1.0rc4+deadbeef", None),
            ("1!1.0.post5+deadbeef", 5),
        ],
    )
    def test_version_post(self, version: str, post: int | None) -> None:
        assert Version(version).post == post

    @pytest.mark.parametrize(
        ("version", "expected"),
        [
            ("1.0.dev1", False),
            ("1.0", False),
            ("1.0+foo", False),
            ("1.0.post1.dev1", True),
            ("1.0.post1", True),
        ],
    )
    def test_version_is_postrelease(self, version: str, expected: bool) -> None:
        assert Version(version).is_postrelease is expected

    @pytest.mark.parametrize(
        ("left", "right", "op"),
        # Below we'll generate every possible combination of VERSIONS that
        # should be True for the given operator
        itertools.chain.from_iterable(
            # Verify that the less than (<) operator works correctly
            [
                [(x, y, operator.lt) for y in VERSIONS[i + 1 :]]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the less than equal (<=) operator works correctly
            [
                [(x, y, operator.le) for y in VERSIONS[i:]]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the equal (==) operator works correctly
            [[(x, x, operator.eq) for x in VERSIONS]]
            +
            # Verify that the not equal (!=) operator works correctly
            [
                [(x, y, operator.ne) for j, y in enumerate(VERSIONS) if i != j]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the greater than equal (>=) operator works correctly
            [
                [(x, y, operator.ge) for y in VERSIONS[: i + 1]]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the greater than (>) operator works correctly
            [
                [(x, y, operator.gt) for y in VERSIONS[:i]]
                for i, x in enumerate(VERSIONS)
            ]
        ),
    )
    def test_comparison_true(
        self, left: str, right: str, op: Callable[[Version, Version], bool]
    ) -> None:
        assert op(Version(left), Version(right))

    @pytest.mark.parametrize(
        ("left", "right", "op"),
        # Below we'll generate every possible combination of VERSIONS that
        # should be False for the given operator
        itertools.chain.from_iterable(
            # Verify that the less than (<) operator works correctly
            [
                [(x, y, operator.lt) for y in VERSIONS[: i + 1]]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the less than equal (<=) operator works correctly
            [
                [(x, y, operator.le) for y in VERSIONS[:i]]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the equal (==) operator works correctly
            [
                [(x, y, operator.eq) for j, y in enumerate(VERSIONS) if i != j]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the not equal (!=) operator works correctly
            [[(x, x, operator.ne) for x in VERSIONS]]
            +
            # Verify that the greater than equal (>=) operator works correctly
            [
                [(x, y, operator.ge) for y in VERSIONS[i + 1 :]]
                for i, x in enumerate(VERSIONS)
            ]
            +
            # Verify that the greater than (>) operator works correctly
            [
                [(x, y, operator.gt) for y in VERSIONS[i:]]
                for i, x in enumerate(VERSIONS)
            ]
        ),
    )
    def test_comparison_false(
        self, left: str, right: str, op: Callable[[Version, Version], bool]
    ) -> None:
        assert not op(Version(left), Version(right))

    @pytest.mark.parametrize("op", ["lt", "le", "eq", "ge", "gt", "ne"])
    def test_dunder_op_returns_notimplemented(self, op: str) -> None:
        method = getattr(Version, f"__{op}__")
        assert method(Version("1"), 1) is NotImplemented

    @pytest.mark.parametrize(("op", "expected"), [("eq", False), ("ne", True)])
    def test_compare_other(self, op: str, expected: bool) -> None:
        other = pretend.stub(**{f"__{op}__": lambda _: NotImplemented})

        assert getattr(operator, op)(Version("1"), other) is expected

    def test_major_version(self) -> None:
        assert Version("2.1.0").major == 2

    def test_minor_version(self) -> None:
        assert Version("2.1.0").minor == 1
        assert Version("2").minor == 0

    def test_micro_version(self) -> None:
        assert Version("2.1.3").micro == 3
        assert Version("2.1").micro == 0
        assert Version("2").micro == 0

    # Tests for replace() method
    def test_replace_no_args(self) -> None:
        """replace() with no arguments should return an equivalent version"""
        v = Version("1.2.3a1.post2.dev3+local")
        v_replaced = replace(v)
        assert v == v_replaced
        assert str(v) == str(v_replaced)

    def test_replace_epoch(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, epoch=2)) == "2!1.2.3"
        assert replace(v, epoch=0).epoch == 0

        v_with_epoch = Version("1!1.2.3")
        assert str(replace(v_with_epoch, epoch=2)) == "2!1.2.3"
        assert str(replace(v_with_epoch, epoch=None)) == "1.2.3"

    def test_replace_release_tuple(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, release=(2, 0, 0))) == "2.0.0"
        assert str(replace(v, release=(1,))) == "1"
        assert str(replace(v, release=(1, 2, 3, 4, 5))) == "1.2.3.4.5"

    def test_replace_release_none(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, release=None)) == "0"

    def test_replace_pre_alpha(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, pre=("a", 1))) == "1.2.3a1"
        assert str(replace(v, pre=("a", 0))) == "1.2.3a0"

    def test_replace_pre_alpha_none(self) -> None:
        v = Version("1.2.3a1")
        assert str(replace(v, pre=None)) == "1.2.3"

    def test_replace_pre_beta(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, pre=("b", 1))) == "1.2.3b1"
        assert str(replace(v, pre=("b", 0))) == "1.2.3b0"

    def test_replace_pre_beta_none(self) -> None:
        v = Version("1.2.3b1")
        assert str(replace(v, pre=None)) == "1.2.3"

    def test_replace_pre_rc(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, pre=("rc", 1))) == "1.2.3rc1"
        assert str(replace(v, pre=("rc", 0))) == "1.2.3rc0"

    def test_replace_pre_rc_none(self) -> None:
        v = Version("1.2.3rc1")
        assert str(replace(v, pre=None)) == "1.2.3"

    def test_replace_post(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, post=1)) == "1.2.3.post1"
        assert str(replace(v, post=0)) == "1.2.3.post0"

    def test_replace_post_none(self) -> None:
        v = Version("1.2.3.post1")
        assert str(replace(v, post=None)) == "1.2.3"

    def test_replace_dev(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, dev=1)) == "1.2.3.dev1"
        assert str(replace(v, dev=0)) == "1.2.3.dev0"

    def test_replace_dev_none(self) -> None:
        v = Version("1.2.3.dev1")
        assert str(replace(v, dev=None)) == "1.2.3"

    def test_replace_local_string(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, local="abc")) == "1.2.3+abc"
        assert str(replace(v, local="abc.123")) == "1.2.3+abc.123"
        assert str(replace(v, local="abc-123")) == "1.2.3+abc.123"

    def test_replace_local_none(self) -> None:
        v = Version("1.2.3+local")
        assert str(replace(v, local=None)) == "1.2.3"

    def test_replace_multiple_components(self) -> None:
        v = Version("1.2.3")
        assert str(replace(v, pre=("a", 1), post=1)) == "1.2.3a1.post1"
        assert str(replace(v, release=(2, 0, 0), pre=("b", 2), dev=1)) == "2.0.0b2.dev1"
        assert str(replace(v, epoch=1, release=(3, 0), local="abc")) == "1!3.0+abc"

    def test_replace_clear_all_optional(self) -> None:
        v = Version("1!1.2.3a1.post2.dev3+local")
        cleared = replace(v, epoch=None, pre=None, post=None, dev=None, local=None)
        assert str(cleared) == "1.2.3"

    def test_replace_preserves_comparison(self) -> None:
        v1 = Version("1.2.3")
        v2 = Version("1.2.4")

        v1_new = replace(v1, release=(1, 2, 4))
        assert v1_new == v2
        assert v1 < v2
        assert v1_new >= v2

    def test_replace_preserves_hash(self) -> None:
        v1 = Version("1.2.3")
        v2 = replace(v1, release=(1, 2, 3))
        assert hash(v1) == hash(v2)

        v3 = replace(v1, release=(2, 0, 0))
        assert hash(v1) != hash(v3)

    def test_replace_returns_same_instance_when_unchanged(self) -> None:
        """replace() returns the exact same object when no components change"""
        v = Version("1.2.3a1.post2.dev3+local")
        assert replace(v) is v
        assert replace(v, epoch=0) is v
        assert replace(v, release=(1, 2, 3)) is v
        assert replace(v, pre=("a", 1)) is v
        assert replace(v, post=2) is v
        assert replace(v, dev=3) is v
        assert replace(v, local="local") is v

    def test_replace_change_pre_type(self) -> None:
        """Can change from one pre-release type to another"""
        v = Version("1.2.3a1")
        assert str(replace(v, pre=("b", 2))) == "1.2.3b2"
        assert str(replace(v, pre=("rc", 1))) == "1.2.3rc1"

        v2 = Version("1.2.3rc5")
        assert str(replace(v2, pre=("a", 0))) == "1.2.3a0"

    def test_replace_invalid_epoch_type(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="epoch must be non-negative"):
            replace(v, epoch="1")  # type: ignore[arg-type]

    def test_replace_invalid_post_type(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="post must be non-negative"):
            replace(v, post="1")  # type: ignore[arg-type]

    def test_replace_invalid_dev_type(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="dev must be non-negative"):
            replace(v, dev="1")  # type: ignore[arg-type]

    def test_replace_invalid_epoch_negative(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="epoch must be non-negative"):
            replace(v, epoch=-1)

    def test_replace_invalid_release_empty(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="release must be a non-empty tuple"):
            replace(v, release=())

    def test_replace_invalid_release_tuple_content(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(
            InvalidVersion, match="release must be a non-empty tuple of non-negative"
        ):
            replace(v, release=(1, -2, 3))

    def test_replace_invalid_pre_negative(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="pre must be a tuple"):
            replace(v, pre=("a", -1))

    def test_replace_invalid_pre_type(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="pre must be a tuple"):
            replace(v, pre=("x", 1))  # type: ignore[arg-type]

    def test_replace_invalid_pre_format(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="pre must be a tuple"):
            replace(v, pre="a1")  # type: ignore[arg-type]
        with pytest.raises(InvalidVersion, match="pre must be a tuple"):
            replace(v, pre=("a",))  # type: ignore[arg-type]
        with pytest.raises(InvalidVersion, match="pre must be a tuple"):
            replace(v, pre=("a", 1, 2))  # type: ignore[arg-type]

    def test_replace_invalid_post_negative(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="post must be non-negative"):
            replace(v, post=-1)

    def test_replace_invalid_dev_negative(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(InvalidVersion, match="dev must be non-negative"):
            replace(v, dev=-1)

    def test_replace_invalid_local_string(self) -> None:
        v = Version("1.2.3")
        with pytest.raises(
            InvalidVersion, match="local must be a valid version string"
        ):
            replace(v, local="abc+123")
        with pytest.raises(
            InvalidVersion, match="local must be a valid version string"
        ):
            replace(v, local="+abc")


# Taken from hatchling 1.28
def reset_version_parts(version: Version, **kwargs: typing.Any) -> None:  # noqa: ANN401
    # https://github.com/pypa/packaging/blob/20.9/packaging/version.py#L301-L310
    internal_version = version._version
    parts: dict[str, typing.Any] = {}
    ordered_part_names = ("epoch", "release", "pre", "post", "dev", "local")

    reset = False
    for part_name in ordered_part_names:
        if reset:
            parts[part_name] = kwargs.get(part_name)
        elif part_name in kwargs:
            parts[part_name] = kwargs[part_name]
            reset = True
        else:
            parts[part_name] = getattr(internal_version, part_name)

    version._version = type(internal_version)(**parts)


# These will be deprecated in 26.1, and removed in the future
def test_deprecated__version() -> None:
    v = Version("1.2.3")
    with pytest.warns(DeprecationWarning, match="is private"):
        assert v._version.release == (1, 2, 3)


def test_hatchling_usage__version() -> None:
    v = Version("2.3.4")
    with pytest.warns(DeprecationWarning, match="is private"):
        reset_version_parts(v, post=("post", 1))
    assert v == Version("2.3.4.post1")
packaging-26.0/PKG-INFO0000644000000000000000000000635500000000000011362 0ustar00Metadata-Version: 2.4
Name: packaging
Version: 26.0
Summary: Core utilities for Python packages
Author-email: Donald Stufft 
Requires-Python: >=3.8
Description-Content-Type: text/x-rst
License-Expression: Apache-2.0 OR BSD-2-Clause
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Typing :: Typed
License-File: LICENSE
License-File: LICENSE.APACHE
License-File: LICENSE.BSD
Project-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 `_.

This library provides utilities that implement the interoperability
specifications 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
- Requirements
- Tags
- Metadata
- Lockfiles
- 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 ``#pypa`` on Freenode to ask questions or get involved.


.. _`documentation`: https://packaging.pypa.io/
.. _`issue tracker`: https://github.com/pypa/packaging/issues


Code of Conduct
---------------

Everyone interacting in the packaging project's codebases, issue trackers, chat
rooms, 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 as
well as how to report a potential security issue. The documentation for this
project 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`_ for
recent changes and project history.

.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/