././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1033566 packaging-26.2/CHANGELOG.rst0000644000000000000000000006421715172742311012353 0ustar00Changelog --------- 26.2 - 2026-04-24 ~~~~~~~~~~~~~~~~~ Fixes: * Fix incorrect sysconfig var name for pyemscripten in (:pull:`1160`) * Make ``Version``, ``Specifier``, ``SpecifierSet``, ``Tag``, ``Marker``, and ``Requirement`` pickle-safe and backward-compatible with pickles created in 25.0-26.1 (including references to the removed ``packaging._structures`` module) (:pull:`1163`, :pull:`1168`, :pull:`1170`, :pull:`1171`) * Re-export ``ExceptionGroup`` in metatadata for now in (:pull:`1164`) Documentation: * Add errors section and fix missing details in (:pull:`1159`) * Document our property-based test suite in (:pull:`1167`) * Fix a ``DirectUrl`` typo in (:pull:`1167`) * Add example of ``is_unsatisfiable`` in (:pull:`1166`) Internal: * Enable the auditor persona on zizmor in (:pull:`1158`) * Test new pickle gaurentees in (:pull:`1174`) * Use new native ReadTheDocs uv integration in (:pull:`1175`) 26.1 - 2026-04-14 ~~~~~~~~~~~~~~~~~ Features: * PEP 783: add handling for Emscripten wheel tags in (:pull:`804`) (old name used in implementation, fixed in next release) * PEP 803: add handling for the ``abi3.abi3t`` free-threading tag in (:pull:`1099`) * PEP 723: add ``packaging.dependency_groups`` module, based on the ``dependency-groups`` package in (:pull:`1065`) * Add the ``packaging.direct_url`` module in (:pull:`944`) * Add the ``packaging.errors`` module in (:pull:`1071`) * Add ``SpecifierSet.is_unsatisfiable`` using ranges (new internals that will be expanded in future versions) in (:pull:`1119`) * Add ``create_compatible_tags_selector`` to select compatible tags in (:pull:`1110`) * Add a ``key`` argument to ``SpecifierSet.filter()`` in (:pull:`1068`) * Support ``&`` and ``|`` for ``Marker``'s in (:pull:`1146`) * Normalize ``Version.__replace__`` and add ``Version.from_parts`` in (:pull:`1078`) * Add an option to validate compressed tag set sort order in ``parse_wheel_filename`` in (:pull:`1150`) Behavior adaptations: * Narrow exclusion of pre-releases for ``V`` to match spec in (:pull:`1141`) * Rename ``format_full_version`` to ``_format_full_version`` to make it visibly private in (:pull:`1125`) * Restrict local version to ASCII in (:pull:`1102`) Pylock (PEP 751) updates: * Add pylock ``select`` function in (:pull:`1092`) * Document pylock ``select()`` method and ``PylockSelectError`` in (:pull:`1153`) * Add ``filename`` property to ``PackageSdist`` and ``PackageWheel``, more validation in (:pull:`1095`) * Give preference to path over url in (:pull:`1128`) * Validate name/version consistency in file names in (:pull:`1114`) Fixes: * Fix ``>`` comparison for versions with dev+local segments in (:pull:`1097`) * Fix incorrect self-comparison for ``InfinityType`` and ``NegativeInfinityType`` in (:pull:`1093`) * Canonicalize when deduplicating specifiers in ``SpecifierSet`` in (:pull:`1109`) * Fix charset error message formatting in (:pull:`1121`) * Handle the ``key`` parameter in ``SpecifierSet.filter`` when specifiers are empty and prerelease is ``False`` in (:pull:`1096`) * Standardize inner components of ``repr`` output in (:pull:`1090`) * ``Specifier``'s ``===`` uses original string, not normalized, when available in (:pull:`1124`) * Propagate int-max-str-digits ``ValueError`` in (:pull:`1155`) Performance: * Add fast path for parsing simple versions (digits and dots only) in (:pull:`1082`) * Add fast path for ``Version`` to ``Version`` comparison by skipping ``_key`` property in (:pull:`1083`) * Cache ``Version`` hash value in dedicated slot in (:pull:`1118`) * Overhaul ``_cmpkey`` to remove use of custom objects in (:pull:`1116`) * Skip ``__replace__`` in Specifier comparison if not needed in (:pull:`1081`) * ``SpecifierSet`` use ``tuple`` instead of ``frozenset`` for ``_specs`` in (:pull:`1108`) * Speed up complex ``SpecifierSet`` filtering by implementing cost-based ordering in (:pull:`1105`) * Speed up wildcard comparison in (:pull:`1111`) * Stream PEP440 filtering in ``SpecifierSet.filter`` in (:pull:`1076`) * Add ``__slots__`` to ``Marker`` in (:pull:`1147`) * Simply ``Specifier`` regex in (:pull:`1106`) * Skip using the hash property internally in (:pull:`1115`) Internal: * Add downstream testing in (:pull:`1049`) * Benchmarking suite in (:pull:`1059`) * Benchmark variance reduction in (:pull:`1107`) * Add property-based tests for PEP 440 in (:pull:`1144`) * Clean up a few ``collections.namedtuple`` in tests in (:pull:`1070`) * Do not reload the tags module in tests in (:pull:`1152`) * Limit ``dir()`` / tab-completion in REPL in (:pull:`1011`) * Add more ``__all__`/`__dir__`` in (:pull:`1069`) * Cleanup pre-commit a bit in (:pull:`1080`) * Pin pre-commit file, use dependabot in (:pull:`1133`) * Remove sphinx-toolbox in (:pull:`1135`) * Use docs group, faster readthedocs in (:pull:`1061`) * Add free-threaded Python to CI in (:pull:`1098`) * Simplify combining ``SpecifierSet.prereleases`` in (:pull:`1073`) * Use direct operator methods in ``_compare_compatible`` in (:pull:`1100`) * Remove unnecessary if statement in ``Specifier.prereleases`` in (:pull:`1074`) * Remove unneeded nesting in ``Specifier.prereleases`` in (:pull:`1072`) Documentation: * Fix documentation: grammar, typos, formatting, and outdated references in (:pull:`1084`) * Fix versionadded for ``Version.from_parts()`` in (:pull:`1134`) * Document ``&`` and ``|`` operators for combining ``Marker`` objects in (:pull:`1151`) * Expand and clean up ``Version`` documentation in (:pull:`1089`) * Move license docs inline in (:pull:`1131`) * Move markers inline in (:pull:`1104`) * Move tags docs to inline in (:pull:`1130`) * Move utilities inline, like other modules in (:pull:`1103`) 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=1777059017.1033566 packaging-26.2/LICENSE0000644000000000000000000000030515172742311011323 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=1777059017.1033566 packaging-26.2/LICENSE.APACHE0000644000000000000000000002367615172742311012263 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=1777059017.1033566 packaging-26.2/LICENSE.BSD0000644000000000000000000000250015172742311011731 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=1777059017.1033566 packaging-26.2/README.rst0000644000000000000000000000431715172742311012014 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 - Licenses - Requirements - Metadata - Tags - Lockfiles (pylock) - Direct URL helpers - Dependency groups - Errors - Utilities Installation ------------ Use ``pip`` to install these utilities:: pip install packaging The ``packaging`` library uses calendar-based versioning (``YY.N``). Discussion ---------- If you run into bugs, you can file them in our `issue tracker`_. You can also join discussions on `GitHub Discussions`_ to ask questions or get involved. .. _`documentation`: https://packaging.pypa.io/ .. _`issue tracker`: https://github.com/pypa/packaging/issues .. _`GitHub Discussions`: https://github.com/pypa/packaging/discussions Code of Conduct --------------- Everyone interacting in the packaging project's codebases, issue trackers, 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=1777059017.1043568 packaging-26.2/docs/Makefile0000644000000000000000000001271015172742311012711 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=1777059017.1046183 packaging-26.2/docs/changelog.rst0000644000000000000000000000003615172742311013730 0ustar00.. include:: ../CHANGELOG.rst ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1046183 packaging-26.2/docs/conf.py0000644000000000000000000000761715172742311012562 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", ] # 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 autodoc_default_options = { "exclude-members": "__weakref__", } # Allow the signature to be overridden autodoc_docstring_signature = 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=1777059017.1046183 packaging-26.2/docs/dependency_groups.rst0000644000000000000000000000431215172742311015517 0ustar00Dependency Groups ================= .. currentmodule:: packaging.dependency_groups Package data as defined in ``pyproject.toml`` may include lists of dependencies in named groups. This is described by the :ref:`dependency groups specification `, which defines the ``[dependency-groups]`` table. This module provides tools for resolving group names to lists of requirements, most notably expanding ``include-group`` directives. Usage ----- Two primary interfaces are offered. An object-based one which caches results and provides ``Requirements`` as its results: .. doctest:: >>> from packaging.dependency_groups import DependencyGroupResolver >>> coverage = ["coverage"] >>> test = ["pytest", {"include-group": "coverage"}] >>> # A resolver is defined on a mapping of group names to group data, as >>> # you might get by loading the [dependency-groups] TOML table. >>> resolver = DependencyGroupResolver({"test": test, "coverage": coverage}) >>> # resolvers support expanding group names to Requirements >>> resolver.resolve("coverage") (,) >>> resolver.resolve("test") (, ) >>> # resolvers can also be used to lookup the dependency groups without >>> # expanding includes >>> resolver.lookup("test") (, DependencyGroupInclude('coverage')) And a simpler functional interface which responds with strings: .. doctest:: >>> from packaging.dependency_groups import resolve_dependency_groups >>> coverage = ["coverage"] >>> test = ["pytest", {"include-group": "coverage"}] >>> groups = {"test": test, "coverage": coverage} >>> resolve_dependency_groups(groups, "test") ('pytest', 'coverage') Reference --------- Functional Interface '''''''''''''''''''' .. autofunction:: resolve_dependency_groups Object Model Interface '''''''''''''''''''''' .. autoclass:: DependencyGroupInclude :members: .. autoclass:: DependencyGroupResolver :members: Exceptions '''''''''' .. autoclass:: DuplicateGroupNames :members: .. autoclass:: CyclicDependencyGroup :members: .. autoclass:: InvalidDependencyGroupObject :members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1046183 packaging-26.2/docs/development/getting-started.rst0000644000000000000000000000552315172742311017436 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 property-based tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The tests under ``tests/property/`` use `Hypothesis`_ and are gated by the ``property`` pytest marker. They are excluded from the default ``pytest`` run (and from ``nox -s tests``) so that downstream packagers and CI stay fast. To run them explicitly: .. code-block:: console $ python -m pytest -m property Or via `nox`_: .. code-block:: console $ nox -s property_tests 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 .. _`Hypothesis`: https://pypi.org/project/hypothesis/ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1048267 packaging-26.2/docs/development/index.rst0000644000000000000000000000103715172742311015434 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=1777059017.1048267 packaging-26.2/docs/development/release-process.rst0000644000000000000000000000312415172742311017420 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. You can get started with this:: $ gh api repos/pypa/packaging/releases/generate-notes \ -f tag_name=YY.N \ -f previous_tag_name=YY.(N-1) \ --jq .body #. 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 that is 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=1777059017.1048267 packaging-26.2/docs/development/reviewing-patches.rst0000644000000000000000000000176615172742311017762 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=1777059017.1048267 packaging-26.2/docs/development/submitting-patches.rst0000644000000000000000000000477115172742311020147 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=1777059017.1048267 packaging-26.2/docs/direct_url.rst0000644000000000000000000000361215172742311014140 0ustar00Direct URLs =========== .. currentmodule:: packaging.direct_url Parse and validate `direct_url.json files `_. Usage ----- .. code-block:: python import json from pathlib import Path from packaging.direct_url import ArchiveInfo, DirectUrl, DirInfo, VcsInfo # A VCS direct URL vcs_direct_url = DirectUrl( url="https://git.example.com/repo.git", vcs_info=VcsInfo( vcs="git", commit_id="2df7bdd8dfef7b879390b9fc4016f02af2f118d4", requested_revision="1.1.0", ), ) # An archive direct URL archive_direct_url = DirectUrl( url="https://example.com/archive.tar.gz", archive_info=ArchiveInfo( hashes={ "sha256": "dc321a1c18a37b5438424ef3714524229dab5f4f78b297671359426fef51be6c" } ), ) # A local editable direct URL archive_direct_url = DirectUrl( url="file:///home/project/example", dir_info=DirInfo( editable=True, ), ) # Serialization to JSON Path("/tmp/direct_url.json").write_text( json.dumps(vcs_direct_url.to_dict()), encoding="utf-8" ) # Load from JSON. The resulting DirectUrl object is validated against the # specification, else a DirectUrlValidationError is raised direct_url = DirectUrl.from_dict( json.loads(Path("/tmp/direct_url.json").read_text(encoding="utf-8")) ) # You can validate a manually constructed DirectUrl class vcs_direct_url.validate() Reference --------- .. autoclass:: DirectUrl :members: from_dict, to_dict, validate :exclude-members: __init__, __new__ .. class:: ArchiveInfo .. class:: DirInfo .. class:: VcsInfo The following exception may be raised by this module: .. autoexception:: DirectUrlValidationError :exclude-members: __init__, __new__ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1048267 packaging-26.2/docs/errors.rst0000644000000000000000000000232515172742311013320 0ustar00Errors ====== Error classes and error-handling helpers used by the packaging library. Currently this contains :class:`~packaging.errors.ExceptionGroup`, a simple backport of the stdlib :class:`ExceptionGroup`. It is recommended to use the stdlib module on Python 3.11+, but this does reexport that as well. Recommended Usage ----------------- .. code-block:: python if sys.version_info < (3, 11): from packaging.errors import ExceptionGroup try: ... except ExceptionGroup as err: for error in err.exceptions: ... Reference --------- .. This has to be listed here so building it on newer Python keeps the docs .. py:class:: packaging.errors.ExceptionGroup(message: str, exceptions: list[Exception]) On older Pythons, this is a small fallback implementation of the :class:`ExceptionGroup` introduced in Python 3.11. :param message: The message for the group. :param exceptions: A list of exceptions contained in the group. Attributes ---------- message (str) The message passed to the group. exceptions (list[Exception]) The exceptions contained in the group. .. automodule:: packaging.errors :members: :exclude-members: ExceptionGroup ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1048267 packaging-26.2/docs/index.rst0000644000000000000000000000124015172742311013106 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 direct_url dependency_groups errors utils .. toctree:: :maxdepth: 2 :caption: Project :hidden: development/index security changelog ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1048267 packaging-26.2/docs/licenses.rst0000644000000000000000000000050215172742311013604 0ustar00Licenses ========= .. currentmodule:: packaging.licenses Helper for canonicalizing SPDX `License-Expression metadata `__ as `defined in PEP 639 `__. Reference --------- .. automodule:: packaging.licenses :members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1048267 packaging-26.2/docs/markers.rst0000644000000000000000000000500015172742311013441 0ustar00Markers ======= 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 Combining markers programmatically ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :class:`Marker` objects support the ``&`` (and) and ``|`` (or) operators for combining markers without manually constructing marker strings: .. doctest:: >>> from packaging.markers import Marker >>> py3 = Marker("python_version >= '3'") >>> linux = Marker("sys_platform == 'linux'") >>> combined = py3 & linux >>> str(combined) 'python_version >= "3" and sys_platform == "linux"' >>> either = py3 | linux >>> str(either) 'python_version >= "3" or sys_platform == "linux"' This is equivalent to writing the combined marker string directly but is useful when building markers dynamically from separate conditions. .. versionadded:: 26.1 Reference --------- .. automodule:: packaging.markers :members: :special-members: __and__, __or__ :exclude-members: __init__ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1048267 packaging-26.2/docs/metadata.rst0000644000000000000000000000335315172742311013566 0ustar00Metadata ======== .. currentmodule:: packaging.metadata 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: :undoc-members: .. autofunction:: packaging.metadata.parse_email Exceptions '''''''''' .. autoclass:: packaging.metadata.InvalidMetadata :members: .. note:: ``packaging.metadata.ExceptionGroup`` is a backward-compatible re-export of :class:`packaging.errors.ExceptionGroup` and is omitted here to avoid duplicate documentation. See :mod:`packaging.errors` for the canonical documentation. .. _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=1777059017.1048267 packaging-26.2/docs/pylock.rst0000644000000000000000000000462315172742311013310 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() # select packages to install for the current environment for package, artifact in pylock.select(): print(f"Install {package.name} from {artifact}") 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, select :exclude-members: __init__, __new__ .. class:: Package .. class:: PackageWheel .. class:: PackageSdist .. class:: PackageArchive .. class:: PackageVcs .. class:: PackageDirectory The following exceptions may be raised by this module: .. autoexception:: PylockValidationError :exclude-members: __init__, __new__ .. autoexception:: PylockUnsupportedVersionError :exclude-members: __init__, __new__ .. autoexception:: PylockSelectError :exclude-members: __init__, __new__ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1048267 packaging-26.2/docs/requirements.rst0000644000000000000000000000700115172742311014523 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. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. :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=1777059017.1048267 packaging-26.2/docs/security.rst0000644000000000000000000000125515172742311013654 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=1777059017.1053567 packaging-26.2/docs/specifiers.rst0000644000000000000000000000437415172742311014146 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'] >>> # We can check if a specifier set can never be satisfied >>> SpecifierSet(">=2.0,<1.0").is_unsatisfiable() True >>> SpecifierSet(">=1.0,<2.0").is_unsatisfiable() False >>> # Compound sets built with ``&`` may also become unsatisfiable >>> (SpecifierSet(">=3.9,<4.0") & SpecifierSet("==3.12.*")).is_unsatisfiable() False >>> (SpecifierSet(">=3.13,<4.0") & SpecifierSet("==3.12.*")).is_unsatisfiable() True Reference --------- .. automodule:: packaging.specifiers :members: :special-members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1053567 packaging-26.2/docs/tags.rst0000644000000000000000000000511115172742311012736 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. .. autoclass:: Tag :members: .. autofunction:: parse_tag .. autofunction:: sys_tags .. autofunction:: create_compatible_tags_selector 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. .. autofunction:: interpreter_name .. autofunction:: interpreter_version .. autofunction:: mac_platforms .. autofunction:: ios_platforms .. autofunction:: android_platforms .. autofunction:: platform_tags .. autofunction:: compatible_tags .. autofunction:: cpython_tags .. autofunction:: generic_tags .. _`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=1777059017.1053567 packaging-26.2/docs/utils.rst0000644000000000000000000000023415172742311013141 0ustar00Utilities ========= A set of small, helper utilities for dealing with Python packages. Reference --------- .. automodule:: packaging.utils :members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1053567 packaging-26.2/docs/version.rst0000644000000000000000000000217415172742311013473 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=1777059017.1053567 packaging-26.2/pyproject.toml0000644000000000000000000001076415172742311013244 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", "Programming Language :: Python :: Free Threading :: 4 - Resilient", "Typing :: Typed", ] dependencies = [] [project.urls] Documentation = "https://packaging.pypa.io/" Source = "https://github.com/pypa/packaging" [dependency-groups] test = [ "coverage[toml]>=7.2.0", "hypothesis>=6.0.0", "pip>=21.1", "pretend", "pytest>=6.2.0", "tomli; python_version<'3.11'", "tomli_w", ] docs = [ "furo", "typing-extensions>=4.1.0; python_version < '3.9'", ] benchmark = [ "asv", "pip", ] dev = [ { include-group = "test" }, { include-group = "benchmark" }, ] [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:", "@(typing.)?overload", "def __dir__()", ] [tool.pytest.ini_options] minversion = "6.2" addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config", "-m", "not property"] xfail_strict = true filterwarnings = ["error"] log_level = "INFO" testpaths = ["tests"] markers = ["property: property-based tests (opt-in)"] [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/*.py" = ["T20"] "tasks/check.py" = ["UP032"] "tasks/check_frozen_revs.py" = ["ANN401"] "tests/test_requirements.py" = ["UP032"] "src/packaging/_musllinux.py" = ["T20"] "docs/conf.py" = ["INP001", "S", "A001"] "noxfile.py" = ["T20", "S"] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1059084 packaging-26.2/src/packaging/__init__.py0000644000000000000000000000075615172742311015154 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.2" __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=1777059017.1059685 packaging-26.2/src/packaging/_elffile.py0000644000000000000000000000621315172742311015154 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=1777059017.1059685 packaging-26.2/src/packaging/_manylinux.py0000644000000000000000000002252715172742311015600 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=1777059017.1059685 packaging-26.2/src/packaging/_musllinux.py0000644000000000000000000000522315172742311015606 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=1777059017.1059685 packaging-26.2/src/packaging/_parser.py0000644000000000000000000002666215172742311015054 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 def __getstate__(self) -> str: # Return just the value string for compactness and stability. return self.value def _restore_value(self, value: object) -> None: if not isinstance(value, str): raise TypeError( f"Cannot restore {self.__class__.__name__} value from {value!r}" ) self.value = value def __setstate__(self, state: object) -> None: if isinstance(state, str): # New format (26.2+): just the value string. self._restore_value(state) return if isinstance(state, tuple) and len(state) == 2: # Old format (packaging <= 26.0, __slots__): (None, {slot: value}). _, slot_dict = state if isinstance(slot_dict, dict) and "value" in slot_dict: self._restore_value(slot_dict["value"]) return if isinstance(state, dict) and "value" in state: # Old format (packaging <= 25.0, no __slots__): plain __dict__. self._restore_value(state["value"]) return raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}") class Variable(Node): __slots__ = () def serialize(self) -> str: return str(self) class Value(Node): __slots__ = () def serialize(self) -> str: 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=1777059017.1059685 packaging-26.2/src/packaging/_structures.py0000644000000000000000000000212515172742311015767 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. """Backward-compatibility shim for unpickling Version objects serialized before packaging 26.1. Old pickles reference ``packaging._structures.InfinityType`` and ``packaging._structures.NegativeInfinityType``. This module provides minimal stand-in classes so that ``pickle.loads()`` can resolve those references. The deserialized objects are not used for comparisons — ``Version.__setstate__`` discards the stale ``_key`` cache and recomputes it from the core version fields. """ from __future__ import annotations class InfinityType: """Stand-in for the removed ``InfinityType`` used in old comparison keys.""" def __repr__(self) -> str: return "Infinity" class NegativeInfinityType: """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys.""" def __repr__(self) -> str: return "-Infinity" Infinity = InfinityType() NegativeInfinity = NegativeInfinityType() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1059685 packaging-26.2/src/packaging/_tokenizer.py0000644000000000000000000001241715172742311015563 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._specifier_regex_str, re.VERBOSE | re.IGNORECASE, ), "AT": re.compile(r"\@"), "URL": re.compile(r"[^ \t]+"), "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), "WS": re.compile(r"[ \t]+"), "END": re.compile(r"$"), } 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=1777059017.1059685 packaging-26.2/src/packaging/dependency_groups.py0000644000000000000000000002375215172742311017133 0ustar00from __future__ import annotations import re from collections.abc import Mapping, Sequence from .errors import _ErrorCollector from .requirements import Requirement __all__ = [ "CyclicDependencyGroup", "DependencyGroupInclude", "DependencyGroupResolver", "DuplicateGroupNames", "InvalidDependencyGroupObject", "resolve_dependency_groups", ] def __dir__() -> list[str]: return __all__ # ----------- # Error Types # ----------- class DuplicateGroupNames(ValueError): """ The same dependency groups were defined twice, with different non-normalized names. """ class CyclicDependencyGroup(ValueError): """ The dependency group includes form a cycle. """ def __init__(self, requested_group: str, group: str, include_group: str) -> None: self.requested_group = requested_group self.group = group self.include_group = include_group if include_group == group: reason = f"{group} includes itself" else: reason = f"{include_group} -> {group}, {group} -> {include_group}" super().__init__( "Cyclic dependency group include while resolving " f"{requested_group}: {reason}" ) # in the PEP 735 spec, the tables in dependency group lists were described as # "Dependency Object Specifiers", but the only defined type of object was a # "Dependency Group Include" -- hence the naming of this error as "Object" class InvalidDependencyGroupObject(ValueError): """ A member of a dependency group was identified as a dict, but was not in a valid format. """ # ------------------------ # Object Model & Interface # ------------------------ class DependencyGroupInclude: __slots__ = ("include_group",) def __init__(self, include_group: str) -> None: """ Initialize a DependencyGroupInclude. :param include_group: The name of the group referred to by this include. """ self.include_group = include_group def __repr__(self) -> str: return f"{self.__class__.__name__}({self.include_group!r})" class DependencyGroupResolver: """ A resolver for Dependency Group data. This class handles caching, name normalization, cycle detection, and other parsing requirements. There are only two public methods for exploring the data: ``lookup()`` and ``resolve()``. :param dependency_groups: A mapping, as provided via pyproject ``[dependency-groups]``. """ def __init__( self, dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], ) -> None: errors = _ErrorCollector() self.dependency_groups = _normalize_group_names(dependency_groups, errors) # a map of group names to parsed data self._parsed_groups: dict[ str, tuple[Requirement | DependencyGroupInclude, ...] ] = {} # a map of group names to their ancestors, used for cycle detection self._include_graph_ancestors: dict[str, tuple[str, ...]] = {} # a cache of completed resolutions to Requirement lists self._resolve_cache: dict[str, tuple[Requirement, ...]] = {} errors.finalize("[dependency-groups] data was invalid") def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]: """ Lookup a group name, returning the parsed dependency data for that group. This will not resolve includes. :param group: the name of the group to lookup """ group = _normalize_name(group) with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._parse_group(group, errors) def resolve(self, group: str) -> tuple[Requirement, ...]: """ Resolve a dependency group to a list of requirements. :param group: the name of the group to resolve """ group = _normalize_name(group) with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._resolve(group, group, errors) def _resolve( self, group: str, requested_group: str, errors: _ErrorCollector ) -> tuple[Requirement, ...]: """ This is a helper for cached resolution to strings. It preserves the name of the group which the user initially requested in order to present a clearer error in the event that a cycle is detected. :param group: The normalized name of the group to resolve. :param requested_group: The group which was used in the original, user-facing request. """ if group in self._resolve_cache: return self._resolve_cache[group] parsed = self._parse_group(group, errors) resolved_group = [] for item in parsed: if isinstance(item, Requirement): resolved_group.append(item) elif isinstance(item, DependencyGroupInclude): include_group = _normalize_name(item.include_group) # if a group is cyclic, record the error # otherwise, follow the include_group reference # # this allows us to examine all includes in a group, even in the # presence of errors if include_group in self._include_graph_ancestors.get(group, ()): errors.error( CyclicDependencyGroup( requested_group, group, item.include_group ) ) else: self._include_graph_ancestors[include_group] = ( *self._include_graph_ancestors.get(group, ()), group, ) resolved_group.extend( self._resolve(include_group, requested_group, errors) ) else: # pragma: no cover raise NotImplementedError( f"Invalid dependency group item after parse: {item}" ) # in the event that errors were detected, present the group as empty and do not # cache the result # this ensures that repeated access to a cyclic group will raise multiple errors if errors.errors: return () self._resolve_cache[group] = tuple(resolved_group) return self._resolve_cache[group] def _parse_group( self, group: str, errors: _ErrorCollector ) -> tuple[Requirement | DependencyGroupInclude, ...]: # short circuit -- never do the work twice if group in self._parsed_groups: return self._parsed_groups[group] if group not in self.dependency_groups: errors.error(LookupError(f"Dependency group '{group}' not found")) return () raw_group = self.dependency_groups[group] if isinstance(raw_group, str): errors.error( TypeError( f"Dependency group {group!r} contained a string rather than a list." ) ) return () if not isinstance(raw_group, Sequence): errors.error( TypeError(f"Dependency group {group!r} is not a sequence type.") ) return () elements: list[Requirement | DependencyGroupInclude] = [] for item in raw_group: if isinstance(item, str): # packaging.requirements.Requirement parsing ensures that this is a # valid PEP 508 Dependency Specifier # raises InvalidRequirement on failure elements.append(Requirement(item)) elif isinstance(item, Mapping): if tuple(item.keys()) != ("include-group",): errors.error( InvalidDependencyGroupObject( f"Invalid dependency group item: {item!r}" ) ) else: include_group = item["include-group"] elements.append(DependencyGroupInclude(include_group=include_group)) else: errors.error(TypeError(f"Invalid dependency group item: {item!r}")) self._parsed_groups[group] = tuple(elements) return self._parsed_groups[group] # -------------------- # Functional Interface # -------------------- def resolve_dependency_groups( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str ) -> tuple[str, ...]: """ Resolve a dependency group to a tuple of requirements, as strings. :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table from ``pyproject.toml`` :param groups: the name of the group(s) to resolve """ resolver = DependencyGroupResolver(dependency_groups) return tuple(str(r) for group in groups for r in resolver.resolve(group)) # ---------------- # internal helpers # ---------------- _NORMALIZE_PATTERN = re.compile(r"[-_.]+") def _normalize_name(name: str) -> str: return _NORMALIZE_PATTERN.sub("-", name).lower() def _normalize_group_names( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], errors: _ErrorCollector, ) -> dict[str, Sequence[str | Mapping[str, str]]]: original_names: dict[str, list[str]] = {} normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {} for group_name, value in dependency_groups.items(): normed_group_name = _normalize_name(group_name) original_names.setdefault(normed_group_name, []).append(group_name) normalized_groups[normed_group_name] = value for normed_name, names in original_names.items(): if len(names) > 1: errors.error( DuplicateGroupNames( "Duplicate dependency group names: " f"{normed_name} ({', '.join(names)})" ) ) return normalized_groups ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1063566 packaging-26.2/src/packaging/direct_url.py0000644000000000000000000002524515172742311015551 0ustar00from __future__ import annotations import dataclasses import re import urllib.parse from collections.abc import Mapping from typing import TYPE_CHECKING, Any, Protocol, TypeVar if TYPE_CHECKING: # pragma: no cover import sys from collections.abc import Collection if sys.version_info >= (3, 11): from typing import Self else: from typing_extensions import Self __all__ = [ "ArchiveInfo", "DirInfo", "DirectUrl", "DirectUrlValidationError", "VcsInfo", ] def __dir__() -> list[str]: return __all__ _T = TypeVar("_T") class _FromMappingProtocol(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) def _json_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return {key: value for key, value in data if value is not None} def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type): raise DirectUrlValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _DirectUrlRequiredKeyError(key) return value def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str ) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise DirectUrlValidationError(e, context=key) from e _PEP610_USER_PASS_ENV_VARS_REGEX = re.compile( r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$" ) def _strip_auth_from_netloc(netloc: str, safe_user_passwords: Collection[str]) -> str: if "@" not in netloc: return netloc user_pass, netloc_no_user_pass = netloc.split("@", 1) if user_pass in safe_user_passwords: return netloc if _PEP610_USER_PASS_ENV_VARS_REGEX.match(user_pass): return netloc return netloc_no_user_pass def _strip_url(url: str, safe_user_passwords: Collection[str]) -> str: """url with user:password part removed unless it is formed with environment variables as specified in PEP 610, or it is a safe user:password such as `git`. """ parsed_url = urllib.parse.urlsplit(url) netloc = _strip_auth_from_netloc(parsed_url.netloc, safe_user_passwords) return urllib.parse.urlunsplit( ( parsed_url.scheme, netloc, parsed_url.path, parsed_url.query, parsed_url.fragment, ) ) class DirectUrlValidationError(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, DirectUrlValidationError): if cause.context: self.context = ( f"{context}.{cause.context}" if context else cause.context ) else: self.context = context # pragma: no cover self.message = cause.message else: self.context = context self.message = str(cause) def __str__(self) -> str: if self.context: return f"{self.message} in {self.context!r}" return self.message class _DirectUrlRequiredKeyError(DirectUrlValidationError): def __init__(self, key: str) -> None: super().__init__("Missing required value", context=key) @dataclasses.dataclass(frozen=True, init=False) class VcsInfo: vcs: str commit_id: str requested_revision: str | None = None def __init__( self, *, vcs: str, commit_id: str, requested_revision: str | None = None, ) -> None: object.__setattr__(self, "vcs", vcs) object.__setattr__(self, "commit_id", commit_id) object.__setattr__(self, "requested_revision", requested_revision) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: # We can't validate vcs value because is not closed. return cls( vcs=_get_required(d, str, "vcs"), requested_revision=_get(d, str, "requested_revision"), commit_id=_get_required(d, str, "commit_id"), ) @dataclasses.dataclass(frozen=True, init=False) class ArchiveInfo: hashes: Mapping[str, str] | None = None def __init__( self, *, hashes: Mapping[str, str] | None = None, ) -> None: object.__setattr__(self, "hashes", hashes) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: hashes = _get(d, Mapping, "hashes") # type: ignore[type-abstract] if hashes is not None and not all(isinstance(h, str) for h in hashes.values()): raise DirectUrlValidationError( "Hash values must be strings", context="hashes" ) legacy_hash = _get(d, str, "hash") if legacy_hash is not None: if "=" not in legacy_hash: raise DirectUrlValidationError( "Invalid hash format (expected '=')", context="hash", ) hash_algorithm, hash_value = legacy_hash.split("=", 1) if hashes is None: # if `hashes` are not present, we can derive it from the legacy `hash` hashes = {hash_algorithm: hash_value} else: # if `hashes` are present, the legacy `hash` must match one of them if hash_algorithm not in hashes: raise DirectUrlValidationError( f"Algorithm {hash_algorithm!r} used in hash field " f"is not present in hashes field", context="hashes", ) if hashes[hash_algorithm] != hash_value: raise DirectUrlValidationError( f"Algorithm {hash_algorithm!r} used in hash field " f"has different value in hashes field", context="hash", ) return cls(hashes=hashes) @dataclasses.dataclass(frozen=True, init=False) class DirInfo: editable: bool | None = None def __init__( self, *, editable: bool | None = None, ) -> None: object.__setattr__(self, "editable", editable) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: return cls( editable=_get(d, bool, "editable"), ) @dataclasses.dataclass(frozen=True, init=False) class DirectUrl: """A class representing a direct URL.""" url: str archive_info: ArchiveInfo | None = None vcs_info: VcsInfo | None = None dir_info: DirInfo | None = None subdirectory: str | None = None # XXX Path or str? def __init__( self, *, url: str, archive_info: ArchiveInfo | None = None, vcs_info: VcsInfo | None = None, dir_info: DirInfo | None = None, subdirectory: str | None = None, ) -> None: object.__setattr__(self, "url", url) object.__setattr__(self, "archive_info", archive_info) object.__setattr__(self, "vcs_info", vcs_info) object.__setattr__(self, "dir_info", dir_info) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: direct_url = cls( url=_get_required(d, str, "url"), archive_info=_get_object(d, ArchiveInfo, "archive_info"), vcs_info=_get_object(d, VcsInfo, "vcs_info"), dir_info=_get_object(d, DirInfo, "dir_info"), subdirectory=_get(d, str, "subdirectory"), ) if ( bool(direct_url.vcs_info) + bool(direct_url.archive_info) + bool(direct_url.dir_info) ) != 1: raise DirectUrlValidationError( "Exactly one of vcs_info, archive_info, dir_info must be present" ) if direct_url.dir_info is not None and not direct_url.url.startswith("file://"): raise DirectUrlValidationError( "URL scheme must be file:// when dir_info is present", context="url", ) # XXX subdirectory must be relative, can we, should we validate that here? return direct_url @classmethod def from_dict(cls, d: Mapping[str, Any], /) -> Self: """Create and validate a DirectUrl instance from a JSON dictionary.""" return cls._from_dict(d) def to_dict( self, *, generate_legacy_hash: bool = False, strip_user_password: bool = True, safe_user_passwords: Collection[str] = ("git",), ) -> Mapping[str, Any]: """Convert the DirectUrl instance to a JSON dictionary. :param generate_legacy_hash: If True, include a legacy `hash` field in `archive_info` for backward compatibility with tools that don't support the `hashes` field. :param strip_user_password: If True, strip user:password from the URL unless it is formed with environment variables as specified in PEP 610, or it is a safe user:password such as `git`. :param safe_user_passwords: A collection of user:password strings that should not be stripped from the URL even if `strip_user_password` is True. """ res = dataclasses.asdict(self, dict_factory=_json_dict_factory) if generate_legacy_hash and self.archive_info and self.archive_info.hashes: hash_algorithm, hash_value = next(iter(self.archive_info.hashes.items())) res["archive_info"]["hash"] = f"{hash_algorithm}={hash_value}" if strip_user_password: res["url"] = _strip_url(self.url, safe_user_passwords) return res def validate(self) -> None: """Validate the DirectUrl instance against the specification. Raises :class:`DirectUrlValidationError` if invalid. """ self.from_dict(self.to_dict()) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1063566 packaging-26.2/src/packaging/errors.py0000644000000000000000000000517015172742311014724 0ustar00from __future__ import annotations import contextlib import dataclasses import sys import typing __all__ = ["ExceptionGroup"] def __dir__() -> list[str]: return __all__ if sys.version_info >= (3, 11): # pragma: no cover from builtins import ExceptionGroup 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})" @dataclasses.dataclass class _ErrorCollector: """ Collect errors into ExceptionGroups. Used like this: collector = _ErrorCollector() # Add a single exception collector.error(ValueError("one")) # Supports nesting, including combining ExceptionGroups with collector.collect(): raise ValueError("two") collector.finalize("Found some errors") Since making a collector and then calling finalize later is a common pattern, a convenience method ``on_exit`` is provided. """ errors: list[Exception] = dataclasses.field(default_factory=list, init=False) def finalize(self, msg: str) -> None: """Raise a group exception if there are any errors.""" if self.errors: raise ExceptionGroup(msg, self.errors) @contextlib.contextmanager def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]: """ Calls finalize if no uncollected errors were present. Uncollected errors are raised normally. """ yield self self.finalize(msg) @contextlib.contextmanager def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]: """ Context manager to collect errors into the error list. Must be inside loops, as only one error can be collected at a time. """ error_classes = err_cls or (Exception,) try: yield except ExceptionGroup as error: self.errors.extend(error.exceptions) except error_classes as error: self.errors.append(error) def error( self, error: Exception, ) -> None: """Add an error to the list.""" self.errors.append(error) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1063566 packaging-26.2/src/packaging/licenses/__init__.py0000644000000000000000000001617515172742311016763 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", ] # Simple __dir__ implementation since there are no public submodules def __dir__() -> list[str]: return __all__ license_ref_allowed = re.compile("^[A-Za-z0-9.-]*$") NormalizedLicenseExpression = NewType("NormalizedLicenseExpression", str) """ A :class:`typing.NewType` of :class:`str`, representing a normalized License-Expression. """ class InvalidLicenseExpression(ValueError): """Raised when a license-expression string is invalid >>> from packaging.licenses import canonicalize_license_expression >>> canonicalize_license_expression("invalid") Traceback (most recent call last): ... packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid' """ def canonicalize_license_expression( raw_license_expression: str, ) -> NormalizedLicenseExpression: """ This function takes a valid License-Expression, and returns the normalized form of it. The return type is typed as :class:`NormalizedLicenseExpression`. This allows type checkers to help require that a string has passed through this function before use. :param str raw_license_expression: The License-Expression to canonicalize. :raises InvalidLicenseExpression: If the License-Expression is invalid due to an invalid/unknown license identifier or invalid syntax. .. doctest:: >>> from packaging.licenses import canonicalize_license_expression >>> canonicalize_license_expression("mit") 'MIT' >>> canonicalize_license_expression("mit and (apache-2.0 or bsd-2-clause)") 'MIT AND (Apache-2.0 OR BSD-2-Clause)' >>> canonicalize_license_expression("(mit") Traceback (most recent call last): ... InvalidLicenseExpression: Invalid license expression: '(mit' >>> canonicalize_license_expression("Use-it-after-midnight") Traceback (most recent call last): ... InvalidLicenseExpression: Unknown license: 'Use-it-after-midnight' """ if not raw_license_expression: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) # Pad any parentheses so tokenization can be achieved by merely splitting on # whitespace. license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ") licenseref_prefix = "LicenseRef-" license_refs = { ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :] for ref in license_expression.split() if ref.lower().startswith(licenseref_prefix.lower()) } # Normalize to lower case so we can look up licenses/exceptions # and so boolean operators are Python-compatible. license_expression = license_expression.lower() tokens = license_expression.split() # Rather than implementing a parenthesis/boolean logic parser, create an # expression that Python can parse. Everything that is not involved with the # grammar itself is replaced with the placeholder `False` and the resultant # expression should become a valid Python expression. python_tokens = [] for token in tokens: if token not in {"or", "and", "with", "(", ")"}: python_tokens.append("False") elif token == "with": python_tokens.append("or") elif ( token == "(" and python_tokens and python_tokens[-1] not in {"or", "and", "("} ) or (token == ")" and python_tokens and python_tokens[-1] == "("): message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) else: python_tokens.append(token) python_expression = " ".join(python_tokens) try: compile(python_expression, "", "eval") except SyntaxError: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) from None # Take a final pass to check for unknown licenses/exceptions. normalized_tokens = [] 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=1777059017.1066914 packaging-26.2/src/packaging/licenses/_spdx.py0000644000000000000000000014366215172742311016343 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=1777059017.1066914 packaging-26.2/src/packaging/markers.py0000644000000000000000000004123715172742311015060 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", ] def __dir__() -> list[str]: return __all__ Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] EvaluateContext = Literal["metadata", "lock_file", "requirement"] """A ``typing.Literal`` enumerating valid marker evaluation contexts. Valid values for the ``context`` passed to :meth:`Marker.evaluate` are: * ``"metadata"`` (for core metadata; default) * ``"lock_file"`` (for lock files) * ``"requirement"`` (i.e. all other situations) """ MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} MARKERS_REQUIRING_VERSION = { "implementation_version", "platform_release", "python_full_version", "python_version", } class InvalidMarker(ValueError): """Raised when attempting to create a :class:`Marker` from invalid input. This error indicates that the given marker string does not conform to the :ref:`specification of dependency specifiers `. """ class UndefinedComparison(ValueError): """Raised when evaluating an unsupported marker comparison. This can happen when marker values are compared as versions but do not conform to the :ref:`specification of version specifiers `. """ class UndefinedEnvironmentName(ValueError): """Raised when evaluating a marker that references a missing environment key.""" class Environment(TypedDict): """ A dictionary that represents a Python environment as captured by :func:`default_environment`. All fields are required. """ implementation_name: str """The implementation's identifier, e.g. ``'cpython'``.""" implementation_version: str """ The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or ``'7.3.13'`` for PyPy3.10 v7.3.13. """ os_name: str """ The value of :py:data:`os.name`. The name of the operating system dependent module imported, e.g. ``'posix'``. """ platform_machine: str """ Returns the machine type, e.g. ``'i386'``. An empty string if the value cannot be determined. """ platform_release: str """ The system's release, e.g. ``'2.2.0'`` or ``'NT'``. An empty string if the value cannot be determined. """ platform_system: str """ The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. An empty string if the value cannot be determined. """ platform_version: str """ The system's release version, e.g. ``'#3 on degas'``. An empty string if the value cannot be determined. """ python_full_version: str """ The Python version as string ``'major.minor.patchlevel'``. Note that unlike the Python :py:data:`sys.version`, this value will always include the patchlevel (it defaults to 0). """ platform_python_implementation: str """ A string identifying the Python implementation, e.g. ``'CPython'``. """ python_version: str """The Python version as string ``'major.minor'``.""" sys_platform: str """ This string contains a platform identifier that can be used to append platform-specific components to :py:data:`sys.path`, for instance. For Unix systems, except on Linux and AIX, this is the lowercased OS name as returned by ``uname -s`` with the first part of the version as returned by ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python was built. """ def _normalize_extras( result: MarkerList | MarkerAtom | str, ) -> MarkerList | MarkerAtom | str: if 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: """Return the default marker environment for the current Python process. This is the base environment used by :meth:`Marker.evaluate`. """ 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: """Represents a parsed dependency marker expression. Marker expressions are parsed according to the :ref:`specification of dependency specifiers `. :param marker: The string representation of a marker expression. :raises InvalidMarker: If ``marker`` cannot be parsed. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ __slots__ = ("_markers",) def __init__(self, marker: str) -> None: # Note: We create a Marker object without calling this constructor in # packaging.requirements.Requirement. If any additional logic is # added here, make sure to mirror/adapt Requirement. # If this fails and throws an error, the repr still expects _markers to # be defined. self._markers: MarkerList = [] try: self._markers = _normalize_extra_values(_parse_marker(marker)) # The attribute `_markers` can be described in terms of a recursive type: # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] # # For example, the following expression: # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") # # is parsed into: # [ # (, ')>, ), # 'and', # [ # (, , ), # 'or', # (, , ) # ] # ] except ParserSyntaxError as e: raise InvalidMarker(str(e)) from e @classmethod def _from_markers(cls, markers: MarkerList) -> Marker: """Create a Marker instance from a pre-parsed marker tree. This avoids re-parsing serialised marker strings when combining markers. """ new = cls.__new__(cls) new._markers = markers return new def __str__(self) -> str: return _format_marker(self._markers) def __repr__(self) -> str: return f"<{self.__class__.__name__}({str(self)!r})>" def __hash__(self) -> int: return hash(str(self)) def __eq__(self, other: object) -> bool: if not isinstance(other, Marker): return NotImplemented return str(self) == str(other) def __getstate__(self) -> str: # Return the marker expression string for compactness and stability. # Internal Node objects are excluded; the string is re-parsed on load. return str(self) def __setstate__(self, state: object) -> None: if isinstance(state, str): # New format (26.2+): just the marker expression string. try: self._markers = _normalize_extra_values(_parse_marker(state)) except ParserSyntaxError as exc: raise TypeError(f"Cannot restore Marker from {state!r}") from exc return if isinstance(state, dict) and "_markers" in state: # Old format (packaging <= 26.1, no __slots__): plain __dict__. markers = state["_markers"] if isinstance(markers, list): self._markers = markers return if isinstance(state, tuple) and len(state) == 2: # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). _, slot_dict = state if isinstance(slot_dict, dict) and "_markers" in slot_dict: markers = slot_dict["_markers"] if isinstance(markers, list): self._markers = markers return raise TypeError(f"Cannot restore Marker from {state!r}") def __and__(self, other: Marker) -> Marker: if not isinstance(other, Marker): return NotImplemented return self._from_markers([self._markers, "and", other._markers]) def __or__(self, other: Marker) -> Marker: if not isinstance(other, Marker): return NotImplemented return self._from_markers([self._markers, "or", other._markers]) def evaluate( self, environment: Mapping[str, str | AbstractSet[str]] | None = None, context: EvaluateContext = "metadata", ) -> bool: """Evaluate a marker. Return the boolean from evaluating this marker against the environment. The environment is determined from the current Python process unless passed in explicitly. :param environment: Mapping containing keys and values to override the detected environment. :param EvaluateContext context: The context in which the marker is evaluated, which influences what marker names are considered valid. Accepted values are ``"metadata"`` (for core metadata; default), ``"lock_file"``, and ``"requirement"`` (i.e. all other situations). :raises UndefinedComparison: If the marker uses a comparison on values that are not valid versions per the :ref:`specification of version specifiers `. :raises UndefinedEnvironmentName: If the marker references a value that is missing from the evaluation environment. :returns: ``True`` if the marker matches, otherwise ``False``. """ 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=1777059017.1066914 packaging-26.2/src/packaging/metadata.py0000644000000000000000000011356215172742311015175 0ustar00from __future__ import annotations import email.header import email.message import email.parser import email.policy import keyword import pathlib import typing from typing import ( Any, Callable, Generic, Literal, TypedDict, cast, ) from . import licenses, requirements, specifiers, utils from . import version as version_module from .errors import ExceptionGroup, _ErrorCollector if typing.TYPE_CHECKING: from .licenses import NormalizedLicenseExpression T = typing.TypeVar("T") __all__ = [ "ExceptionGroup", # Keep this for a bit (makes mypy happy w/ 26.0 compat) "InvalidMetadata", "Metadata", "RFC822Message", "RFC822Policy", "RawMetadata", "parse_email", ] def __dir__() -> list[str]: return __all__ class InvalidMetadata(ValueError): """A metadata field contains invalid data.""" 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. All fields are considered optional. """ # Metadata 1.0 - PEP 241 metadata_version: str name: str version: str platforms: list[str] summary: str description: str keywords: list[str] home_page: str author: str author_email: str license: str # Metadata 1.1 - PEP 314 supported_platforms: list[str] download_url: str classifiers: list[str] requires: list[str] provides: list[str] obsoletes: list[str] # Metadata 1.2 - PEP 345 maintainer: str maintainer_email: str requires_dist: list[str] provides_dist: list[str] obsoletes_dist: list[str] requires_python: str requires_external: list[str] project_urls: dict[str, str] # Metadata 2.0 # PEP 426 attempted to completely revamp the metadata format # but got stuck without ever being able to build consensus on # it and ultimately ended up withdrawn. # # However, a number of tools had started emitting METADATA with # `2.0` Metadata-Version, so for historical reasons, this version # was skipped. # Metadata 2.1 - PEP 566 description_content_type: str provides_extra: list[str] # Metadata 2.2 - PEP 643 dynamic: list[str] # Metadata 2.3 - PEP 685 # No new fields were added in PEP 685, just some edge case were # tightened up to provide better interoperability. # Metadata 2.4 - PEP 639 license_expression: str 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 {charset!r}" ) markdown_variants = {"GFM", "CommonMark"} variant = parameters.get("variant", "GFM") # Use an acceptable default. if content_type == "text/markdown" and variant not in markdown_variants: raise self._invalid_metadata( f"valid Markdown variants for {{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: collector = _ErrorCollector() metadata_version = None with collector.collect(InvalidMetadata): metadata_version = ins.metadata_version metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) # Make sure to check for the fields that are present, the required # fields (so their absence can be reported). fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS # Remove fields that have already been checked. fields_to_check -= {"metadata_version"} for key in fields_to_check: try: if metadata_version: # Can't use getattr() as that triggers descriptor protocol which # will fail due to no value for the instance argument. try: field_metadata_version = cls.__dict__[key].added except KeyError: exc = InvalidMetadata(key, f"unrecognized field: {key!r}") collector.error(exc) continue field_age = _VALID_METADATA_VERSIONS.index( field_metadata_version ) if field_age > metadata_age: field = _RAW_TO_EMAIL_MAPPING[key] exc = InvalidMetadata( field, f"{field} introduced in metadata version " f"{field_metadata_version}, not {metadata_version}", ) collector.error(exc) continue getattr(ins, key) except InvalidMetadata as exc: collector.error(exc) collector.finalize("invalid metadata") return ins @classmethod def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: """Parse metadata from email headers. If *validate* is true, the metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ raw, unparsed = parse_email(data) if validate: with _ErrorCollector().on_exit("unparsed") as collector: for unparsed_key in unparsed: if unparsed_key in _EMAIL_TO_RAW_MAPPING: message = f"{unparsed_key!r} has invalid data" else: message = f"unrecognized field: {unparsed_key!r}" collector.error(InvalidMetadata(unparsed_key, message)) try: 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=1777059017.1066914 packaging-26.2/src/packaging/py.typed0000644000000000000000000000000015172742311014520 0ustar00././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1073568 packaging-26.2/src/packaging/pylock.py0000644000000000000000000010214215172742311014706 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, cast, ) from urllib.parse import urlparse from .markers import Environment, Marker, default_environment from .specifiers import SpecifierSet from .tags import create_compatible_tags_selector, sys_tags from .utils import ( NormalizedName, is_normalized_name, parse_sdist_filename, parse_wheel_filename, ) from .version import Version if TYPE_CHECKING: # pragma: no cover from collections.abc import Collection, Iterator from pathlib import Path from typing_extensions import Self from .tags import Tag _logger = logging.getLogger(__name__) __all__ = [ "Package", "PackageArchive", "PackageDirectory", "PackageSdist", "PackageVcs", "PackageWheel", "Pylock", "PylockUnsupportedVersionError", "PylockValidationError", "is_valid_pylock_path", ] def __dir__() -> list[str]: return __all__ _T = TypeVar("_T") _T2 = TypeVar("_T2") class _FromMappingProtocol(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) _PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$") def is_valid_pylock_path(path: Path) -> bool: """Check if the given path is a valid pylock file path.""" return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name)) def _toml_key(key: str) -> str: return key.replace("_", "-") def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 if isinstance(value, (Version, Marker, SpecifierSet)): return str(value) if isinstance(value, Sequence) and key == "environments": return [str(v) for v in value] return value def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return { _toml_key(key): _toml_value(key, value) for key, value in data if value is not None } def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type): raise PylockValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _PylockRequiredKeyError(key) return value def _get_sequence( d: Mapping[str, Any], expected_item_type: type[_T], key: str ) -> Sequence[_T] | None: """Get a list value from the dictionary and verify it's the expected items type.""" if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] return None if isinstance(value, (str, bytes)): # special case: str and bytes are Sequences, but we want to reject it raise PylockValidationError( f"Unexpected type {type(value).__name__} (expected Sequence)", context=key, ) for i, item in enumerate(value): if not isinstance(item, expected_item_type): raise PylockValidationError( f"Unexpected type {type(item).__name__} " f"(expected {expected_item_type.__name__})", context=f"{key}[{i}]", ) return value def _get_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str, ) -> _T2 | None: """Get a value from the dictionary, verify it's the expected type, and convert to the target type. This assumes the target_type constructor accepts the value. """ if (value := _get(d, expected_type, key)) is None: return None try: return target_type(value) except Exception as e: raise PylockValidationError(e, context=key) from e def _get_required_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str, ) -> _T2: """Get a required value from the dict, verify it's the expected type, and convert to the target type.""" if (value := _get_as(d, expected_type, target_type, key)) is None: raise _PylockRequiredKeyError(key) return value def _get_sequence_as( d: Mapping[str, Any], expected_item_type: type[_T], target_item_type: Callable[[_T], _T2], key: str, ) -> list[_T2] | None: """Get list value from dictionary and verify expected items type.""" if (value := _get_sequence(d, expected_item_type, key)) is None: return None result = [] try: for item in value: typed_item = target_item_type(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str ) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise PylockValidationError(e, context=key) from e def _get_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str ) -> list[_FromMappingProtocolT] | None: """Get a list value from the dictionary and convert its items to a dataclass.""" if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] return None result: list[_FromMappingProtocolT] = [] try: for item in value: typed_item = target_item_type._from_dict(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result def _get_required_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str ) -> Sequence[_FromMappingProtocolT]: """Get a required list value from the dictionary and convert its items to a dataclass.""" if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: raise _PylockRequiredKeyError(key) return result def _validate_normalized_name(name: str) -> NormalizedName: """Validate that a string is a NormalizedName.""" if not is_normalized_name(name): raise PylockValidationError(f"Name {name!r} is not normalized") return NormalizedName(name) def _validate_path_url(path: str | None, url: str | None) -> None: if not path and not url: raise PylockValidationError("path or url must be provided") def _path_name(path: str | None) -> str | None: if not path: return None # If the path is relative it MAY use POSIX-style path separators explicitly # for portability if "/" in path: return path.rsplit("/", 1)[-1] elif "\\" in path: return path.rsplit("\\", 1)[-1] else: return path def _url_name(url: str | None) -> str | None: if not url: return None url_path = urlparse(url).path return url_path.rsplit("/", 1)[-1] def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: if not hashes: raise PylockValidationError("At least one hash must be provided") if not all(isinstance(hash_val, str) for hash_val in hashes.values()): raise PylockValidationError("Hash values must be strings") return hashes class PylockValidationError(Exception): """Raised when when input data is not spec-compliant.""" context: str | None = None message: str def __init__( self, cause: str | Exception, *, context: str | None = None, ) -> None: if isinstance(cause, PylockValidationError): if cause.context: self.context = ( f"{context}.{cause.context}" if context else cause.context ) else: self.context = context self.message = cause.message else: self.context = context self.message = str(cause) def __str__(self) -> str: if self.context: return f"{self.message} in {self.context!r}" return self.message class _PylockRequiredKeyError(PylockValidationError): def __init__(self, key: str) -> None: super().__init__("Missing required value", context=key) class PylockUnsupportedVersionError(PylockValidationError): """Raised when encountering an unsupported `lock_version`.""" class PylockSelectError(Exception): """Base exception for errors raised by :meth:`Pylock.select`.""" @dataclass(frozen=True, init=False) class PackageVcs: type: str url: str | None = None path: str | None = None requested_revision: str | None = None commit_id: str # type: ignore[misc] subdirectory: str | None = None def __init__( self, *, type: str, url: str | None = None, path: str | None = None, requested_revision: str | None = None, commit_id: str, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "type", type) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "requested_revision", requested_revision) object.__setattr__(self, "commit_id", commit_id) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_vcs = cls( type=_get_required(d, str, "type"), url=_get(d, str, "url"), path=_get(d, str, "path"), requested_revision=_get(d, str, "requested-revision"), commit_id=_get_required(d, str, "commit-id"), subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_vcs.path, package_vcs.url) return package_vcs @dataclass(frozen=True, init=False) class PackageDirectory: path: str editable: bool | None = None subdirectory: str | None = None def __init__( self, *, path: str, editable: bool | None = None, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "path", path) object.__setattr__(self, "editable", editable) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: return cls( path=_get_required(d, str, "path"), editable=_get(d, bool, "editable"), subdirectory=_get(d, str, "subdirectory"), ) @dataclass(frozen=True, init=False) class PackageArchive: url: str | None = None path: str | None = None size: int | None = None upload_time: datetime | None = None hashes: Mapping[str, str] # type: ignore[misc] subdirectory: str | None = None def __init__( self, *, url: str | None = None, path: str | None = None, size: int | None = None, upload_time: datetime | None = None, hashes: Mapping[str, str], subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "hashes", hashes) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_archive = cls( url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), upload_time=_get(d, datetime, "upload-time"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_archive.path, package_archive.url) return package_archive @dataclass(frozen=True, init=False) class PackageSdist: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc] def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_sdist = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_sdist.path, package_sdist.url) return package_sdist @property def filename(self) -> str: """Get the filename of the sdist.""" filename = self.name or _path_name(self.path) or _url_name(self.url) if not filename: raise PylockValidationError("Cannot determine sdist filename") return filename @dataclass(frozen=True, init=False) class PackageWheel: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc] def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_wheel = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_wheel.path, package_wheel.url) return package_wheel @property def filename(self) -> str: """Get the filename of the wheel.""" filename = self.name or _path_name(self.path) or _url_name(self.url) if not filename: raise PylockValidationError("Cannot determine wheel filename") return filename @dataclass(frozen=True, init=False) class Package: name: NormalizedName version: Version | None = None marker: Marker | None = None requires_python: SpecifierSet | None = None dependencies: Sequence[Mapping[str, Any]] | None = None vcs: PackageVcs | None = None directory: PackageDirectory | None = None archive: PackageArchive | None = None index: str | None = None sdist: PackageSdist | None = None wheels: Sequence[PackageWheel] | None = None attestation_identities: Sequence[Mapping[str, Any]] | None = None tool: Mapping[str, Any] | None = None def __init__( self, *, name: NormalizedName, version: Version | None = None, marker: Marker | None = None, requires_python: SpecifierSet | None = None, dependencies: Sequence[Mapping[str, Any]] | None = None, vcs: PackageVcs | None = None, directory: PackageDirectory | None = None, archive: PackageArchive | None = None, index: str | None = None, sdist: PackageSdist | None = None, wheels: Sequence[PackageWheel] | None = None, attestation_identities: Sequence[Mapping[str, Any]] | None = None, tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "version", version) object.__setattr__(self, "marker", marker) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "dependencies", dependencies) object.__setattr__(self, "vcs", vcs) object.__setattr__(self, "directory", directory) object.__setattr__(self, "archive", archive) object.__setattr__(self, "index", index) object.__setattr__(self, "sdist", sdist) object.__setattr__(self, "wheels", wheels) object.__setattr__(self, "attestation_identities", attestation_identities) object.__setattr__(self, "tool", tool) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package = cls( name=_get_required_as(d, str, _validate_normalized_name, "name"), version=_get_as(d, str, Version, "version"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] marker=_get_as(d, str, Marker, "marker"), vcs=_get_object(d, PackageVcs, "vcs"), directory=_get_object(d, PackageDirectory, "directory"), archive=_get_object(d, PackageArchive, "archive"), index=_get(d, str, "index"), sdist=_get_object(d, PackageSdist, "sdist"), wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) distributions = bool(package.sdist) + len(package.wheels or []) direct_urls = ( bool(package.vcs) + bool(package.directory) + bool(package.archive) ) if distributions > 0 and direct_urls > 0: raise PylockValidationError( "None of vcs, directory, archive must be set if sdist or wheels are set" ) if distributions == 0 and direct_urls != 1: raise PylockValidationError( "Exactly one of vcs, directory, archive must be set " "if sdist and wheels are not set" ) for i, wheel in enumerate(package.wheels or []): try: (name, version, _, _) = parse_wheel_filename(wheel.filename) except Exception as e: raise PylockValidationError( f"Invalid wheel filename {wheel.filename!r}", context=f"wheels[{i}]", ) from e if name != package.name: raise PylockValidationError( f"Name in {wheel.filename!r} is not consistent with " f"package name {package.name!r}", context=f"wheels[{i}]", ) if package.version and version != package.version: raise PylockValidationError( f"Version in {wheel.filename!r} is not consistent with " f"package version {str(package.version)!r}", context=f"wheels[{i}]", ) if package.sdist: try: name, version = parse_sdist_filename(package.sdist.filename) except Exception as e: raise PylockValidationError( f"Invalid sdist filename {package.sdist.filename!r}", context="sdist", ) from e if name != package.name: raise PylockValidationError( f"Name in {package.sdist.filename!r} is not consistent with " f"package name {package.name!r}", context="sdist", ) if package.version and version != package.version: raise PylockValidationError( f"Version in {package.sdist.filename!r} is not consistent with " f"package version {str(package.version)!r}", context="sdist", ) try: for i, attestation_identity in enumerate( # noqa: B007 package.attestation_identities or [] ): _get_required(attestation_identity, str, "kind") except Exception as e: raise PylockValidationError( e, context=f"attestation-identities[{i}]" ) from e return package @property def is_direct(self) -> bool: return not (self.sdist or self.wheels) @dataclass(frozen=True, init=False) class Pylock: """A class representing a pylock file.""" lock_version: Version environments: Sequence[Marker] | None = None requires_python: SpecifierSet | None = None extras: Sequence[NormalizedName] | None = None dependency_groups: Sequence[str] | None = None default_groups: Sequence[str] | None = None created_by: str # type: ignore[misc] packages: Sequence[Package] # type: ignore[misc] tool: Mapping[str, Any] | None = None def __init__( self, *, lock_version: Version, environments: Sequence[Marker] | None = None, requires_python: SpecifierSet | None = None, extras: Sequence[NormalizedName] | None = None, dependency_groups: Sequence[str] | None = None, default_groups: Sequence[str] | None = None, created_by: str, packages: Sequence[Package], tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "lock_version", lock_version) object.__setattr__(self, "environments", environments) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "extras", extras) object.__setattr__(self, "dependency_groups", dependency_groups) object.__setattr__(self, "default_groups", default_groups) object.__setattr__(self, "created_by", created_by) object.__setattr__(self, "packages", packages) object.__setattr__(self, "tool", tool) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: pylock = cls( lock_version=_get_required_as(d, str, Version, "lock-version"), environments=_get_sequence_as(d, str, Marker, "environments"), extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), dependency_groups=_get_sequence(d, str, "dependency-groups"), default_groups=_get_sequence(d, str, "default-groups"), created_by=_get_required(d, str, "created-by"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), packages=_get_required_sequence_of_objects(d, Package, "packages"), tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) if not Version("1") <= pylock.lock_version < Version("2"): raise PylockUnsupportedVersionError( f"pylock version {pylock.lock_version} is not supported" ) if pylock.lock_version > Version("1.0"): _logger.warning( "pylock minor version %s is not supported", pylock.lock_version ) return pylock @classmethod def from_dict(cls, d: Mapping[str, Any], /) -> Self: """Create and validate a Pylock instance from a TOML dictionary. Raises :class:`PylockValidationError` if the input data is not spec-compliant. """ return cls._from_dict(d) def to_dict(self) -> Mapping[str, Any]: """Convert the Pylock instance to a TOML dictionary.""" return dataclasses.asdict(self, dict_factory=_toml_dict_factory) def validate(self) -> None: """Validate the Pylock instance against the specification. Raises :class:`PylockValidationError` otherwise.""" self.from_dict(self.to_dict()) def select( self, *, environment: Environment | None = None, tags: Sequence[Tag] | None = None, extras: Collection[str] | None = None, dependency_groups: Collection[str] | None = None, ) -> Iterator[ tuple[ Package, PackageVcs | PackageDirectory | PackageArchive | PackageWheel | PackageSdist, ] ]: """Select what to install from the lock file. The *environment* and *tags* parameters represent the environment being selected for. If unspecified, ``packaging.markers.default_environment()`` and ``packaging.tags.sys_tags()`` are used. The *extras* parameter represents the extras to install. The *dependency_groups* parameter represents the groups to install. If unspecified, the default groups are used. This method must be used on valid Pylock instances (i.e. one obtained from :meth:`Pylock.from_dict` or if constructed manually, after calling :meth:`Pylock.validate`). """ compatible_tags_selector = create_compatible_tags_selector(tags or sys_tags()) # #. Gather the extras and dependency groups to install and set ``extras`` and # ``dependency_groups`` for marker evaluation, respectively. # # #. ``extras`` SHOULD be set to the empty set by default. # #. ``dependency_groups`` SHOULD be the set created from # :ref:`pylock-default-groups` by default. env = cast( "dict[str, str | frozenset[str]]", dict( environment or {}, # Marker.evaluate will fill-up extras=frozenset(extras or []), dependency_groups=frozenset( (self.default_groups or []) if dependency_groups is None # to allow selecting no group else dependency_groups ), ), ) env_python_full_version = ( environment["python_full_version"] if environment else default_environment()["python_full_version"] ) # #. Check if the metadata version specified by :ref:`pylock-lock-version` is # supported; an error or warning MUST be raised as appropriate. # Covered by lock.validate() which is a precondition for this method. # #. If :ref:`pylock-requires-python` is specified, check that the environment # being installed for meets the requirement; an error MUST be raised if it is # not met. if self.requires_python and not self.requires_python.contains( env_python_full_version, ): raise PylockSelectError( f"python_full_version {env_python_full_version!r} " f"in provided environment does not satisfy the Python version " f"requirement {str(self.requires_python)!r}" ) # #. If :ref:`pylock-environments` is specified, check that at least one of the # environment marker expressions is satisfied; an error MUST be raised if no # expression is satisfied. if self.environments: for env_marker in self.environments: if env_marker.evaluate( cast("dict[str, str]", environment or {}), context="requirement" ): break else: raise PylockSelectError( "Provided environment does not satisfy any of the " "environments specified in the lock file" ) # #. For each package listed in :ref:`pylock-packages`: selected_packages_by_name: dict[str, tuple[int, Package]] = {} for package_index, package in enumerate(self.packages): # #. If :ref:`pylock-packages-marker` is specified, check if it is # satisfied;if it isn't, skip to the next package. if package.marker and not package.marker.evaluate(env, context="lock_file"): continue # #. If :ref:`pylock-packages-requires-python` is specified, check if it is # satisfied; an error MUST be raised if it isn't. if package.requires_python and not package.requires_python.contains( env_python_full_version, ): raise PylockSelectError( f"python_full_version {env_python_full_version!r} " f"in provided environment does not satisfy the Python version " f"requirement {str(package.requires_python)!r} for package " f"{package.name!r} at packages[{package_index}]" ) # #. Check that no other conflicting instance of the package has been slated # to be installed; an error about the ambiguity MUST be raised otherwise. if package.name in selected_packages_by_name: raise PylockSelectError( f"Multiple packages with the name {package.name!r} are " f"selected at packages[{package_index}] and " f"packages[{selected_packages_by_name[package.name][0]}]" ) # #. Check that the source of the package is specified appropriately (i.e. # there are no conflicting sources in the package entry); # an error MUST be raised if any issues are found. # Covered by lock.validate() which is a precondition for this method. # #. Add the package to the set of packages to install. selected_packages_by_name[package.name] = (package_index, package) # #. For each package to be installed: for package_index, package in selected_packages_by_name.values(): # - If :ref:`pylock-packages-vcs` is set: if package.vcs is not None: yield package, package.vcs # - Else if :ref:`pylock-packages-directory` is set: elif package.directory is not None: yield package, package.directory # - Else if :ref:`pylock-packages-archive` is set: elif package.archive is not None: yield package, package.archive # - Else if there are entries for :ref:`pylock-packages-wheels`: elif package.wheels: # #. Look for the appropriate wheel file based on # :ref:`pylock-packages-wheels-name`; if one is not found then move # on to :ref:`pylock-packages-sdist` or an error MUST be raised about # a lack of source for the project. best_wheel = next( compatible_tags_selector( (wheel, parse_wheel_filename(wheel.filename)[-1]) for wheel in package.wheels ), None, ) if best_wheel: yield package, best_wheel elif package.sdist is not None: yield package, package.sdist else: raise PylockSelectError( f"No wheel found matching the provided tags " f"for package {package.name!r} " f"at packages[{package_index}], " f"and no sdist available as a fallback" ) # - Else if no :ref:`pylock-packages-wheels` file is found or # :ref:`pylock-packages-sdist` is solely set: elif package.sdist is not None: yield package, package.sdist else: # Covered by lock.validate() which is a precondition for this method. raise NotImplementedError # pragma: no cover ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1073568 packaging-26.2/src/packaging/requirements.py0000644000000000000000000001043715172742311016135 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 __all__ = [ "InvalidRequirement", "Requirement", ] def __dir__() -> list[str]: return __all__ 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. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ # 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 __getstate__(self) -> str: # Return the requirement string for compactness and stability. # Re-parsed on load to reconstruct all fields. return str(self) def __setstate__(self, state: object) -> None: if isinstance(state, str): # New format (26.2+): just the requirement string. try: tmp = Requirement(state) except InvalidRequirement as exc: raise TypeError(f"Cannot restore Requirement from {state!r}") from exc self.name = tmp.name self.url = tmp.url self.extras = tmp.extras self.specifier = tmp.specifier self.marker = tmp.marker return if isinstance(state, dict): # Old format (packaging <= 26.1, no __slots__): plain __dict__. self.__dict__.update(state) return raise TypeError(f"Cannot restore Requirement from {state!r}") def __str__(self) -> str: return "".join(self._iter_parts(self.name)) def __repr__(self) -> str: return f"<{self.__class__.__name__}({str(self)!r})>" def __hash__(self) -> int: 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=1777059017.1073568 packaging-26.2/src/packaging/specifiers.py0000644000000000000000000021353215172742311015547 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 enum import functools import itertools import re import sys import typing from typing import ( TYPE_CHECKING, Any, Callable, Final, Iterable, Iterator, Sequence, TypeVar, Union, ) from .utils import canonicalize_version from .version import InvalidVersion, Version if sys.version_info >= (3, 10): from typing import TypeGuard # pragma: no cover elif TYPE_CHECKING: from typing_extensions import TypeGuard __all__ = [ "BaseSpecifier", "InvalidSpecifier", "Specifier", "SpecifierSet", ] def __dir__() -> list[str]: return __all__ def _validate_spec(spec: object, /) -> TypeGuard[tuple[str, str]]: return ( isinstance(spec, tuple) and len(spec) == 2 and isinstance(spec[0], str) and isinstance(spec[1], str) ) def _validate_pre(pre: object, /) -> TypeGuard[bool | None]: return pre is None or isinstance(pre, bool) T = TypeVar("T") UnparsedVersion = Union[Version, str] UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) CallableOperator = Callable[[Version, str], bool] # The smallest possible PEP 440 version. No valid version is less than this. _MIN_VERSION: Final[Version] = Version("0.dev0") def _trim_release(release: tuple[int, ...]) -> tuple[int, ...]: """Strip trailing zeros from a release tuple for normalized comparison.""" end = len(release) while end > 1 and release[end - 1] == 0: end -= 1 return release if end == len(release) else release[:end] class _BoundaryKind(enum.Enum): """Where a boundary marker sits in the version ordering.""" AFTER_LOCALS = enum.auto() # after V+local, before V.post0 AFTER_POSTS = enum.auto() # after V.postN, before next release @functools.total_ordering class _BoundaryVersion: """A point on the version line between two real PEP 440 versions. Some specifier semantics imply boundaries between real versions: ``<=1.0`` includes ``1.0+local`` and ``>1.0`` excludes ``1.0.post0``. No real :class:`Version` falls on those boundaries, so this class creates values that sort between the real versions on either side. Two kinds exist, shown relative to a base version V:: V < V+local < AFTER_LOCALS(V) < V.post0 < AFTER_POSTS(V) ``AFTER_LOCALS`` sits after V and every V+local, but before V.post0. Upper bound of ``<=V``, ``==V``, ``!=V``. ``AFTER_POSTS`` sits after every V.postN, but before the next release segment. Lower bound of ``>V`` (final or pre-release V) to exclude post-releases per PEP 440. """ __slots__ = ("_kind", "_trimmed_release", "version") def __init__(self, version: Version, kind: _BoundaryKind) -> None: self.version = version self._kind = kind self._trimmed_release = _trim_release(version.release) def _is_family(self, other: Version) -> bool: """Is ``other`` a version that this boundary sorts above?""" v = self.version if not ( other.epoch == v.epoch and _trim_release(other.release) == self._trimmed_release and other.pre == v.pre ): return False if self._kind == _BoundaryKind.AFTER_LOCALS: # Local family: exact same public version (any local label). return other.post == v.post and other.dev == v.dev # Post family: same base + any post-release (or identical). return other.dev == v.dev or other.post is not None def __eq__(self, other: object) -> bool: if isinstance(other, _BoundaryVersion): return self.version == other.version and self._kind == other._kind return NotImplemented def __lt__(self, other: _BoundaryVersion | Version) -> bool: if isinstance(other, _BoundaryVersion): if self.version != other.version: return self.version < other.version return self._kind.value < other._kind.value return not self._is_family(other) and self.version < other def __hash__(self) -> int: return hash((self.version, self._kind)) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.version!r}, {self._kind.name})" @functools.total_ordering class _LowerBound: """Lower bound of a version range. A version *v* of ``None`` means unbounded below (-inf). At equal versions, ``[v`` sorts before ``(v`` because an inclusive bound starts earlier. """ __slots__ = ("inclusive", "version") def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: self.version = version self.inclusive = inclusive def __eq__(self, other: object) -> bool: if not isinstance(other, _LowerBound): return NotImplemented # pragma: no cover return self.version == other.version and self.inclusive == other.inclusive def __lt__(self, other: _LowerBound) -> bool: if not isinstance(other, _LowerBound): # pragma: no cover return NotImplemented # -inf < anything (except -inf). if self.version is None: return other.version is not None if other.version is None: return False if self.version != other.version: return self.version < other.version # [v < (v: inclusive starts earlier. return self.inclusive and not other.inclusive def __hash__(self) -> int: return hash((self.version, self.inclusive)) def __repr__(self) -> str: bracket = "[" if self.inclusive else "(" return f"<{self.__class__.__name__} {bracket}{self.version!r}>" @functools.total_ordering class _UpperBound: """Upper bound of a version range. A version *v* of ``None`` means unbounded above (+inf). At equal versions, ``v)`` sorts before ``v]`` because an exclusive bound ends earlier. """ __slots__ = ("inclusive", "version") def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: self.version = version self.inclusive = inclusive def __eq__(self, other: object) -> bool: if not isinstance(other, _UpperBound): return NotImplemented # pragma: no cover return self.version == other.version and self.inclusive == other.inclusive def __lt__(self, other: _UpperBound) -> bool: if not isinstance(other, _UpperBound): # pragma: no cover return NotImplemented # Nothing < +inf (except +inf itself). if self.version is None: return False if other.version is None: return True if self.version != other.version: return self.version < other.version # v) < v]: exclusive ends earlier. return not self.inclusive and other.inclusive def __hash__(self) -> int: return hash((self.version, self.inclusive)) def __repr__(self) -> str: bracket = "]" if self.inclusive else ")" return f"<{self.__class__.__name__} {self.version!r}{bracket}>" if typing.TYPE_CHECKING: _VersionOrBoundary = Union[Version, _BoundaryVersion, None] #: A single contiguous version range, represented as a #: (lower bound, upper bound) pair. _VersionRange = tuple[_LowerBound, _UpperBound] _NEG_INF = _LowerBound(None, False) _POS_INF = _UpperBound(None, False) _FULL_RANGE: tuple[_VersionRange] = ((_NEG_INF, _POS_INF),) def _range_is_empty(lower: _LowerBound, upper: _UpperBound) -> bool: """True when the range defined by *lower* and *upper* contains no versions.""" if lower.version is None or upper.version is None: return False if lower.version == upper.version: return not (lower.inclusive and upper.inclusive) return lower.version > upper.version def _intersect_ranges( left: Sequence[_VersionRange], right: Sequence[_VersionRange], ) -> list[_VersionRange]: """Intersect two sorted, non-overlapping range lists (two-pointer merge).""" result: list[_VersionRange] = [] left_index = right_index = 0 while left_index < len(left) and right_index < len(right): left_lower, left_upper = left[left_index] right_lower, right_upper = right[right_index] lower = max(left_lower, right_lower) upper = min(left_upper, right_upper) if not _range_is_empty(lower, upper): result.append((lower, upper)) # Advance whichever side has the smaller upper bound. if left_upper < right_upper: left_index += 1 else: right_index += 1 return result def _next_prefix_dev0(version: Version) -> Version: """Smallest version in the next prefix: 1.2 -> 1.3.dev0.""" release = (*version.release[:-1], version.release[-1] + 1) return Version.from_parts(epoch=version.epoch, release=release, dev=0) def _base_dev0(version: Version) -> Version: """The .dev0 of a version's base release: 1.2 -> 1.2.dev0.""" return Version.from_parts(epoch=version.epoch, release=version.release, dev=0) def _coerce_version(version: UnparsedVersion) -> Version | None: if not isinstance(version, Version): try: version = Version(version) except InvalidVersion: return None return version def _public_version(version: Version) -> Version: if version.local is None: return version return version.__replace__(local=None) def _post_base(version: Version) -> Version: """The version that *version* is a post-release of. 1.0.post1 -> 1.0, 1.0a1.post0 -> 1.0a1, 1.0.post0.dev1 -> 1.0. """ return version.__replace__(post=None, dev=None, local=None) def _earliest_prerelease(version: Version) -> Version: """Earliest pre-release of *version*. 1.2 -> 1.2.dev0, 1.2.post1 -> 1.2.post1.dev0. """ return version.__replace__(dev=0, local=None) def _nearest_non_prerelease( v: _VersionOrBoundary, ) -> Version | None: """Smallest non-pre-release version at or above *v*, or None.""" if v is None: return None if isinstance(v, _BoundaryVersion): inner = v.version if inner.is_prerelease: # AFTER_LOCALS(1.0a1) -> nearest non-pre is 1.0 return inner.__replace__(pre=None, dev=None, local=None) # AFTER_LOCALS(1.0) -> nearest non-pre is 1.0.post0 # AFTER_LOCALS(1.0.post0) -> nearest non-pre is 1.0.post1 k = (inner.post + 1) if inner.post is not None else 0 return inner.__replace__(post=k, local=None) if not v.is_prerelease: return v # Strip pre/dev to get the final or post-release form. return v.__replace__(pre=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. """ @typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ... @typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ... @abc.abstractmethod def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """ class Specifier(BaseSpecifier): """This class abstracts handling of version specifiers. .. tip:: It is generally not required to instantiate this manually. You should instead prefer to work with :class:`SpecifierSet` instead, which can parse comma-separated version specifiers (which is what package metadata contains). Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ __slots__ = ( "_prereleases", "_ranges", "_spec", "_spec_version", "_wildcard_split", ) _specifier_regex_str = r""" (?: (?: # The identity operators allow for an escape hatch that will # do an exact string match of the version you wish to install. # This will not be parsed by PEP 440 and we cannot determine # any semantic meaning from it. This operator is discouraged # but included entirely as an escape hatch. === # Only match for the identity operator \s* [^\s;)]* # The arbitrary version can be just about anything, # we match everything except for whitespace, a # semi-colon for marker support, and a closing paren # since versions can be enclosed in them. ) | (?: # The (non)equality operators allow for wild card and local # versions to be specified so we have to define these two # operators separately to enable that. (?:==|!=) # Only match for equals and not equals \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release # You cannot use a wild card and a pre-release, post-release, a dev or # local version together so group them with a | and make them optional. (?: \.\* # Wild card syntax of .* | (?a: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?a: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release (?a:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local )? ) | (?: # The compatible operator requires at least two digits in the # release segment. (?:~=) # Only match for the compatible operator \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) | (?: # All other operators only allow a sub set of what the # (non)equality operators do. Specifically they do not allow # local versions to be specified nor do they allow the prefix # matching wild cards. (?:<=|>=|<|>) \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release (?a: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?a: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) ) """ _regex = re.compile( r"\s*" + _specifier_regex_str + r"\s*", re.VERBOSE | re.IGNORECASE ) _operators: Final = { "~=": "compatible", "==": "equal", "!=": "not_equal", "<=": "less_than_equal", ">=": "greater_than_equal", "<": "less_than", ">": "greater_than", "===": "arbitrary", } def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: """Initialize a Specifier instance. :param spec: The string representation of a specifier which will be parsed and normalized before use. :param prereleases: This tells the specifier if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given specifier is invalid (i.e. bad syntax). """ if not self._regex.fullmatch(spec): raise InvalidSpecifier(f"Invalid specifier: {spec!r}") spec = spec.strip() if spec.startswith("==="): operator, version = spec[:3], spec[3:].strip() elif spec.startswith(("~=", "==", "!=", "<=", ">=")): operator, version = spec[:2], spec[2:].strip() else: operator, version = spec[:1], spec[1:].strip() self._spec: tuple[str, str] = (operator, version) # Store whether or not this Specifier should accept prereleases self._prereleases = prereleases # Specifier version cache self._spec_version: tuple[str, Version] | None = None # Populated on first wildcard (==X.*) comparison self._wildcard_split: tuple[list[str], int] | None = None # Version range cache (populated by _to_ranges) self._ranges: Sequence[_VersionRange] | None = None def _get_spec_version(self, version: str) -> Version | None: """One element cache, as only one spec Version is needed per Specifier.""" if self._spec_version is not None and self._spec_version[0] == version: return self._spec_version[1] version_specifier = _coerce_version(version) if version_specifier is None: return None self._spec_version = (version, version_specifier) return version_specifier def _require_spec_version(self, version: str) -> Version: """Get spec version, asserting it's valid (not for === operator). This method should only be called for operators where version strings are guaranteed to be valid PEP 440 versions (not ===). """ spec_version = self._get_spec_version(version) assert spec_version is not None return spec_version def _to_ranges(self) -> Sequence[_VersionRange]: """Convert this specifier to sorted, non-overlapping version ranges. Each standard operator maps to one or two ranges. ``===`` is modeled as full range (actual check done separately). Cached. """ if self._ranges is not None: return self._ranges op = self.operator ver_str = self.version if op == "===": self._ranges = _FULL_RANGE return _FULL_RANGE if ver_str.endswith(".*"): result = self._wildcard_ranges(op, ver_str) else: result = self._standard_ranges(op, ver_str) self._ranges = result return result def _wildcard_ranges(self, op: str, ver_str: str) -> list[_VersionRange]: # ==1.2.* -> [1.2.dev0, 1.3.dev0); !=1.2.* -> complement. base = self._require_spec_version(ver_str[:-2]) lower = _base_dev0(base) upper = _next_prefix_dev0(base) if op == "==": return [(_LowerBound(lower, True), _UpperBound(upper, False))] # != return [ (_NEG_INF, _UpperBound(lower, False)), (_LowerBound(upper, True), _POS_INF), ] def _standard_ranges(self, op: str, ver_str: str) -> list[_VersionRange]: v = self._require_spec_version(ver_str) if op == ">=": return [(_LowerBound(v, True), _POS_INF)] if op == "<=": return [ ( _NEG_INF, _UpperBound(_BoundaryVersion(v, _BoundaryKind.AFTER_LOCALS), True), ) ] if op == ">": if v.dev is not None: # >V.devN: dev versions have no post-releases, so the # next real version is V.dev(N+1). lower_ver = v.__replace__(dev=v.dev + 1, local=None) return [(_LowerBound(lower_ver, True), _POS_INF)] if v.post is not None: # >V.postN: next real version is V.post(N+1).dev0. lower_ver = v.__replace__(post=v.post + 1, dev=0, local=None) return [(_LowerBound(lower_ver, True), _POS_INF)] # >V (final or pre-release): skip V+local and all V.postN. return [ ( _LowerBound(_BoundaryVersion(v, _BoundaryKind.AFTER_POSTS), False), _POS_INF, ) ] if op == "<": # bool | None: # If there is an explicit prereleases set for this, then we'll just # blindly use that. if self._prereleases is not None: return self._prereleases # Only the "!=" operator does not imply prereleases when # the version in the specifier is a prerelease. operator, version_str = self._spec if operator == "!=": return False # The == specifier with trailing .* cannot include prereleases # e.g. "==1.0a1.*" is not valid. if operator == "==" and version_str.endswith(".*"): return False # "===" can have arbitrary string versions, so we cannot parse # those, we take prereleases as unknown (None) for those. version = self._get_spec_version(version_str) if version is None: return None # For all other operators, use the check if spec Version # object implies pre-releases. return version.is_prerelease @prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value def __getstate__(self) -> tuple[tuple[str, str], bool | None]: # Return state as a 2-item tuple for compactness: # ((operator, version), prereleases) # Cache members are excluded and will be recomputed on demand. return (self._spec, self._prereleases) def __setstate__(self, state: object) -> None: # Always discard cached values - they will be recomputed on demand. self._spec_version = None self._wildcard_split = None self._ranges = None if isinstance(state, tuple): if len(state) == 2: # New format (26.2+): ((operator, version), prereleases) spec, prereleases = state if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return if len(state) == 2 and isinstance(state[1], dict): # Format (packaging 26.0-26.1): (None, {slot: value}). _, slot_dict = state spec = slot_dict.get("_spec") prereleases = slot_dict.get("_prereleases", "invalid") if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return if isinstance(state, dict): # Old format (packaging <= 25.x, no __slots__): state is a plain dict. spec = state.get("_spec") prereleases = state.get("_prereleases", "invalid") if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return raise TypeError(f"Cannot restore Specifier from {state!r}") @property def operator(self) -> str: """The operator of this specifier. >>> Specifier("==1.2.3").operator '==' """ return self._spec[0] @property def version(self) -> str: """The version of this specifier. >>> Specifier("==1.2.3").version '1.2.3' """ return self._spec[1] def __repr__(self) -> str: """A representation of the Specifier that shows all internal state. >>> Specifier('>=1.0.0') =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._compare_greater_than_equal(prospective, spec)) and ( self._compare_equal(prospective, prefix) ) def _get_wildcard_split(self, spec: str) -> tuple[list[str], int]: """Cached split of a wildcard spec into components and numeric length. >>> Specifier("==1.*")._get_wildcard_split("1.*") (['0', '1'], 2) >>> Specifier("==3.10.*")._get_wildcard_split("3.10.*") (['0', '3', '10'], 3) """ wildcard_split = self._wildcard_split if wildcard_split is None: normalized = canonicalize_version(spec[:-2], strip_trailing_zero=False) split_spec = _version_split(normalized) wildcard_split = (split_spec, _numeric_prefix_len(split_spec)) self._wildcard_split = wildcard_split return wildcard_split def _compare_equal(self, prospective: Version, spec: str) -> bool: # We need special logic to handle prefix matching if spec.endswith(".*"): split_spec, spec_numeric_len = self._get_wildcard_split(spec) # In the case of prefix matching we want to ignore local segment. normalized_prospective = canonicalize_version( _public_version(prospective), strip_trailing_zero=False ) # 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 = _left_pad(split_prospective, spec_numeric_len) # 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 # The spec says: "= _earliest_prerelease(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 # The spec says: ">V MUST NOT allow a post-release of the specified # version unless the specified version is itself a post-release." if ( not spec.is_postrelease and prospective.is_postrelease and _post_base(prospective) == spec ): return False # Per the spec: ">V MUST NOT match a local version of the specified # version". A "local version of V" is any version whose public part # equals V. So >1.0a1 must not match 1.0a1+local, but must still # match 1.0a2+local. if prospective.local is not None and _public_version(prospective) == 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))) @typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ... @typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ... def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """Filter items in the given iterable, that match the specifier. :param iterable: An iterable that can contain version strings and :class:`Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions. :param key: A callable that takes a single argument (an item from the iterable) and returns a version string or :class:`Version` instance to be used for filtering. >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) ['1.2.3', '1.3', ] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3").filter( ... [{"ver": "1.2"}, {"ver": "1.3"}], ... key=lambda x: x["ver"])) [{'ver': '1.3'}] """ 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 key is None else key(version)) match = False 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 self.operator == "===": match = self._compare_arbitrary( version if key is None else key(version), self.version ) else: match = operator_callable(parsed_version, self.version) if match and parsed_version is not None: # 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 _pep440_filter_prereleases( iterable: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None ) -> Iterator[Any]: """Filter per PEP 440: exclude prereleases unless no finals exist.""" # Two lists used: # * all_nonfinal to preserve order if no finals exist # * arbitrary_strings for streaming when first final found all_nonfinal: list[Any] = [] arbitrary_strings: list[Any] = [] found_final = False for item in iterable: parsed = _coerce_version(item if key is None else key(item)) if parsed is None: # Arbitrary strings are always included as it is not # possible to determine if they are prereleases, # and they have already passed all specifiers. if found_final: yield item else: arbitrary_strings.append(item) all_nonfinal.append(item) continue if not parsed.is_prerelease: # Final release found - flush arbitrary strings, then yield if not found_final: yield from arbitrary_strings found_final = True yield item continue # Prerelease - buffer if no finals yet, otherwise skip if not found_final: all_nonfinal.append(item) # No finals found - yield all buffered items if not found_final: yield from all_nonfinal 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 _numeric_prefix_len(split: list[str]) -> int: """Count leading numeric components in a :func:`_version_split` result. >>> _numeric_prefix_len(["0", "1", "2", "a1"]) 3 """ count = 0 for segment in split: if not segment.isdigit(): break count += 1 return count def _left_pad(split: list[str], target_numeric_len: int) -> list[str]: """Pad a :func:`_version_split` result with ``"0"`` segments to reach ``target_numeric_len`` numeric components. Suffix segments are preserved. >>> _left_pad(["0", "1", "a1"], 4) ['0', '1', '0', '0', 'a1'] """ numeric_len = _numeric_prefix_len(split) pad_needed = target_numeric_len - numeric_len if pad_needed <= 0: return split return [*split[:numeric_len], *(["0"] * pad_needed), *split[numeric_len:]] def _operator_cost(op_entry: tuple[CallableOperator, str, str]) -> int: """Sort key for Cost Based Ordering of specifier operators in _filter_versions. Operators run sequentially on a shrinking candidate set, so operators that reject the most versions should run first to minimize work for later ones. Tier 0: Exact equality (==, ===), likely to narrow candidates to one version Tier 1: Range checks (>=, <=, >, <), cheap and usually reject a large portion Tier 2: Wildcard equality (==.*) and compatible release (~=), more expensive Tier 3: Exact !=, cheap but rarely rejects Tier 4: Wildcard !=.*, expensive and rarely rejects """ _, ver, op = op_entry if op == "==": return 0 if not ver.endswith(".*") else 2 if op in (">=", "<=", ">", "<"): return 1 if op == "~=": return 2 if op == "!=": return 3 if not ver.endswith(".*") else 4 if op == "===": return 0 raise ValueError(f"Unknown operator: {op!r}") # pragma: no cover class SpecifierSet(BaseSpecifier): """This class abstracts handling of a set of version specifiers. It can be passed a single specifier (``>=3.0``), a comma-separated list of specifiers (``>=3.0,!=3.1``), or no specifier at all. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ __slots__ = ( "_canonicalized", "_has_arbitrary", "_is_unsatisfiable", "_prereleases", "_resolved_ops", "_specs", ) def __init__( self, specifiers: str | Iterable[Specifier] = "", prereleases: bool | None = None, ) -> None: """Initialize a SpecifierSet instance. :param specifiers: The string representation of a specifier or a comma-separated list of specifiers which will be parsed and normalized before use. May also be an iterable of ``Specifier`` instances, which will be used as is. :param prereleases: This tells the SpecifierSet if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given ``specifiers`` are not parseable than this exception will be raised. """ if isinstance(specifiers, str): # Split on `,` to break each individual specifier into its own item, and # strip each item to remove leading/trailing whitespace. split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] self._specs: tuple[Specifier, ...] = tuple(map(Specifier, split_specifiers)) # Fast substring check; avoids iterating parsed specs. self._has_arbitrary = "===" in specifiers else: self._specs = tuple(specifiers) # Substring check works for both Specifier objects and plain # strings (setuptools passes lists of strings). self._has_arbitrary = any("===" in str(s) for s in self._specs) self._canonicalized = len(self._specs) <= 1 self._resolved_ops: list[tuple[CallableOperator, str, str]] | None = None # Store our prereleases value so we can use it later to determine if # we accept prereleases or not. self._prereleases = prereleases self._is_unsatisfiable: bool | None = None def _canonical_specs(self) -> tuple[Specifier, ...]: """Deduplicate, sort, and cache specs for order-sensitive operations.""" if not self._canonicalized: self._specs = tuple(dict.fromkeys(sorted(self._specs, key=str))) self._canonicalized = True self._resolved_ops = None self._is_unsatisfiable = None return self._specs @property def prereleases(self) -> bool | None: # If we have been given an explicit prerelease modifier, then we'll # pass that through here. if self._prereleases is not None: return self._prereleases # If we don't have any specifiers, and we don't have a forced value, # then we'll just return None since we don't know if this should have # pre-releases or not. if not self._specs: return None # Otherwise we'll see if any of the given specifiers accept # prereleases, if any of them do we'll return True, otherwise False. if any(s.prereleases for s in self._specs): return True return None @prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value self._is_unsatisfiable = None def __getstate__(self) -> tuple[tuple[Specifier, ...], bool | None]: # Return state as a 2-item tuple for compactness: # (specs, prereleases) # Cache members are excluded and will be recomputed on demand. return (self._specs, self._prereleases) def __setstate__(self, state: object) -> None: # Always discard cached values - they will be recomputed on demand. self._resolved_ops = None self._is_unsatisfiable = None if isinstance(state, tuple): if len(state) == 2: # New format (26.2+): (specs, prereleases) specs, prereleases = state if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in specs) return if len(state) == 2 and isinstance(state[1], dict): # Format (packaging 26.0-26.1): (None, {slot: value}). _, slot_dict = state specs = slot_dict.get("_specs", ()) prereleases = slot_dict.get("_prereleases") # Convert frozenset to tuple (26.0 stored as frozenset) if isinstance(specs, frozenset): specs = tuple(sorted(specs, key=str)) if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(self._specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in self._specs) return if isinstance(state, dict): # Old format (packaging <= 25.x, no __slots__): state is a plain dict. specs = state.get("_specs", ()) prereleases = state.get("_prereleases") # Convert frozenset to tuple (26.0 stored as frozenset) if isinstance(specs, frozenset): specs = tuple(sorted(specs, key=str)) if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(self._specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in self._specs) return raise TypeError(f"Cannot restore SpecifierSet from {state!r}") def __repr__(self) -> str: """A representation of the specifier set that shows all internal state. Note that the ordering of the individual specifiers within the set may not match the input string. >>> SpecifierSet('>=1.0.0,!=2.0.0') =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"<{self.__class__.__name__}({str(self)!r}{pre})>" def __str__(self) -> str: """A string representation of the specifier set that can be round-tripped. Note that the ordering of the individual specifiers within the set may not match the input string. >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) '!=1.0.1,>=1.0.0' >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) '!=1.0.1,>=1.0.0' """ return ",".join(str(s) for s in self._canonical_specs()) def __hash__(self) -> int: return hash(self._canonical_specs()) def __and__(self, other: SpecifierSet | str) -> SpecifierSet: """Return a SpecifierSet which is a combination of the two sets. :param other: The other object to combine with. >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' =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 = self._specs + other._specs specifier._canonicalized = len(specifier._specs) <= 1 specifier._has_arbitrary = self._has_arbitrary or other._has_arbitrary specifier._resolved_ops = None # Combine prerelease settings: use common or non-None value if self._prereleases is None or self._prereleases == other._prereleases: specifier._prereleases = other._prereleases elif other._prereleases is None: specifier._prereleases = self._prereleases else: raise ValueError( "Cannot combine SpecifierSets with True and False prerelease overrides." ) return specifier def __eq__(self, other: object) -> bool: """Whether or not the two SpecifierSet-like objects are equal. :param other: The other object to check against. The value of :attr:`prereleases` is ignored. >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") True >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) True >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" True >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") False >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") False """ if isinstance(other, (str, Specifier)): other = SpecifierSet(str(other)) elif not isinstance(other, SpecifierSet): return NotImplemented return self._canonical_specs() == other._canonical_specs() def __len__(self) -> int: """Returns the number of specifiers in this specifier set.""" return len(self._specs) def __iter__(self) -> Iterator[Specifier]: """ Returns an iterator over all the underlying :class:`Specifier` instances in this specifier set. >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) [, =1.0.0')>] """ return iter(self._specs) def _get_ranges(self) -> Sequence[_VersionRange]: """Intersect all specifiers into a single list of version ranges. Returns an empty list when unsatisfiable. ``===`` specs are modeled as full range; string matching is checked separately by :meth:`_check_arbitrary_unsatisfiable`. """ specs = self._specs result: Sequence[_VersionRange] | None = None for s in specs: if result is None: result = s._to_ranges() else: result = _intersect_ranges(result, s._to_ranges()) if not result: break if result is None: # pragma: no cover raise RuntimeError("_get_ranges called with no specs") return result def is_unsatisfiable(self) -> bool: """Check whether this specifier set can never be satisfied. Returns True if no version can satisfy all specifiers simultaneously. >>> SpecifierSet(">=2.0,<1.0").is_unsatisfiable() True >>> SpecifierSet(">=1.0,<2.0").is_unsatisfiable() False >>> SpecifierSet("").is_unsatisfiable() False >>> SpecifierSet("==1.0,!=1.0").is_unsatisfiable() True """ cached = self._is_unsatisfiable if cached is not None: return cached if not self._specs: self._is_unsatisfiable = False return False result = not self._get_ranges() if not result: result = self._check_arbitrary_unsatisfiable() if not result and self.prereleases is False: result = self._check_prerelease_only_ranges() self._is_unsatisfiable = result return result def _check_prerelease_only_ranges(self) -> bool: """With prereleases=False, check if every range contains only pre-release versions (which would be excluded from matching).""" for lower, upper in self._get_ranges(): nearest = _nearest_non_prerelease(lower.version) if nearest is None: return False if upper.version is None or nearest < upper.version: return False if nearest == upper.version and upper.inclusive: return False return True def _check_arbitrary_unsatisfiable(self) -> bool: """Check === (arbitrary equality) specs for unsatisfiability. === uses case-insensitive string comparison, so the only candidate that can match ``===V`` is the literal string V. This method checks whether that candidate is excluded by other specifiers. """ arbitrary = [s for s in self._specs if s.operator == "==="] if not arbitrary: return False # Multiple === must agree on the same string (case-insensitive). first = arbitrary[0].version.lower() if any(s.version.lower() != first for s in arbitrary[1:]): return True # The sole candidate is the === version string. Check whether # it can satisfy every standard spec. candidate = _coerce_version(arbitrary[0].version) # With prereleases=False, a prerelease candidate is excluded # by contains() before the === string check even runs. if ( self.prereleases is False and candidate is not None and candidate.is_prerelease ): return True standard = [s for s in self._specs if s.operator != "==="] if not standard: return False if candidate is None: # Unparsable string cannot satisfy any standard spec. return True return not all(s.contains(candidate) for s in standard) def __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 # When item is a string and === is involved, keep it as-is # so the comparison isn't done against the normalized form. if version is None or (self._has_arbitrary and not isinstance(item, Version)): check_item = item else: check_item = version return bool(list(self.filter([check_item], prereleases=prereleases))) @typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ... @typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ... def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """Filter items in the given iterable, that match the specifiers in this set. :param iterable: An iterable that can contain version strings and :class:`Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions. :param key: A callable that takes a single argument (an item from the iterable) and returns a version string or :class:`Version` instance to be used for filtering. >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) ['1.3', ] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3").filter( ... [{"ver": "1.2"}, {"ver": "1.3"}], ... key=lambda x: x["ver"])) [{'ver': '1.3'}] An "empty" SpecifierSet will filter items based on the presence of prerelease versions in the set. >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet("").filter(["1.5a1"])) ['1.5a1'] >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] """ # 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 # Filter versions that match all specifiers using Cost Based Ordering. 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. # Fast path: single specifier, delegate directly. if len(self._specs) == 1: filtered = self._specs[0].filter( iterable, prereleases=True if prereleases is None else prereleases, key=key, ) else: filtered = self._filter_versions( iterable, key, prereleases=True if prereleases is None else prereleases, ) if prereleases is not None: return filtered return _pep440_filter_prereleases(filtered, key) # Handle Empty SpecifierSet. if prereleases is True: return iter(iterable) if prereleases is False: return ( item for item in iterable if ( (version := _coerce_version(item if key is None else key(item))) is None or not version.is_prerelease ) ) # PEP 440: exclude prereleases unless no final releases matched return _pep440_filter_prereleases(iterable, key) def _filter_versions( self, iterable: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None, prereleases: bool | None = None, ) -> Iterator[Any]: """Filter versions against all specifiers in a single pass. Uses Cost Based Ordering: specifiers are sorted by _operator_cost so that cheap range operators reject versions early, avoiding expensive wildcard or compatible operators on versions that would have been rejected anyway. """ # Pre-resolve operators and sort (cached after first call). if self._resolved_ops is None: self._resolved_ops = sorted( ( (spec._get_operator(spec.operator), spec.version, spec.operator) for spec in self._specs ), key=_operator_cost, ) ops = self._resolved_ops exclude_prereleases = prereleases is False for item in iterable: parsed = _coerce_version(item if key is None else key(item)) if parsed is None: # Only === can match non-parseable versions. if all( op == "===" and str(item).lower() == ver.lower() for _, ver, op in ops ): yield item elif exclude_prereleases and parsed.is_prerelease: pass elif all( str(item if key is None else key(item)).lower() == ver.lower() if op == "===" else op_fn(parsed, ver) for op_fn, ver, op in ops ): # Short-circuits on the first failing operator. yield item ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1073568 packaging-26.2/src/packaging/tags.py0000644000000000000000000010266015172742311014350 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 operator import platform import re import struct import subprocess import sys import sysconfig from importlib.machinery import EXTENSION_SUFFIXES from typing import ( TYPE_CHECKING, Iterable, Iterator, Sequence, Tuple, TypeVar, cast, ) from . import _manylinux, _musllinux if TYPE_CHECKING: from collections.abc import Callable, Iterable from typing import AbstractSet __all__ = [ "INTERPRETER_SHORT_NAMES", "AppleVersion", "PythonVersion", "Tag", "UnsortedTagsError", "android_platforms", "compatible_tags", "cpython_tags", "create_compatible_tags_selector", "generic_tags", "interpreter_name", "interpreter_version", "ios_platforms", "mac_platforms", "parse_tag", "platform_tags", "sys_tags", ] def __dir__() -> list[str]: return __all__ logger = logging.getLogger(__name__) PythonVersion = Sequence[int] AppleVersion = Tuple[int, int] _T = TypeVar("_T") INTERPRETER_SHORT_NAMES: dict[str, str] = { "python": "py", # Generic. "cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy", } # This function can be unit tested without reloading the module # (Unlike _32_BIT_INTERPRETER) def _compute_32_bit_interpreter() -> bool: return struct.calcsize("P") == 4 _32_BIT_INTERPRETER = _compute_32_bit_interpreter() class UnsortedTagsError(ValueError): """ Raised when a tag component is not in sorted order per PEP 425. """ class Tag: """ A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] def __init__(self, interpreter: str, abi: str, platform: str) -> None: """ :param str interpreter: The interpreter name, e.g. ``"py"`` (see :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter names to their short names). :param str abi: The ABI that a wheel supports, e.g. ``"cp37m"``. :param str platform: The OS/platform the wheel supports, e.g. ``"win_amd64"``. """ self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() # The __hash__ of every single element in a Set[Tag] will be evaluated each time # that a set calls its `.disjoint()` method, which may be called hundreds of # times when scanning a page of links for packages with tags matching that # Set[Tag]. Pre-computing the value here produces significant speedups for # downstream consumers. self._hash = hash((self._interpreter, self._abi, self._platform)) @property def interpreter(self) -> str: """ The interpreter name, e.g. ``"py"`` (see :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter names to their short names). """ return self._interpreter @property def abi(self) -> str: """ The supported ABI. """ return self._abi @property def platform(self) -> str: """ The OS/platform. """ return self._platform def __eq__(self, other: object) -> bool: if not isinstance(other, Tag): return NotImplemented return ( (self._hash == other._hash) # Short-circuit ASAP for perf reasons. and (self._platform == other._platform) and (self._abi == other._abi) and (self._interpreter == other._interpreter) ) def __hash__(self) -> int: return self._hash def __str__(self) -> str: return f"{self._interpreter}-{self._abi}-{self._platform}" def __repr__(self) -> str: return f"<{self} @ {id(self)}>" def __getstate__(self) -> tuple[str, str, str]: # Return state as a 3-item tuple: (interpreter, abi, platform). # Cache member _hash is excluded and will be recomputed. return (self._interpreter, self._abi, self._platform) def __setstate__(self, state: object) -> None: if isinstance(state, tuple): if len(state) == 3 and all(isinstance(s, str) for s in state): # New format (26.2+): (interpreter, abi, platform) self._interpreter, self._abi, self._platform = state self._hash = hash((self._interpreter, self._abi, self._platform)) return if len(state) == 2 and isinstance(state[1], dict): # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). _, slots = state try: interpreter = slots["_interpreter"] abi = slots["_abi"] platform = slots["_platform"] except KeyError: raise TypeError(f"Cannot restore Tag from {state!r}") from None if not all( isinstance(value, str) for value in (interpreter, abi, platform) ): raise TypeError(f"Cannot restore Tag from {state!r}") self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() self._hash = hash((self._interpreter, self._abi, self._platform)) return raise TypeError(f"Cannot restore Tag from {state!r}") def parse_tag(tag: str, *, validate_order: bool = False) -> frozenset[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of :class:`Tag` instances. Returning a set is required due to the possibility that the tag is a `compressed tag set`_, e.g. ``"py2.py3-none-any"`` which supports both Python 2 and Python 3. If **validate_order** is true, compressed tag set components are checked to be in sorted order as required by PEP 425. :param str tag: The tag to parse, e.g. ``"py3-none-any"``. :param bool validate_order: Check whether compressed tag set components are in sorted order. :raises UnsortedTagsError: If **validate_order** is true and any compressed tag set component is not in sorted order. .. versionadded:: 26.1 The *validate_order* parameter. """ tags = set() interpreters, abis, platforms = tag.split("-") if validate_order: for component in (interpreters, abis, platforms): parts = component.split(".") if parts != sorted(parts): raise UnsortedTagsError( f"Tag component {component!r} is not in sorted order per PEP 425" ) 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 free-threaded builds do not support abi3. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading def _abi3t_applies(python_version: PythonVersion, threading: bool) -> bool: """ Determine if the Python version supports abi3t. PEP 803 was first implemented in Python 3.15 but, per PEP 803, this returns tags going back to Python 3.2 to mirror the abi3 implementation and leave open the possibility of abi3t wheels supporting older Python versions. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and threading def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: py_version = tuple(py_version) # To allow for version comparison. abis = [] version = _version_nodot(py_version[:2]) threading = debug = pymalloc = ucs4 = "" with_debug = _get_config_var("Py_DEBUG", warn) has_refcount = hasattr(sys, "gettotalrefcount") # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled # extension modules is the best option. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 has_ext = "_d.pyd" in EXTENSION_SUFFIXES if with_debug or (with_debug is None and (has_refcount or has_ext)): debug = "d" if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): threading = "t" if py_version < (3, 8): with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) if with_pymalloc or with_pymalloc is None: pymalloc = "m" if py_version < (3, 3): unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) if unicode_size == 4 or ( unicode_size is None and sys.maxunicode == 0x10FFFF ): ucs4 = "u" elif debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}{threading}") abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") return abis def cpython_tags( python_version: PythonVersion | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for the CPython interpreter. The specific tags generated are: - ``cp--`` - ``cp--`` - ``cp-none-`` - ``cp--`` where "older version" is all older minor versions down to Python 3.2 (when ``abi3`` was introduced) If ``python_version`` only provides a major-only version then only user-provided ABIs via ``abis`` and the ``none`` ABI will be used. The ``stable_abi`` will be either ``abi3`` or ``abi3t`` if `abi` is a GIL-enabled ABI like `"cp315"` or a free-threaded ABI like `"cp315t"`, respectively. :param Sequence python_version: A one- or two-item sequence representing the targeted Python version. Defaults to ``sys.version_info[:2]``. :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs compatible with the current system. :param Iterable platforms: Iterable of compatible platforms. Defaults to the platforms compatible with the current system. :param bool warn: Whether warnings should be logged. Defaults to ``False``. """ 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) use_abi3t = _abi3t_applies(python_version, threading) if use_abi3: yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) if use_abi3t: yield from (Tag(interpreter, "abi3t", platform_) for platform_ in platforms) yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) if use_abi3 or use_abi3t: for minor_version in range(python_version[1] - 1, 1, -1): for platform_ in platforms: version = _version_nodot((python_version[0], minor_version)) interpreter = f"cp{version}" if use_abi3: yield Tag(interpreter, "abi3", platform_) if use_abi3t: # Support for abi3t was introduced in Python 3.15, but in # principle abi3t wheels are possible for older limited API # versions, so allow things like ("cp37", "abi3t", "platform") yield Tag(interpreter, "abi3t", platform_) def _generic_abi() -> list[str]: """ Return the ABI tag based on EXT_SUFFIX. """ # The following are examples of `EXT_SUFFIX`. # We want to keep the parts which are related to the ABI and remove the # parts which are related to the platform: # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 # - mac: '.cpython-310-darwin.so' => cp310 # - win: '.cp310-win_amd64.pyd' => cp310 # - win: '.pyd' => cp37 (uses _cpython_abis()) # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' # => graalpy_38_native ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) if not isinstance(ext_suffix, str) or 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 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``. """ 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 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. """ 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 :attr:`~Tag.platform` tags for macOS. The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system. :param tuple version: A two-item tuple representing the version of macOS. Defaults to the current system's version. :param str arch: The CPU architecture. Defaults to the architecture of the current system, e.g. ``"x86_64"``. .. note:: Equivalent support for the other major platforms is purposefully not provided: - On Windows, platform compatibility is statically specified - On Linux, code must be run on the system itself to determine compatibility """ 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 :attr:`~Tag.platform` tags for iOS. :param tuple version: A two-item tuple representing the version of iOS. Defaults to the current system's version. :param str multiarch: The CPU architecture+ABI to be used. This should be in the format by ``sys.implementation._multiarch`` (e.g., ``arm64_iphoneos`` or ``x86_64_iphonesimulator``). Defaults to the current system's multiarch value. .. note:: Behavior of this method is undefined if invoked on non-iOS platforms without providing explicit version and multiarch arguments. """ 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 _emscripten_platforms() -> Iterator[str]: pyemscripten_platform_version = sysconfig.get_config_var( "PYEMSCRIPTEN_PLATFORM_VERSION" ) if pyemscripten_platform_version: yield f"pyemscripten_{pyemscripten_platform_version}_wasm32" yield from _generic_platforms() def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform()) def platform_tags() -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for the running interpreter. """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "iOS": return ios_platforms() elif platform.system() == "Android": return android_platforms() elif platform.system() == "Linux": return _linux_platforms() elif platform.system() == "Emscripten": return _emscripten_platforms() else: return _generic_platforms() def interpreter_name() -> str: """ Returns the name of the running interpreter. Some implementations have a reserved, two-letter abbreviation which will be returned when appropriate. This typically acts as the prefix to the :attr:`~Tag.interpreter` tag. """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name def interpreter_version(*, warn: bool = False) -> str: """ Returns the running interpreter's version. This typically acts as the suffix to the :attr:`~Tag.interpreter` tag. :param bool warn: Whether warnings should be logged. Defaults to ``False``. """ version = _get_config_var("py_version_nodot", warn=warn) return str(version) if version else _version_nodot(sys.version_info[:2]) def _version_nodot(version: PythonVersion) -> str: return "".join(map(str, version)) def sys_tags(*, warn: bool = False) -> Iterator[Tag]: """ Yields the sequence of tag triples that the running interpreter supports. The iterable is ordered so that the best-matching tag is first in the sequence. The exact preferential order to tags is interpreter-specific, but in general the tag importance is in the order of: 1. Interpreter 2. Platform 3. ABI This order is due to the fact that an ABI is inherently tied to the platform, but platform-specific code is not necessarily tied to the ABI. The interpreter is the most important tag as it dictates basic support for any wheel. The function returns an iterable in order to allow for the possible short-circuiting of tag generation if the entire sequence is not necessary and tag calculation happens to be expensive. :param bool warn: Whether warnings should be logged. Defaults to ``False``. .. versionchanged:: 21.3 Added the `pp3-none-any` tag (:issue:`311`). .. versionchanged:: 27.0 Added the `abi3t` tag (:issue:`1099`). """ 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) def create_compatible_tags_selector( tags: Iterable[Tag], ) -> Callable[[Iterable[tuple[_T, AbstractSet[Tag]]]], Iterator[_T]]: """Create a callable to select things compatible with supported tags. This function accepts an ordered sequence of tags, with the preferred tags first. The returned callable accepts an iterable of tuples (thing, set[Tag]), and returns an iterator of things, with the things with the best matching tags first. Example to select compatible wheel filenames: >>> from packaging import tags >>> from packaging.utils import parse_wheel_filename >>> selector = tags.create_compatible_tags_selector(tags.sys_tags()) >>> filenames = ["foo-1.0-py3-none-any.whl", "foo-1.0-py2-none-any.whl"] >>> list(selector([ ... (filename, parse_wheel_filename(filename)[-1]) for filename in filenames ... ])) ['foo-1.0-py3-none-any.whl'] .. versionadded:: 26.1 """ tag_ranks: dict[Tag, int] = {} for rank, tag in enumerate(tags): tag_ranks.setdefault(tag, rank) # ignore duplicate tags, keep first supported_tags = tag_ranks.keys() def selector( tagged_things: Iterable[tuple[_T, AbstractSet[Tag]]], ) -> Iterator[_T]: ranked_things: list[tuple[_T, int]] = [] for thing, thing_tags in tagged_things: supported_thing_tags = thing_tags & supported_tags if supported_thing_tags: thing_rank = min(tag_ranks[t] for t in supported_thing_tags) ranked_things.append((thing, thing_rank)) return iter( thing for thing, _ in sorted(ranked_things, key=operator.itemgetter(1)) ) return selector ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1073568 packaging-26.2/src/packaging/utils.py0000644000000000000000000002317015172742311014550 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, UnsortedTagsError, parse_tag from .version import InvalidVersion, Version, _TrimmedRelease __all__ = [ "BuildTag", "InvalidName", "InvalidSdistFilename", "InvalidWheelFilename", "NormalizedName", "canonicalize_name", "canonicalize_version", "is_normalized_name", "parse_sdist_filename", "parse_wheel_filename", ] def __dir__() -> list[str]: return __all__ BuildTag = Union[Tuple[()], Tuple[int, str]] NormalizedName = NewType("NormalizedName", str) """ A :class:`typing.NewType` of :class:`str`, representing a normalized name. """ 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 | re.ASCII ) _normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]", re.ASCII) # PEP 427: The build number must start with a digit. _build_tag_regex = re.compile(r"(\d+)(.*)", re.ASCII) def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: """ This function takes a valid Python package or extra name, and returns the normalized form of it. The return type is typed as :class:`NormalizedName`. This allows type checkers to help require that a string has passed through this function before use. If **validate** is true, then the function will check if **name** is a valid distribution name before normalizing. :param str name: The name to normalize. :param bool validate: Check whether the name is a valid distribution name. :raises InvalidName: If **validate** is true and the name is not an acceptable distribution name. >>> from packaging.utils import canonicalize_name >>> canonicalize_name("Django") 'django' >>> canonicalize_name("oslo.concurrency") 'oslo-concurrency' >>> canonicalize_name("requests") 'requests' """ if validate and not _validate_regex.fullmatch(name): raise InvalidName(f"name is invalid: {name!r}") # Ensure all ``.`` and ``_`` are ``-`` # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 # Much faster than re, and even faster than str.translate value = name.lower().replace("_", "-").replace(".", "-") # Condense repeats (faster than regex) while "--" in value: value = value.replace("--", "-") return cast("NormalizedName", value) def is_normalized_name(name: str) -> bool: """ Check if a name is already normalized (i.e. :func:`canonicalize_name` would roundtrip to the same value). :param str name: The name to check. >>> from packaging.utils import is_normalized_name >>> is_normalized_name("requests") True >>> is_normalized_name("Django") False """ return _normalized_regex.fullmatch(name) is not None def canonicalize_version( version: Version | str, *, strip_trailing_zero: bool = True ) -> str: """Return a canonical form of a version as a string. This function takes a string representing a package version (or a :class:`~packaging.version.Version` instance), and returns the normalized form of it. By default, it strips trailing zeros from the release segment. >>> from packaging.utils import canonicalize_version >>> canonicalize_version('1.0.1') '1.0.1' Per PEP 625, versions may have multiple canonical forms, differing only by trailing zeros. >>> canonicalize_version('1.0.0') '1' >>> canonicalize_version('1.0.0', strip_trailing_zero=False) '1.0.0' Invalid versions are returned unaltered. >>> canonicalize_version('foo bar baz') 'foo bar baz' >>> canonicalize_version('1.4.0.0.0') '1.4' """ if isinstance(version, str): try: version = Version(version) except InvalidVersion: return str(version) return str(_TrimmedRelease(version) if strip_trailing_zero else version) def parse_wheel_filename( filename: str, *, validate_order: bool = False, ) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: """ This function takes the filename of a wheel file, and parses it, returning a tuple of name, version, build number, and tags. The name part of the tuple is normalized and typed as :class:`NormalizedName`. The version portion is an instance of :class:`~packaging.version.Version`. The build number is ``()`` if there is no build number in the wheel filename, otherwise a two-item tuple of an integer for the leading digits and a string for the rest of the build number. The tags portion is a frozen set of :class:`~packaging.tags.Tag` instances (as the tag string format allows multiple tags to be combined into a single string). If **validate_order** is true, compressed tag set components are checked to be in sorted order as required by PEP 425. :param str filename: The name of the wheel file. :param bool validate_order: Check whether compressed tag set components are in sorted order. :raises InvalidWheelFilename: If the filename in question does not follow the :ref:`wheel specification `. >>> from packaging.utils import parse_wheel_filename >>> from packaging.tags import Tag >>> from packaging.version import Version >>> name, ver, build, tags = parse_wheel_filename("foo-1.0-py3-none-any.whl") >>> name 'foo' >>> ver == Version('1.0') True >>> tags == {Tag("py3", "none", "any")} True >>> not build True .. versionadded:: 26.1 The *validate_order* parameter. """ 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 = () tag_str = parts[-1] try: tags = parse_tag(tag_str, validate_order=validate_order) except UnsortedTagsError: raise InvalidWheelFilename( f"Invalid wheel filename (compressed tag set components must be in " f"sorted order per PEP 425): {filename!r}" ) from None return (name, version, build, tags) def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: """ This function takes the filename of a sdist file (as specified in the `Source distribution format`_ documentation), and parses it, returning a tuple of the normalized name and version as represented by an instance of :class:`~packaging.version.Version`. :param str filename: The name of the sdist file. :raises InvalidSdistFilename: If the filename does not end with an sdist extension (``.zip`` or ``.tar.gz``), or if it does not contain a dash separating the name and the version of the distribution. >>> 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 .. _Source distribution format: https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-name """ if filename.endswith(".tar.gz"): file_stem = filename[: -len(".tar.gz")] elif filename.endswith(".zip"): file_stem = filename[: -len(".zip")] else: raise InvalidSdistFilename( f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" f" {filename!r}" ) # We are requiring a PEP 440 version, which cannot contain dashes, # so we split on the last dash. name_part, sep, version_part = file_stem.rpartition("-") if not sep: raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") 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=1777059017.1073568 packaging-26.2/src/packaging/version.py0000644000000000000000000011274115172742311015100 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, normalize_pre, Version, _cmpkey """ from __future__ import annotations import re import sys import typing from typing import ( Any, Callable, Literal, NamedTuple, SupportsInt, Tuple, TypedDict, Union, ) if typing.TYPE_CHECKING: from typing_extensions import Self, Unpack if sys.version_info >= (3, 13): # pragma: no cover from warnings import deprecated as _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: Callable[[...], object]) -> object: @functools.wraps(func) def wrapper(*args: object, **kwargs: object) -> object: warnings.warn( message, category=DeprecationWarning, stacklevel=2, ) return func(*args, **kwargs) return wrapper return decorator _LETTER_NORMALIZATION = { "alpha": "a", "beta": "b", "c": "rc", "pre": "rc", "preview": "rc", "rev": "post", "r": "post", } __all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "normalize_pre", "parse"] def __dir__() -> list[str]: return __all__ LocalType = Tuple[Union[int, str], ...] CmpLocalType = Tuple[Tuple[int, str], ...] CmpSuffix = Tuple[int, int, int, int, int, int] CmpKey = Union[ Tuple[int, Tuple[int, ...], CmpSuffix], Tuple[int, Tuple[int, ...], CmpSuffix, CmpLocalType], ] VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] class _VersionReplace(TypedDict, total=False): epoch: int | None release: tuple[int, ...] | None pre: tuple[str, int] | None post: int | None dev: int | None local: str | None def normalize_pre(letter: str, /) -> str: """Normalize the pre-release segment of a version string. Returns a lowercase version of the string if not a known pre-release identifier. >>> normalize_pre('alpha') 'a' >>> normalize_pre('BETA') 'b' >>> normalize_pre('rc') 'rc' :param letter: .. versionadded:: 26.1 """ letter = letter.lower() return _LETTER_NORMALIZATION.get(letter, letter) def parse(version: str) -> Version: """Parse the given version string. This is identical to the :class:`Version` constructor. >>> parse('1.0.dev1') :param version: The version string to parse. :raises InvalidVersion: When the version string is not a valid version. """ return Version(version) class InvalidVersion(ValueError): """Raised when a version string is not a valid version. >>> Version("invalid") Traceback (most recent call last): ... packaging.version.InvalidVersion: Invalid version: 'invalid' """ class _BaseVersion: __slots__ = () # This can also be a normal member (see the packaging_legacy package); # we are just requiring it to be readable. Actually defining a property # has runtime effect on subclasses, so it's typing only. if typing.TYPE_CHECKING: @property def _key(self) -> tuple[Any, ...]: ... def __hash__(self) -> int: return hash(self._key) # Please keep the duplicated `isinstance` check # in the six comparisons hereunder # unless you find a way to avoid adding overhead function calls. def __lt__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key < other._key def __le__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key <= other._key def __eq__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key == other._key def __ge__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key >= other._key def __gt__(self, other: _BaseVersion) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key > other._key def __ne__(self, other: object) -> bool: if not isinstance(other, _BaseVersion): return NotImplemented return self._key != other._key # Deliberately not anchored to the start and end of the string, to make it # easier for 3rd party code to reuse # Note that ++ doesn't behave identically on CPython and PyPy, so not using it here _VERSION_PATTERN = r""" v?+ # optional leading v (?a: (?:(?P[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]+)?
        )?+
    )
    (?a:\+
        (?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.

.. versionchanged:: 26.0

   The regex now uses possessive qualifiers on Python 3.11 if they are
   supported (CPython 3.11.5+, PyPy 3.11.13+).

:meta hide-value:
"""


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

# Fast path: If a version has only digits and dots then we
# can skip the regex and parse it as a release segment
_SIMPLE_VERSION_INDICATORS = frozenset(".0123456789")


def _validate_epoch(value: object, /) -> int:
    epoch = value or 0
    if isinstance(epoch, int) and epoch >= 0:
        return epoch
    msg = f"epoch must be non-negative integer, got {epoch}"
    raise InvalidVersion(msg)


def _validate_release(value: object, /) -> tuple[int, ...]:
    release = (0,) if value is None else value
    if (
        isinstance(release, tuple)
        and len(release) > 0
        and all(isinstance(i, int) and i >= 0 for i in release)
    ):
        return release
    msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
    raise InvalidVersion(msg)


def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
    if value is None:
        return value
    if isinstance(value, tuple) and len(value) == 2:
        letter, number = value
        letter = normalize_pre(letter)
        if letter in {"a", "b", "rc"} and isinstance(number, int) and number >= 0:
            # type checkers can't infer the Literal type here on letter
            return (letter, number)  # type: ignore[return-value]
    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
    raise InvalidVersion(msg)


def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
    if value is None:
        return value
    if isinstance(value, int) and value >= 0:
        return ("post", value)
    msg = f"post must be non-negative integer, got {value}"
    raise InvalidVersion(msg)


def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
    if value is None:
        return value
    if isinstance(value, int) and value >= 0:
        return ("dev", value)
    msg = f"dev must be non-negative integer, got {value}"
    raise InvalidVersion(msg)


def _validate_local(value: object, /) -> LocalType | None:
    if value is None:
        return value
    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
        return _parse_local_version(value)
    msg = f"local must be a valid version string, got {value!r}"
    raise InvalidVersion(msg)


# Backward compatibility for internals before 26.0. Do not use.
class _Version(NamedTuple):
    epoch: int
    release: tuple[int, ...]
    dev: tuple[Literal["dev"], int] | None
    pre: tuple[Literal["a", "b", "rc"], int] | None
    post: tuple[Literal["post"], int] | None
    local: LocalType | None


class Version(_BaseVersion):
    """This class abstracts handling of a project's versions.

    A :class:`Version` instance is comparison aware and can be compared and
    sorted using the standard Python interfaces.

    >>> v1 = Version("1.0a5")
    >>> v2 = Version("1.0")
    >>> v1
    
    >>> v2
    
    >>> v1 < v2
    True
    >>> v1 == v2
    False
    >>> v1 > v2
    False
    >>> v1 >= v2
    False
    >>> v1 <= v2
    True

    :class:`Version` is immutable; use :meth:`__replace__` to change
    part of a version.

    Instances are safe to serialize with :mod:`pickle`. They use a stable
    format so the same pickle can be loaded in future packaging releases.

    .. versionchanged:: 26.2

        Added a stable pickle format. Pickles created with packaging 26.2+ can
        be unpickled with future releases.  Backward compatibility with pickles
        from packaging < 26.2 is supported but may be removed in a future
        release.
    """

    __slots__ = (
        "_dev",
        "_epoch",
        "_hash_cache",
        "_key_cache",
        "_local",
        "_post",
        "_pre",
        "_release",
    )
    __match_args__ = ("_str",)
    """
    Pattern matching is supported on Python 3.10+.

    .. versionadded:: 26.0

    :meta hide-value:
    """

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

    _epoch: int
    _release: tuple[int, ...]
    _dev: tuple[Literal["dev"], int] | None
    _pre: tuple[Literal["a", "b", "rc"], int] | None
    _post: tuple[Literal["post"], int] | None
    _local: LocalType | None

    _hash_cache: int | None
    _key_cache: CmpKey | None

    def __init__(self, version: str) -> None:
        """Initialize a Version object.

        :param version:
            The string representation of a version which will be parsed and normalized
            before use.
        :raises InvalidVersion:
            If the ``version`` does not conform to PEP 440 in any way then this
            exception will be raised.
        """
        if _SIMPLE_VERSION_INDICATORS.issuperset(version):
            try:
                self._release = tuple(map(int, version.split(".")))
            except ValueError:
                # Empty parts (from "1..2", ".1", etc.) are invalid versions.
                # Any other ValueError (e.g. int str-digits limit) should
                # propagate to the caller.
                if "" in version.split("."):
                    raise InvalidVersion(f"Invalid version: {version!r}") from None
                # TODO: remove "no cover" when Python 3.9 is dropped.
                raise  # pragma: no cover

            self._epoch = 0
            self._pre = None
            self._post = None
            self._dev = None
            self._local = None
            self._key_cache = None
            self._hash_cache = None
            return

        # Validate the version and parse it into pieces
        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(".")))
        # We can type ignore the assignments below because the regex guarantees
        # the correct strings
        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))  # type: ignore[assignment]
        self._post = _parse_letter_version(  # type: ignore[assignment]
            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
        )
        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))  # type: ignore[assignment]
        self._local = _parse_local_version(match.group("local"))

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

    @classmethod
    def from_parts(
        cls,
        *,
        epoch: int = 0,
        release: tuple[int, ...],
        pre: tuple[str, int] | None = None,
        post: int | None = None,
        dev: int | None = None,
        local: str | None = None,
    ) -> Self:
        """
        Return a new version composed of the various parts.

        This allows you to build a version without going though a string and
        running a regular expression. It normalizes pre-release strings. The
        ``release=`` keyword argument is required.

        >>> Version.from_parts(release=(1,2,3))
        
        >>> Version.from_parts(release=(0,1,0), pre=("b", 1))
        

        :param epoch:
        :param release: This version tuple is required

        .. versionadded:: 26.1
        """
        _epoch = _validate_epoch(epoch)
        _release = _validate_release(release)
        _pre = _validate_pre(pre) if pre is not None else None
        _post = _validate_post(post) if post is not None else None
        _dev = _validate_dev(dev) if dev is not None else None
        _local = _validate_local(local) if local is not None else None

        new_version = cls.__new__(cls)
        new_version._key_cache = None
        new_version._hash_cache = None
        new_version._epoch = _epoch
        new_version._release = _release
        new_version._pre = _pre
        new_version._post = _post
        new_version._dev = _dev
        new_version._local = _local

        return new_version

    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
        """
        __replace__(*, epoch=..., release=..., pre=..., post=..., dev=..., local=...)

        Return a new version with parts replaced.

        This returns a new version (unless no parts were changed). The
        pre-release is normalized. Setting a value to ``None`` clears it.

        >>> v = Version("1.2.3")
        >>> v.__replace__(pre=("a", 1))
        

        :param int | None epoch:
        :param tuple[int, ...] | None release:
        :param tuple[str, int] | None pre:
        :param int | None post:
        :param int | None dev:
        :param str | None local:

        .. versionadded:: 26.0
        .. versionchanged:: 26.1

           The pre-release portion is now normalized.
        """
        epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
        release = (
            _validate_release(kwargs["release"])
            if "release" in kwargs
            else self._release
        )
        pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
        post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
        dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
        local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local

        if (
            epoch == self._epoch
            and release == self._release
            and pre == self._pre
            and post == self._post
            and dev == self._dev
            and local == self._local
        ):
            return self

        new_version = self.__class__.__new__(self.__class__)
        new_version._key_cache = None
        new_version._hash_cache = None
        new_version._epoch = epoch
        new_version._release = release
        new_version._pre = pre
        new_version._post = post
        new_version._dev = dev
        new_version._local = local

        return new_version

    @property
    def _key(self) -> CmpKey:
        if self._key_cache is None:
            self._key_cache = _cmpkey(
                self._epoch,
                self._release,
                self._pre,
                self._post,
                self._dev,
                self._local,
            )
        return self._key_cache

    # __hash__ must be defined when __eq__ is overridden,
    # otherwise Python sets __hash__ to None.
    def __hash__(self) -> int:
        if (cached_hash := self._hash_cache) is not None:
            return cached_hash

        if (key := self._key_cache) is None:
            self._key_cache = key = _cmpkey(
                self._epoch,
                self._release,
                self._pre,
                self._post,
                self._dev,
                self._local,
            )
        self._hash_cache = cached_hash = hash(key)
        return cached_hash

    # Override comparison methods to use direct _key_cache access
    # This is faster than property access, especially before Python 3.12
    def __lt__(self, other: _BaseVersion) -> bool:
        if isinstance(other, Version):
            if self._key_cache is None:
                self._key_cache = _cmpkey(
                    self._epoch,
                    self._release,
                    self._pre,
                    self._post,
                    self._dev,
                    self._local,
                )
            if other._key_cache is None:
                other._key_cache = _cmpkey(
                    other._epoch,
                    other._release,
                    other._pre,
                    other._post,
                    other._dev,
                    other._local,
                )
            return self._key_cache < other._key_cache

        if not isinstance(other, _BaseVersion):
            return NotImplemented

        return super().__lt__(other)

    def __le__(self, other: _BaseVersion) -> bool:
        if isinstance(other, Version):
            if self._key_cache is None:
                self._key_cache = _cmpkey(
                    self._epoch,
                    self._release,
                    self._pre,
                    self._post,
                    self._dev,
                    self._local,
                )
            if other._key_cache is None:
                other._key_cache = _cmpkey(
                    other._epoch,
                    other._release,
                    other._pre,
                    other._post,
                    other._dev,
                    other._local,
                )
            return self._key_cache <= other._key_cache

        if not isinstance(other, _BaseVersion):
            return NotImplemented

        return super().__le__(other)

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Version):
            if self._key_cache is None:
                self._key_cache = _cmpkey(
                    self._epoch,
                    self._release,
                    self._pre,
                    self._post,
                    self._dev,
                    self._local,
                )
            if other._key_cache is None:
                other._key_cache = _cmpkey(
                    other._epoch,
                    other._release,
                    other._pre,
                    other._post,
                    other._dev,
                    other._local,
                )
            return self._key_cache == other._key_cache

        if not isinstance(other, _BaseVersion):
            return NotImplemented

        return super().__eq__(other)

    def __ge__(self, other: _BaseVersion) -> bool:
        if isinstance(other, Version):
            if self._key_cache is None:
                self._key_cache = _cmpkey(
                    self._epoch,
                    self._release,
                    self._pre,
                    self._post,
                    self._dev,
                    self._local,
                )
            if other._key_cache is None:
                other._key_cache = _cmpkey(
                    other._epoch,
                    other._release,
                    other._pre,
                    other._post,
                    other._dev,
                    other._local,
                )
            return self._key_cache >= other._key_cache

        if not isinstance(other, _BaseVersion):
            return NotImplemented

        return super().__ge__(other)

    def __gt__(self, other: _BaseVersion) -> bool:
        if isinstance(other, Version):
            if self._key_cache is None:
                self._key_cache = _cmpkey(
                    self._epoch,
                    self._release,
                    self._pre,
                    self._post,
                    self._dev,
                    self._local,
                )
            if other._key_cache is None:
                other._key_cache = _cmpkey(
                    other._epoch,
                    other._release,
                    other._pre,
                    other._post,
                    other._dev,
                    other._local,
                )
            return self._key_cache > other._key_cache

        if not isinstance(other, _BaseVersion):
            return NotImplemented

        return super().__gt__(other)

    def __ne__(self, other: object) -> bool:
        if isinstance(other, Version):
            if self._key_cache is None:
                self._key_cache = _cmpkey(
                    self._epoch,
                    self._release,
                    self._pre,
                    self._post,
                    self._dev,
                    self._local,
                )
            if other._key_cache is None:
                other._key_cache = _cmpkey(
                    other._epoch,
                    other._release,
                    other._pre,
                    other._post,
                    other._dev,
                    other._local,
                )
            return self._key_cache != other._key_cache

        if not isinstance(other, _BaseVersion):
            return NotImplemented

        return super().__ne__(other)

    def __getstate__(
        self,
    ) -> tuple[
        int,
        tuple[int, ...],
        tuple[str, int] | None,
        tuple[str, int] | None,
        tuple[str, int] | None,
        LocalType | None,
    ]:
        # Return state as a 6-item tuple for compactness:
        #   (epoch, release, pre, post, dev, local)
        # Cache members are excluded and will be recomputed on demand
        return (
            self._epoch,
            self._release,
            self._pre,
            self._post,
            self._dev,
            self._local,
        )

    def __setstate__(self, state: object) -> None:
        # Always discard cached values — they may contain stale references
        # (e.g. packaging._structures.InfinityType from pre-26.1 pickles)
        # and will be recomputed on demand from the core fields above.
        self._key_cache = None
        self._hash_cache = None

        if isinstance(state, tuple):
            if len(state) == 6:
                # New format (26.2+): (epoch, release, pre, post, dev, local)
                (
                    self._epoch,
                    self._release,
                    self._pre,
                    self._post,
                    self._dev,
                    self._local,
                ) = state
                return
            if len(state) == 2:
                # Format (packaging 26.0-26.1): (None, {slot: value}).
                _, slot_dict = state
                if isinstance(slot_dict, dict):
                    self._epoch = slot_dict["_epoch"]
                    self._release = slot_dict["_release"]
                    self._pre = slot_dict.get("_pre")
                    self._post = slot_dict.get("_post")
                    self._dev = slot_dict.get("_dev")
                    self._local = slot_dict.get("_local")
                    return
        if isinstance(state, dict):
            # Old format (packaging <= 25.x, no __slots__): state is a plain
            # dict with "_version" (_Version NamedTuple) and "_key" entries.
            version_nt = state.get("_version")
            if version_nt is not None:
                self._epoch = version_nt.epoch
                self._release = version_nt.release
                self._pre = version_nt.pre
                self._post = version_nt.post
                self._dev = version_nt.dev
                self._local = version_nt.local
                return

        raise TypeError(f"Cannot restore Version from {state!r}")

    @property
    @_deprecated("Version._version is private and will be removed soon")
    def _version(self) -> _Version:
        return _Version(
            self._epoch, self._release, self._dev, self._pre, self._post, self._local
        )

    @_version.setter
    @_deprecated("Version._version is private and will be removed soon")
    def _version(self, value: _Version) -> None:
        self._epoch = value.epoch
        self._release = value.release
        self._dev = value.dev
        self._pre = value.pre
        self._post = value.post
        self._local = value.local
        self._key_cache = None
        self._hash_cache = None

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

        >>> Version('1.0.0')
        
        """
        return f"<{self.__class__.__name__}({str(self)!r})>"

    def __str__(self) -> str:
        """A string representation of the version that can be round-tripped.

        >>> str(Version("1.0a5"))
        '1.0a5'
        """
        # This is a hot function, so not calling self.base_version
        version = ".".join(map(str, self.release))

        # Epoch
        if self.epoch:
            version = f"{self.epoch}!{version}"

        # Pre-release
        if self.pre is not None:
            version += "".join(map(str, self.pre))

        # Post-release
        if self.post is not None:
            version += f".post{self.post}"

        # Development release
        if self.dev is not None:
            version += f".dev{self.dev}"

        # Local version segment
        if self.local is not None:
            version += f"+{self.local}"

        return version

    @property
    def _str(self) -> str:
        """Internal property for match_args"""
        return str(self)

    @property
    def epoch(self) -> int:
        """The epoch of the version.

        >>> Version("2.0.0").epoch
        0
        >>> Version("1!2.0.0").epoch
        1
        """
        return self._epoch

    @property
    def release(self) -> tuple[int, ...]:
        """The components of the "release" segment of the version.

        >>> Version("1.2.3").release
        (1, 2, 3)
        >>> Version("2.0.0").release
        (2, 0, 0)
        >>> Version("1!2.0.0.post0").release
        (2, 0, 0)

        Includes trailing zeroes but not the epoch or any pre-release / development /
        post-release suffixes.
        """
        return self._release

    @property
    def pre(self) -> tuple[Literal["a", "b", "rc"], int] | None:
        """The pre-release segment of the version.

        >>> print(Version("1.2.3").pre)
        None
        >>> Version("1.2.3a1").pre
        ('a', 1)
        >>> Version("1.2.3b1").pre
        ('b', 1)
        >>> Version("1.2.3rc1").pre
        ('rc', 1)
        """
        return self._pre

    @property
    def post(self) -> int | None:
        """The post-release number of the version.

        >>> print(Version("1.2.3").post)
        None
        >>> Version("1.2.3.post1").post
        1
        """
        return self._post[1] if self._post else None

    @property
    def dev(self) -> int | None:
        """The development number of the version.

        >>> print(Version("1.2.3").dev)
        None
        >>> Version("1.2.3.dev1").dev
        1
        """
        return self._dev[1] if self._dev else None

    @property
    def local(self) -> str | None:
        """The local version segment of the version.

        >>> print(Version("1.2.3").local)
        None
        >>> Version("1.2.3+abc").local
        'abc'
        """
        if self._local:
            return ".".join(str(x) for x in self._local)
        else:
            return None

    @property
    def public(self) -> str:
        """The public portion of the version.

        This returns a string. If you want a :class:`Version` again and care
        about performance, use ``v.__replace__(local=None)`` instead.

        >>> Version("1.2.3").public
        '1.2.3'
        >>> Version("1.2.3+abc").public
        '1.2.3'
        >>> Version("1!1.2.3dev1+abc").public
        '1!1.2.3.dev1'
        """
        return str(self).split("+", 1)[0]

    @property
    def base_version(self) -> str:
        """The "base version" of the version.

        This returns a string. If you want a :class:`Version` again and care
        about performance, use
        ``v.__replace__(pre=None, post=None, dev=None, local=None)`` instead.

        >>> Version("1.2.3").base_version
        '1.2.3'
        >>> Version("1.2.3+abc").base_version
        '1.2.3'
        >>> Version("1!1.2.3dev1+abc").base_version
        '1!1.2.3'

        The "base version" is the public version of the project without any pre or post
        release markers.
        """
        release_segment = ".".join(map(str, self.release))
        return f"{self.epoch}!{release_segment}" if self.epoch else release_segment

    @property
    def is_prerelease(self) -> bool:
        """Whether this version is a pre-release.

        >>> Version("1.2.3").is_prerelease
        False
        >>> Version("1.2.3a1").is_prerelease
        True
        >>> Version("1.2.3b1").is_prerelease
        True
        >>> Version("1.2.3rc1").is_prerelease
        True
        >>> Version("1.2.3dev1").is_prerelease
        True
        """
        return self.dev is not None or self.pre is not None

    @property
    def is_postrelease(self) -> bool:
        """Whether this version is a post-release.

        >>> Version("1.2.3").is_postrelease
        False
        >>> Version("1.2.3.post1").is_postrelease
        True
        """
        return self.post is not None

    @property
    def is_devrelease(self) -> bool:
        """Whether this version is a development release.

        >>> Version("1.2.3").is_devrelease
        False
        >>> Version("1.2.3.dev1").is_devrelease
        True
        """
        return self.dev is not None

    @property
    def major(self) -> int:
        """The first item of :attr:`release` or ``0`` if unavailable.

        >>> Version("1.2.3").major
        1
        """
        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


# Sort ranks for pre-release: dev-only < a < b < rc < stable (no pre-release).
_PRE_RANK = {"a": 0, "b": 1, "rc": 2}
_PRE_RANK_DEV_ONLY = -1  # sorts before a(0)
_PRE_RANK_STABLE = 3  # sorts after rc(2)

# In local version segments, strings sort before ints per PEP 440.
_LOCAL_STR_RANK = -1  # sorts before all non-negative ints

# Pre-computed suffix for stable releases (no pre, post, or dev segments).
# See _cmpkey() for the suffix layout.
_STABLE_SUFFIX = (_PRE_RANK_STABLE, 0, 0, 0, 1, 0)


def _cmpkey(
    epoch: int,
    release: tuple[int, ...],
    pre: tuple[str, int] | None,
    post: tuple[str, int] | None,
    dev: tuple[str, int] | None,
    local: LocalType | None,
) -> CmpKey:
    """Build a comparison key for PEP 440 ordering.

    Returns ``(epoch, release, suffix)`` or
    ``(epoch, release, suffix, local)`` so that plain tuple
    comparison gives the correct order.

    Trailing zeros are stripped from the release so that ``1.0.0 == 1``.

    The suffix is a flat 6-int tuple that encodes pre/post/dev:
    ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``

    pre_rank: dev-only=-1, a=0, b=1, rc=2, no-pre=3
        Dev-only releases (no pre or post) get -1 so they sort before
        any alpha/beta/rc.  Releases without a pre-release tag get 3
        so they sort after rc.
    post_rank: no-post=0, post=1
        Releases without a post segment sort before those with one.
    dev_rank: dev=0, no-dev=1
        Releases without a dev segment sort after those with one.

    Local segments use ``(n, "")`` for ints and ``(-1, s)`` for strings,
    following PEP 440: strings sort before ints, strings compare
    lexicographically, ints compare numerically, and shorter segments
    sort before longer when prefixes match.  Versions without a local
    segment sort before those with one (3-tuple < 4-tuple).

    >>> _cmpkey(0, (1, 0, 0), None, None, None, None)
    (0, (1,), (3, 0, 0, 0, 1, 0))
    >>> _cmpkey(0, (1,), ("a", 1), None, None, None)
    (0, (1,), (0, 1, 0, 0, 1, 0))
    >>> _cmpkey(0, (1,), None, None, None, ("ubuntu", 1))
    (0, (1,), (3, 0, 0, 0, 1, 0), ((-1, 'ubuntu'), (1, '')))
    """
    # Strip trailing zeros: 1.0.0 compares equal to 1.
    len_release = len(release)
    i = len_release
    while i and release[i - 1] == 0:
        i -= 1
    trimmed = release if i == len_release else release[:i]

    # Fast path: stable release with no local segment.
    if pre is None and post is None and dev is None and local is None:
        return epoch, trimmed, _STABLE_SUFFIX

    if pre is None and post is None and dev is not None:
        # dev-only (e.g. 1.0.dev1) sorts before all pre-releases.
        pre_rank, pre_n = _PRE_RANK_DEV_ONLY, 0
    elif pre is None:
        pre_rank, pre_n = _PRE_RANK_STABLE, 0
    else:
        pre_rank, pre_n = _PRE_RANK[pre[0]], pre[1]

    post_rank = 0 if post is None else 1
    post_n = 0 if post is None else post[1]

    dev_rank = 1 if dev is None else 0
    dev_n = 0 if dev is None else dev[1]

    suffix = (pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)

    if local is None:
        return epoch, trimmed, suffix

    cmp_local: CmpLocalType = tuple(
        (seg, "") if isinstance(seg, int) else (_LOCAL_STR_RANK, seg) for seg in local
    )
    return epoch, trimmed, suffix, cmp_local
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1083567
packaging-26.2/tests/__init__.py0000644000000000000000000000026415172742311013575 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=1777059017.1087763
packaging-26.2/tests/conftest.py0000644000000000000000000000043515172742311013663 0ustar00from __future__ import annotations

import sysconfig


def pytest_report_header() -> str:
    lines = [f"sysconfig platform: {sysconfig.get_platform()}"]
    if sysconfig.get_config_var("Py_GIL_DISABLED"):
        lines.append("free-threaded Python build")
    return "\n".join(lines)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1087763
packaging-26.2/tests/manylinux/build.sh0000755000000000000000000000340215172742311015143 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
././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-armv7l-armel0000755000000000000000000000006415172742311020170 0ustar00ELF(44 	(././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-armv7l-armhf0000755000000000000000000000006415172742311020165 0ustar00ELF(44 	(././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-invalid-class0000755000000000000000000000006415172742311020413 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-invalid-data0000755000000000000000000000006415172742311020217 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-invalid-magic0000755000000000000000000000006415172742311020366 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-s390x-s390x0000644000000000000000000000010015172742311017420 0ustar00ELFP@p@8	@././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-too-short0000644000000000000000000000005015172742311017610 0ustar00ELF401././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-x86_64-amd640000644000000000000000000000010015172742311017515 0ustar00ELF>p@H1@8@././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-x86_64-i3860000755000000000000000000000006415172742311017307 0ustar00ELF4014 (././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/manylinux/hello-world-x86_64-x320000755000000000000000000000006415172742311017232 0ustar00ELF>p4<14 (././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1777059017.108903
packaging-26.2/tests/metadata/everything.metadata0000644000000000000000000000347115172742311017135 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=1777059017.1093035
packaging-26.2/tests/musllinux/glibc-x86_640000755000000000000000000000200015172742311015454 0ustar00ELF>@9@8
@@@@     XX-==X`-==888  XXXDDStd888  Ptd   DDQtdRtd-==HH/lib64/ld-linux-x86-64.so.2GNUGNUKWz7StyxyʍGNUemQ '././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1093035
packaging-26.2/tests/musllinux/musl-aarch640000755000000000000000000000200015172742311015646 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=1777059017.1093035
packaging-26.2/tests/musllinux/musl-i3860000755000000000000000000000200015172742311015107 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=1777059017.1093566
packaging-26.2/tests/musllinux/musl-x86_640000755000000000000000000000200015172742311015354 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=1777059017.1093566
packaging-26.2/tests/property/__init__.py0000644000000000000000000000000015172742311015445 0ustar00././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/strategies.py0000644000000000000000000001174515172742311016102 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 hypothesis import settings
from hypothesis import strategies as st

from packaging.specifiers import SpecifierSet
from packaging.version import Version

SETTINGS = settings(max_examples=300, deadline=None)

# PEP 440 versions covering the major forms.
VERSION_POOL = [
    Version("0"),
    Version("0.0"),
    Version("0.1"),
    Version("1.0"),
    Version("1.0.0"),
    Version("1.2.3"),
    Version("2.0"),
    Version("3.0.0.0"),
    Version("10.20.30"),
    Version("1.0a0"),
    Version("1.0a1"),
    Version("1.0b2"),
    Version("1.0rc1"),
    Version("1.0.dev0"),
    Version("1.0.dev1"),
    Version("1.0.post0"),
    Version("1.0.post1"),
    Version("1.0a1.post1"),
    Version("1.0a1.dev1"),
    Version("1.0.post1.dev1"),
    Version("1.0a1.post1.dev1"),
    Version("1.0+local"),
    Version("1.0+abc.1"),
    Version("1.0+abc.def"),
    Version("1!1.0"),
    Version("1!1.0a1"),
    Version("2!0.1"),
]

small_ints = st.integers(min_value=0, max_value=20)
pre_tags = st.sampled_from(["a", "b", "rc"])
ops = st.sampled_from([">=", "<=", ">", "<", "==", "!="])

release_segment = st.lists(small_ints, min_size=1, max_size=4).map(
    lambda parts: ".".join(str(p) for p in parts)
)

local_numeric = st.integers(min_value=0, max_value=100).map(str)
local_text = st.sampled_from(["abc", "ubuntu", "local", "patch", "dev"])
local_segment = st.one_of(local_numeric, local_text)
local_labels = st.lists(local_segment, min_size=1, max_size=3).map(".".join)


@st.composite
def pep440_versions(
    draw: st.DrawFn,
    *,
    include_local: bool = True,
    min_segments: int = 1,
) -> Version:
    """Generate a random PEP 440 version."""
    epoch = draw(st.sampled_from([None, 0, 1]))
    num_segments = draw(st.integers(min_value=min_segments, max_value=4))
    release = tuple(draw(small_ints) for _ in range(num_segments))

    pre = None
    if draw(st.booleans()):
        pre = (draw(pre_tags), draw(small_ints))

    post: int | None = None
    if draw(st.booleans()):
        post = draw(small_ints)

    dev: int | None = None
    if draw(st.booleans()):
        dev = draw(small_ints)

    local: str | None = None
    if include_local and draw(st.booleans()):
        local = draw(local_labels)

    parts: list[str] = []
    if epoch is not None and epoch != 0:
        parts.append(f"{epoch}!")
    parts.append(".".join(str(s) for s in release))
    if pre is not None:
        parts.append(f"{pre[0]}{pre[1]}")
    if post is not None:
        parts.append(f".post{post}")
    if dev is not None:
        parts.append(f".dev{dev}")
    if local is not None:
        parts.append(f"+{local}")

    return Version("".join(parts))


@st.composite
def nonlocal_versions(draw: st.DrawFn) -> Version:
    """Generate a PEP 440 version without a local segment."""
    v: Version = draw(pep440_versions(include_local=False))
    return v


@st.composite
def release_versions(draw: st.DrawFn, *, min_segments: int = 1) -> Version:
    """Generate a final release version (no pre/post/dev/local)."""
    num_segments = draw(st.integers(min_value=min_segments, max_value=4))
    release = tuple(draw(small_ints) for _ in range(num_segments))
    return Version(".".join(str(s) for s in release))


@st.composite
def multi_segment_versions(draw: st.DrawFn) -> Version:
    """Generate a version with at least 2 release segments (for ~=)."""
    v: Version = draw(pep440_versions(include_local=False, min_segments=2))
    return v


@st.composite
def versions_with_local(draw: st.DrawFn) -> Version:
    """Generate a PEP 440 version that always has a local segment."""
    base = draw(pep440_versions(include_local=False))
    local_part = draw(local_labels)
    return Version(f"{base}+{local_part}")


@st.composite
def specifier_sets(draw: st.DrawFn) -> SpecifierSet:
    """Generate a random SpecifierSet from common operator/version pairs."""
    num = draw(st.integers(min_value=1, max_value=3))
    parts: list[str] = []
    for _ in range(num):
        op = draw(ops)
        major = draw(small_ints)
        minor = draw(small_ints)
        parts.append(f"{op}{major}.{minor}")
    return SpecifierSet(",".join(parts))


@st.composite
def related_version_triple(
    draw: st.DrawFn,
) -> tuple[Version, Version, Version]:
    """Three versions sharing a release segment with different suffixes."""
    num_segments = draw(st.integers(min_value=1, max_value=3))
    release = tuple(draw(small_ints) for _ in range(num_segments))
    base = ".".join(str(s) for s in release)

    def _build(draw: st.DrawFn) -> Version:
        pre = draw(st.sampled_from([None, None, "a0", "b1", "rc1"]))
        post = draw(st.sampled_from([None, None, ".post0", ".post1"]))
        dev = draw(st.sampled_from([None, None, None, ".dev0"]))
        return Version(f"{base}{pre or ''}{post or ''}{dev or ''}")

    return (_build(draw), _build(draw), _build(draw))
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/test_specifier_comparison.py0000644000000000000000000007644515172742311021202 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 hypothesis import assume, given
from hypothesis import strategies as st

from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet
from packaging.version import Version
from tests.property.strategies import (
    SETTINGS,
    local_labels,
    nonlocal_versions,
    pre_tags,
    small_ints,
    specifier_sets,
    versions_with_local,
)

pytestmark = pytest.mark.property


class TestInclusiveOrderedComparison:
    """An inclusive ordered comparison clause includes a comparison operator and a
    version identifier, and will match any version where the comparison is correct
    based on the relative position of the candidate version and the specified
    version given the consistent ordering defined by the standard
    Version scheme.

    The inclusive ordered comparison operators are ``<=`` and ``>=``."""

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_greater_equal_matches_iff_ordering_holds(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """>=V matches candidate iff candidate (public) >= V."""
        spec = Specifier(f">={specifier_version}")
        pub = Version(str(candidate).split("+")[0]) if candidate.local else candidate
        assert spec.contains(candidate, prereleases=True) == (pub >= specifier_version)

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_less_equal_matches_iff_ordering_holds(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """<=V matches candidate iff candidate (public) <= V."""
        spec = Specifier(f"<={specifier_version}")
        pub = Version(str(candidate).split("+")[0]) if candidate.local else candidate
        assert spec.contains(candidate, prereleases=True) == (pub <= specifier_version)


class TestInclusiveOrderedComparisonZeroPadding:
    """As with version matching, the release segment is zero padded as necessary to
    ensure the release segments are compared with the same length."""

    @given(
        major=small_ints,
        minor=small_ints,
    )
    @SETTINGS
    def test_greater_equal_zero_padding(self, major: int, minor: int) -> None:
        """>=X.Y matches X.Y.0.0 because zero padding makes them equal."""
        spec = Specifier(f">={major}.{minor}")
        candidate = Version(f"{major}.{minor}.0.0")
        assert spec.contains(candidate, prereleases=True)

    @given(
        major=small_ints,
        minor=small_ints,
    )
    @SETTINGS
    def test_less_equal_zero_padding(self, major: int, minor: int) -> None:
        """<=X.Y matches X.Y.0.0 because zero padding makes them equal."""
        spec = Specifier(f"<={major}.{minor}")
        candidate = Version(f"{major}.{minor}.0.0")
        assert spec.contains(candidate, prereleases=True)

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_greater_equal_padded_and_unpadded_are_equivalent(
        self, major: int, minor: int
    ) -> None:
        """>=X.Y and >=X.Y.0 should accept the same set of versions."""
        spec_short = Specifier(f">={major}.{minor}")
        spec_long = Specifier(f">={major}.{minor}.0")
        # They are semantically equivalent for any candidate.
        candidate = Version(f"{major}.{minor}")
        assert spec_short.contains(candidate, prereleases=True) == spec_long.contains(
            candidate, prereleases=True
        )


class TestInclusiveOrderedComparisonLocalVersions:
    """Local version identifiers are NOT permitted in this version specifier."""

    @given(specifier_version=versions_with_local())
    @SETTINGS
    def test_greater_equal_with_local_spec_raises(
        self, specifier_version: Version
    ) -> None:
        """Creating >= with a local version in the spec should raise."""
        with pytest.raises(InvalidSpecifier):
            Specifier(f">={specifier_version}")

    @given(specifier_version=versions_with_local())
    @SETTINGS
    def test_less_equal_with_local_spec_raises(
        self, specifier_version: Version
    ) -> None:
        """Creating <= with a local version in the spec should raise."""
        with pytest.raises(InvalidSpecifier):
            Specifier(f"<={specifier_version}")

    @given(
        candidate=versions_with_local(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_greater_equal_strips_local_from_candidate(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """>=V compares against the public version of the candidate."""
        spec = Specifier(f">={specifier_version}")
        pub = Version(str(candidate).split("+")[0])
        assert spec.contains(candidate, prereleases=True) == (pub >= specifier_version)

    @given(
        candidate=versions_with_local(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_less_equal_strips_local_from_candidate(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """<=V compares against the public version of the candidate."""
        spec = Specifier(f"<={specifier_version}")
        pub = Version(str(candidate).split("+")[0])
        assert spec.contains(candidate, prereleases=True) == (pub <= specifier_version)


class TestExclusiveOrderedComparisonDefinition:
    """The exclusive ordered comparisons ``>`` and ``<`` are similar to the inclusive
    ordered comparisons in that they rely on the relative position of the candidate
    version and the specified version given the consistent ordering defined by the
    standard Version scheme. However, they specifically exclude pre-releases,
    post-releases, and local versions of the specified version.

    Implied: ordered comparisons must be monotonic with respect to version
    ordering. If candidate ``a`` matches ``>V`` and ``b > a`` then ``b``
    must also match ``>V``. Symmetrically for ``<``."""

    @given(specifier_version=nonlocal_versions())
    @SETTINGS
    def test_greater_than_excludes_spec_version_itself(
        self, specifier_version: Version
    ) -> None:
        """>V does not match V."""
        spec = Specifier(f">{specifier_version}")
        assert not spec.contains(specifier_version, prereleases=True)

    @given(specifier_version=nonlocal_versions())
    @SETTINGS
    def test_less_than_excludes_spec_version_itself(
        self, specifier_version: Version
    ) -> None:
        """ None:
        """>V only matches candidates that are strictly greater than V."""
        spec = Specifier(f">{specifier_version}")
        if spec.contains(candidate, prereleases=True):
            assert candidate > specifier_version

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_less_than_requires_candidate_strictly_less(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """V`` MUST NOT allow a post-release
    of the given version unless ``V`` itself is a post release. You may mandate
    that releases are later than a particular post release, including additional
    post releases, by using ``>V.postN``. For example, ``>1.7`` will allow
    ``1.7.1`` but not ``1.7.0.post1`` and ``>1.7.post2`` will allow ``1.7.1``
    and ``1.7.0.post3`` but not ``1.7.0``."""

    @given(
        specifier_version=nonlocal_versions(),
        post_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_greater_than_nonpost_excludes_post_of_itself(
        self, specifier_version: Version, post_num: int
    ) -> None:
        """>V (non-post) must not match V.postN."""
        assume(not specifier_version.is_postrelease)
        assume(not specifier_version.is_devrelease)
        postrelease_version = Version(f"{specifier_version}.post{post_num}")
        spec = Specifier(f">{specifier_version}")
        assert not spec.contains(postrelease_version, prereleases=True)

    def test_spec_example_gt_1_7(self) -> None:
        """>1.7 will allow 1.7.1 but not 1.7.0.post1."""
        spec = Specifier(">1.7")
        assert spec.contains("1.7.1", prereleases=True)
        assert not spec.contains("1.7.0.post1", prereleases=True)

    def test_spec_example_gt_1_7_post2(self) -> None:
        """>1.7.post2 will allow 1.7.1 and 1.7.0.post3 but not 1.7.0."""
        spec = Specifier(">1.7.post2")
        assert spec.contains("1.7.1", prereleases=True)
        assert spec.contains("1.7.0.post3", prereleases=True)
        assert not spec.contains("1.7.0", prereleases=True)

    @given(
        major=small_ints,
        minor=small_ints,
        pre=st.sampled_from([None, "a0", "b1", "rc1"]),
        post_n=st.integers(min_value=0, max_value=5),
        higher_post=st.integers(min_value=0, max_value=10),
    )
    @SETTINGS
    def test_greater_than_post_allows_higher_post(
        self,
        major: int,
        minor: int,
        pre: str | None,
        post_n: int,
        higher_post: int,
    ) -> None:
        """>V.postN allows V.postM where M > N."""
        assume(higher_post > post_n)
        base = f"{major}.{minor}{pre or ''}"
        spec = Specifier(f">{base}.post{post_n}")
        candidate = Version(f"{base}.post{higher_post}")
        assert spec.contains(candidate, prereleases=True)

    @given(
        specifier_version=nonlocal_versions(),
        bump=st.integers(min_value=1, max_value=5),
        post_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_greater_than_allows_post_of_later_release(
        self, specifier_version: Version, bump: int, post_num: int
    ) -> None:
        """>V allows (V+bump).postN since V+bump > V."""
        release = list(specifier_version.release)
        release[-1] += bump
        bumped = ".".join(str(s) for s in release)
        if specifier_version.epoch:
            bumped = f"{specifier_version.epoch}!{bumped}"
        candidate = Version(f"{bumped}.post{post_num}")
        spec = Specifier(f">{specifier_version}")
        assert spec.contains(candidate, prereleases=True)


class TestExclusiveGtLocalVersion:
    """The exclusive ordered comparison ``>V`` MUST NOT match a local version of
    the specified version."""

    @given(
        specifier_version=nonlocal_versions(),
        local_part=local_labels,
    )
    @SETTINGS
    def test_greater_than_excludes_local_of_spec_version(
        self, specifier_version: Version, local_part: str
    ) -> None:
        """>V must not match V+local."""
        local_ver = Version(f"{specifier_version}+{local_part}")
        spec = Specifier(f">{specifier_version}")
        assert not spec.contains(local_ver, prereleases=True)

    @given(
        specifier_version=nonlocal_versions(),
        bump=st.integers(min_value=1, max_value=5),
        local_part=local_labels,
    )
    @SETTINGS
    def test_greater_than_allows_local_of_later_version(
        self, specifier_version: Version, bump: int, local_part: str
    ) -> None:
        """>V allows (V+bump)+local since the public part is > V."""
        release = list(specifier_version.release)
        release[-1] += bump
        bumped = ".".join(str(s) for s in release)
        if specifier_version.epoch:
            bumped = f"{specifier_version.epoch}!{bumped}"
        candidate = Version(f"{bumped}+{local_part}")
        spec = Specifier(f">{specifier_version}")
        assert spec.contains(candidate, prereleases=True)


class TestExclusiveLtPreRelease:
    """The exclusive ordered comparison `` None:
        """= earliest_pre)
        assume(prerelease_version < specifier_version)
        spec = Specifier(f"<{specifier_version}")
        assert not spec.contains(prerelease_version, prereleases=True)

    @given(
        specifier_version=nonlocal_versions(),
        earlier_pre_tag=pre_tags,
        earlier_pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_less_than_prerelease_allows_earlier_prerelease(
        self,
        specifier_version: Version,
        earlier_pre_tag: str,
        earlier_pre_num: int,
    ) -> None:
        """ None:
        """= decrement)
        release[-1] -= decrement
        earlier = ".".join(str(s) for s in release)
        if specifier_version.epoch:
            earlier = f"{specifier_version.epoch}!{earlier}"
        candidate = Version(f"{earlier}{pre_tag}{pre_num}")
        spec = Specifier(f"<{specifier_version}")
        assert spec.contains(candidate, prereleases=True)

    def test_spec_example_lt_with_prerelease_spec(self) -> None:
        """<1.0rc1 allows 1.0a1 and 1.0b2 but not 1.0rc1 itself."""
        spec = Specifier("<1.0rc1")
        assert spec.contains("1.0a1", prereleases=True)
        assert spec.contains("1.0b2", prereleases=True)
        assert not spec.contains("1.0rc1", prereleases=True)

    def test_less_than_final_excludes_dev_of_same_base(self) -> None:
        """<1.0 should not match 1.0.dev0 (dev releases are pre-releases)."""
        spec = Specifier("<1.0")
        assert not spec.contains("1.0.dev0", prereleases=True)


class TestExclusiveOrderedComparisonZeroPadding:
    """As with version matching, the release segment is zero padded as necessary to
    ensure the release segments are compared with the same length."""

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_greater_than_zero_padded_equivalence(self, major: int, minor: int) -> None:
        """>X.Y and >X.Y.0 are semantically equivalent."""
        spec_short = Specifier(f">{major}.{minor}")
        spec_long = Specifier(f">{major}.{minor}.0")
        # They should agree on a version that is clearly higher.
        high = Version(f"{major}.{minor + 1}")
        assert spec_short.contains(high, prereleases=True) == spec_long.contains(
            high, prereleases=True
        )

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_less_than_zero_padded_equivalence(self, major: int, minor: int) -> None:
        """ 0 or minor > 0)
        spec_short = Specifier(f"<{major}.{minor}")
        spec_long = Specifier(f"<{major}.{minor}.0")
        # They should agree on a version that is clearly lower.
        low = Version("0.0.1") if major > 0 or minor > 1 else Version("0.0")
        assert spec_short.contains(low, prereleases=True) == spec_long.contains(
            low, prereleases=True
        )


class TestExclusiveOrderedComparisonLocalVersions:
    """Local version identifiers are NOT permitted in this version specifier."""

    @given(specifier_version=versions_with_local())
    @SETTINGS
    def test_greater_than_with_local_spec_raises(
        self, specifier_version: Version
    ) -> None:
        """Creating > with a local version in the spec should raise."""
        with pytest.raises(InvalidSpecifier):
            Specifier(f">{specifier_version}")

    @given(specifier_version=versions_with_local())
    @SETTINGS
    def test_less_than_with_local_spec_raises(self, specifier_version: Version) -> None:
        """Creating < with a local version in the spec should raise."""
        with pytest.raises(InvalidSpecifier):
            Specifier(f"<{specifier_version}")


class TestArbitraryEqualityDefinition:
    """Arbitrary equality comparisons are simple string equality operations which do
    not take into account any of the semantic information such as zero padding or
    local versions. The comparison MUST treat ASCII letters case-insensitively, e.g.
    by lowercasing, and is unspecified for non-ASCII text. This operator also does
    not support prefix matching as the ``==`` operator does.

    The primary use case for arbitrary equality is to allow for specifying
    a version which cannot otherwise be represented by this specification.
    This operator is special and acts as an escape hatch to allow someone
    using a tool which implements this specification to still install a
    legacy version which is otherwise incompatible with this
    specification."""

    @given(
        ver_str=st.sampled_from(
            ["1.0", "2.0.1", "foobar", "1.0a1", "1.0.post1", "1.0+local"]
        )
    )
    @SETTINGS
    def test_arbitrary_matches_exact_string(self, ver_str: str) -> None:
        """===X matches the string X."""
        spec = Specifier(f"==={ver_str}")
        assert spec.contains(ver_str, prereleases=True)

    @given(ver_str=st.sampled_from(["FooBar", "HELLO", "AbC.1", "Version1"]))
    @SETTINGS
    def test_arbitrary_case_insensitive(self, ver_str: str) -> None:
        """=== comparison is case-insensitive for ASCII."""
        spec = Specifier(f"==={ver_str}")
        assert spec.contains(ver_str.lower(), prereleases=True)
        assert spec.contains(ver_str.upper(), prereleases=True)

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_arbitrary_no_zero_padding(self, major: int, minor: int) -> None:
        """===X.Y does NOT match X.Y.0 (no zero padding semantics)."""
        spec = Specifier(f"==={major}.{minor}")
        padded = f"{major}.{minor}.0"
        # Only matches if the strings are literally equal (they are not).
        assert not spec.contains(padded, prereleases=True)

    @given(
        base=st.sampled_from(["1.0", "2.3", "0.1"]),
        suffix=st.sampled_from(["1", ".0", ".1", "a"]),
    )
    @SETTINGS
    def test_arbitrary_no_prefix_matching(self, base: str, suffix: str) -> None:
        """=== does not support prefix matching like == does."""
        spec = Specifier(f"==={base}")
        extended = f"{base}{suffix}"
        assume(extended.lower() != base.lower())
        assert not spec.contains(extended, prereleases=True)


class TestArbitraryEqualityFoobar:
    """An example would be ``===foobar`` which would match a version of ``foobar``."""

    def test_foobar_example(self) -> None:
        """===foobar matches foobar."""
        spec = Specifier("===foobar")
        assert spec.contains("foobar", prereleases=True)

    def test_foobar_case_insensitive(self) -> None:
        """===foobar matches FOOBAR (case-insensitive)."""
        spec = Specifier("===foobar")
        assert spec.contains("FOOBAR", prereleases=True)

    def test_foobar_does_not_match_other(self) -> None:
        """===foobar does not match barbaz."""
        spec = Specifier("===foobar")
        assert not spec.contains("barbaz", prereleases=True)


class TestArbitraryEqualityNoLocal:
    """This operator may also be used to explicitly require an unpatched version
    of a project such as ``===1.0`` which would not match for a version
    ``1.0+downstream1``."""

    def test_spec_example_1_0_no_downstream(self) -> None:
        """===1.0 does not match 1.0+downstream1."""
        spec = Specifier("===1.0")
        assert not spec.contains("1.0+downstream1", prereleases=True)

    @given(
        ver_str=st.sampled_from(["1.0", "2.0", "3.1.4"]),
        local=st.sampled_from(["downstream1", "ubuntu1", "local.1"]),
    )
    @SETTINGS
    def test_arbitrary_excludes_local_variants(self, ver_str: str, local: str) -> None:
        """===V does not match V+local."""
        spec = Specifier(f"==={ver_str}")
        assert not spec.contains(f"{ver_str}+{local}", prereleases=True)

    @given(ver_str=st.sampled_from(["1.0", "2.0", "3.1.4"]))
    @SETTINGS
    def test_arbitrary_matches_exact(self, ver_str: str) -> None:
        """===V does match V exactly."""
        spec = Specifier(f"==={ver_str}")
        assert spec.contains(ver_str, prereleases=True)


class TestPreReleaseImplicitExclusion:
    """Pre-releases of any kind, including developmental releases, are implicitly
    excluded from all version specifiers, unless they are already present
    on the system, explicitly requested by the user, or if the only available
    version that satisfies the version specifier is a pre-release.

    By default, dependency resolution tools SHOULD:

    * accept already installed pre-releases for all version specifiers
    * accept remotely available pre-releases for version specifiers where
      there is no final or post release that satisfies the version specifier
    * exclude all other pre-releases from consideration

    Dependency resolution tools SHOULD also allow users to request the
    following alternative behaviours:

    * accepting pre-releases for all version specifiers
    * excluding pre-releases for all version specifiers"""

    @given(
        major=st.integers(min_value=0, max_value=10),
        minor=st.integers(min_value=0, max_value=10),
        bump=st.integers(min_value=1, max_value=5),
        pre_tag=pre_tags,
        pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_pre_excluded_by_default_when_finals_exist(
        self, major: int, minor: int, bump: int, pre_tag: str, pre_num: int
    ) -> None:
        """A pre-release is excluded when a final release also matches."""
        specifier_version = Version(f"{major}.{minor}")
        # Create a pre-release of a *later* version so it satisfies >=specifier_version.
        later = Version(f"{major}.{minor + bump}")
        prerelease_version = Version(f"{major}.{minor + bump}{pre_tag}{pre_num}")
        spec = Specifier(f">={specifier_version}")
        # With both a final and pre-release available, default filtering
        # should exclude the pre-release.
        candidates = [str(later), str(prerelease_version)]
        filtered = list(spec.filter(candidates))
        assert str(later) in filtered
        assert str(prerelease_version) not in filtered

    @given(
        major=st.integers(min_value=0, max_value=10),
        minor=st.integers(min_value=0, max_value=10),
        bump=st.integers(min_value=1, max_value=5),
        pre_tag=pre_tags,
        pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_pre_included_when_explicitly_requested(
        self, major: int, minor: int, bump: int, pre_tag: str, pre_num: int
    ) -> None:
        """Pre-releases are included when prereleases=True."""
        specifier_version = Version(f"{major}.{minor}")
        prerelease_version = Version(f"{major}.{minor + bump}{pre_tag}{pre_num}")
        spec = Specifier(f">={specifier_version}")
        filtered = list(
            spec.filter(
                [str(specifier_version), str(prerelease_version)], prereleases=True
            )
        )
        assert str(prerelease_version) in filtered

    @given(
        major=st.integers(min_value=0, max_value=10),
        minor=st.integers(min_value=0, max_value=10),
        bump=st.integers(min_value=1, max_value=5),
        pre_tag=pre_tags,
        pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_pre_included_when_only_available(
        self, major: int, minor: int, bump: int, pre_tag: str, pre_num: int
    ) -> None:
        """Pre-releases are included if they are the only matching version."""
        specifier_version = Version(f"{major}.{minor}")
        prerelease_version = Version(f"{major}.{minor + bump}{pre_tag}{pre_num}")
        spec = Specifier(f">={specifier_version}")
        # Only the pre-release is available.
        filtered = list(spec.filter([str(prerelease_version)]))
        assert str(prerelease_version) in filtered

    @given(
        major=st.integers(min_value=0, max_value=10),
        minor=st.integers(min_value=0, max_value=10),
        bump=st.integers(min_value=1, max_value=5),
        pre_tag=pre_tags,
        pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_pre_excluded_when_explicitly_disabled(
        self, major: int, minor: int, bump: int, pre_tag: str, pre_num: int
    ) -> None:
        """Pre-releases are excluded when prereleases=False."""
        specifier_version = Version(f"{major}.{minor}")
        prerelease_version = Version(f"{major}.{minor + bump}{pre_tag}{pre_num}")
        spec = Specifier(f">={specifier_version}")
        filtered = list(
            spec.filter(
                [str(specifier_version), str(prerelease_version)], prereleases=False
            )
        )
        assert str(prerelease_version) not in filtered

    @given(version=nonlocal_versions())
    @SETTINGS
    def test_dev_release_is_also_prerelease(self, version: Version) -> None:
        """Dev releases are pre-releases and subject to the same exclusion."""
        assume(version.is_devrelease)
        assert version.is_prerelease

    @given(
        major=st.integers(min_value=0, max_value=10),
        minor=st.integers(min_value=0, max_value=10),
        bump=st.integers(min_value=1, max_value=5),
        pre_tag=pre_tags,
        pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_specifier_set_pre_fallback_when_no_finals(
        self, major: int, minor: int, bump: int, pre_tag: str, pre_num: int
    ) -> None:
        """SpecifierSet.filter with default prereleases returns
        pre-releases when no final release satisfies the specifier."""
        spec = SpecifierSet(f">={major}.{minor}")
        prerelease_version = Version(f"{major}.{minor + bump}{pre_tag}{pre_num}")
        filtered = list(spec.filter([str(prerelease_version)]))
        assert str(prerelease_version) in filtered

    @given(
        major=st.integers(min_value=0, max_value=10),
        minor=st.integers(min_value=0, max_value=10),
        bump=st.integers(min_value=1, max_value=5),
        pre_tag=pre_tags,
        pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_specifier_set_pre_excluded_by_default(
        self, major: int, minor: int, bump: int, pre_tag: str, pre_num: int
    ) -> None:
        """SpecifierSet.filter with default prereleases excludes
        pre-releases when a final release is also available."""
        later = Version(f"{major}.{minor + bump}")
        prerelease_version = Version(f"{major}.{minor + bump}{pre_tag}{pre_num}")
        spec = SpecifierSet(f">={major}.{minor}")
        filtered = list(spec.filter([str(later), str(prerelease_version)]))
        assert str(later) in filtered
        assert str(prerelease_version) not in filtered

    @given(
        spec=specifier_sets(),
        versions=st.lists(nonlocal_versions(), max_size=15),
    )
    @SETTINGS
    def test_prereleases_false_never_yields_prerelease(
        self, spec: SpecifierSet, versions: list[Version]
    ) -> None:
        """filter(vs, prereleases=False) never returns a pre-release."""
        strs = [str(version) for version in versions]
        filtered = list(spec.filter(strs, prereleases=False))
        for version_str in filtered:
            assert not Version(version_str).is_prerelease


class TestPostAndFinalReleasesAlwaysIncluded:
    """Post-releases and final releases receive no special treatment in version
    specifiers - they are always included unless explicitly excluded."""

    @given(version=nonlocal_versions())
    @SETTINGS
    def test_post_release_not_excluded_by_default(self, version: Version) -> None:
        """Post-releases are included in default filtering."""
        assume(version.is_postrelease and version.local is None)
        spec = Specifier(f">={version}")
        filtered = list(spec.filter([str(version)]))
        assert str(version) in filtered

    @given(version=nonlocal_versions())
    @SETTINGS
    def test_final_release_not_excluded_by_default(self, version: Version) -> None:
        """Final releases are included in default filtering."""
        assume(not version.is_prerelease and not version.is_postrelease)
        assume(not version.is_devrelease and version.local is None)
        spec = Specifier(f">={version}")
        filtered = list(spec.filter([str(version)]))
        assert str(version) in filtered

    @given(
        major=st.integers(min_value=0, max_value=10),
        minor=st.integers(min_value=0, max_value=10),
        bump=st.integers(min_value=1, max_value=5),
        post_num=st.integers(min_value=0, max_value=5),
        pre_tag=pre_tags,
        pre_num=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_post_included_while_pre_excluded(
        self,
        major: int,
        minor: int,
        bump: int,
        post_num: int,
        pre_tag: str,
        pre_num: int,
    ) -> None:
        """When both post and pre are available, post is included, pre is not."""
        base = Version(f"{major}.{minor}")
        # Post-release of the base version is always >= base.
        postrelease_version = Version(f"{base}.post{post_num}")
        # Pre-release of a later version so it satisfies >=base.
        prerelease_version = Version(f"{major}.{minor + bump}{pre_tag}{pre_num}")
        spec = Specifier(f">={base}")
        filtered = list(
            spec.filter([str(base), str(postrelease_version), str(prerelease_version)])
        )
        assert str(postrelease_version) in filtered
        assert str(base) in filtered
        assert str(prerelease_version) not in filtered
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/test_specifier_extended.py0000644000000000000000000001127315172742311020614 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 typing

import pytest
from hypothesis import assume, given
from hypothesis import strategies as st

from packaging.specifiers import SpecifierSet
from tests.property.strategies import (
    SETTINGS,
    VERSION_POOL,
    nonlocal_versions,
    pep440_versions,
    release_versions,
    specifier_sets,
)

if typing.TYPE_CHECKING:
    from packaging.version import Version

pytestmark = pytest.mark.property


@st.composite
def unsatisfiable_sets(draw: st.DrawFn) -> SpecifierSet:
    """Build a SpecifierSet that is guaranteed unsatisfiable."""
    pattern = draw(
        st.sampled_from(
            [
                "contradictory_range",
                "equal_not_equal",
                "equal_not_equal_wildcard",
                "contradictory_pins",
            ]
        )
    )

    if pattern == "contradictory_range":
        lo = draw(nonlocal_versions())
        hi = draw(nonlocal_versions())
        assume(hi > lo)
        return SpecifierSet(f">={hi},<{lo}")

    if pattern == "equal_not_equal":
        v = draw(pep440_versions())
        return SpecifierSet(f"=={v},!={v}")

    if pattern == "equal_not_equal_wildcard":
        v = draw(release_versions())
        return SpecifierSet(f"=={v}.*,!={v}.*")

    # contradictory_pins: ==X,==Y where X != Y
    # Local versions excluded: ==V (no local) matches V+local, so
    # ==1.0 and ==1.0+local are not contradictory.
    a = draw(nonlocal_versions())
    b = draw(nonlocal_versions())
    assume(a != b)
    return SpecifierSet(f"=={a},=={b}")


class TestIsUnsatisfiableSoundness:
    """Logical properties of is_unsatisfiable() that follow from its
    definition but are not stated in PEP 440."""

    @given(spec=unsatisfiable_sets(), version=pep440_versions())
    @SETTINGS
    def test_unsatisfiable_rejects_all_versions(
        self, spec: SpecifierSet, version: Version
    ) -> None:
        """An unsatisfiable set must reject every version."""
        assert spec.is_unsatisfiable()
        assert not spec.contains(version, prereleases=True)

    @given(spec=specifier_sets())
    @SETTINGS
    def test_filter_nonempty_implies_satisfiable(self, spec: SpecifierSet) -> None:
        """If filter finds any match in VERSION_POOL, the set is satisfiable."""
        versions = [str(v) for v in VERSION_POOL]
        if list(spec.filter(versions, prereleases=True)):
            assert not spec.is_unsatisfiable()

    @given(spec_a=unsatisfiable_sets(), spec_b=specifier_sets())
    @SETTINGS
    def test_unsatisfiable_monotone_under_intersection(
        self, spec_a: SpecifierSet, spec_b: SpecifierSet
    ) -> None:
        """Adding constraints to an unsatisfiable set keeps it unsatisfiable."""
        assert (spec_a & spec_b).is_unsatisfiable()

    @given(
        spec_a=specifier_sets(),
        spec_b=specifier_sets(),
        version=pep440_versions(),
    )
    @SETTINGS
    def test_and_agrees_with_is_unsatisfiable(
        self,
        spec_a: SpecifierSet,
        spec_b: SpecifierSet,
        version: Version,
    ) -> None:
        """If A & B is satisfiable, any version it accepts must be
        accepted by both A and B individually."""
        combined = spec_a & spec_b
        if combined.contains(version, prereleases=True):
            assert not combined.is_unsatisfiable()
            assert spec_a.contains(version, prereleases=True)
            assert spec_b.contains(version, prereleases=True)


class TestIsUnsatisfiableWithPrereleases:
    """Logical properties of is_unsatisfiable() when prereleases=False.
    A set whose only solutions are pre-releases should be reported as
    unsatisfiable."""

    @given(spec=specifier_sets())
    @SETTINGS
    def test_prereleases_false_unsatisfiable_implies_empty_filter(
        self, spec: SpecifierSet
    ) -> None:
        """If unsatisfiable with prereleases=False, filter returns nothing."""
        ss = SpecifierSet(str(spec), prereleases=False)
        if ss.is_unsatisfiable():
            versions = [str(v) for v in VERSION_POOL]
            assert not list(ss.filter(versions))

    @given(
        spec=specifier_sets(),
        version=nonlocal_versions(),
    )
    @SETTINGS
    def test_prereleases_false_unsatisfiable_rejects_non_prereleases(
        self, spec: SpecifierSet, version: Version
    ) -> None:
        """If unsatisfiable with prereleases=False, non-prerelease
        versions cannot match."""
        ss = SpecifierSet(str(spec), prereleases=False)
        if ss.is_unsatisfiable() and not version.is_prerelease:
            assert not ss.contains(version)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/test_specifier_implied.py0000644000000000000000000007422115172742311020441 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 hypothesis import assume, given
from hypothesis import strategies as st

from packaging.specifiers import Specifier, SpecifierSet
from packaging.version import Version
from tests.property.strategies import (
    SETTINGS,
    local_labels,
    nonlocal_versions,
    pep440_versions,
    pre_tags,
    related_version_triple,
    release_versions,
    small_ints,
    specifier_sets,
)

pytestmark = pytest.mark.property


class TestFilterContainmentConsistency:
    """Implied by the definitions of filter() and contains(): filtering a list
    of versions should produce exactly the versions that individually satisfy
    the specifier."""

    @given(
        spec=specifier_sets(),
        versions=st.lists(pep440_versions(), min_size=0, max_size=15),
    )
    @SETTINGS
    def test_filter_equals_manual_containment(
        self, spec: SpecifierSet, versions: list[Version]
    ) -> None:
        """filter(vs) should equal [v for v in vs if v in spec]."""
        strs = [str(v) for v in versions]
        filtered = list(spec.filter(strs, prereleases=True))
        manual = [s for s in strs if spec.contains(s, prereleases=True)]
        assert filtered == manual

    @given(
        spec=specifier_sets(),
        versions=st.lists(pep440_versions(), min_size=0, max_size=15),
    )
    @SETTINGS
    def test_filter_preserves_order(
        self, spec: SpecifierSet, versions: list[Version]
    ) -> None:
        """filter() must return versions in the same order as the input."""
        strs = [str(v) for v in versions]
        filtered = list(spec.filter(strs, prereleases=True))
        # The filtered list must be a subsequence of the input.
        it = iter(strs)
        for f in filtered:
            for s in it:
                if s == f:
                    break
            else:
                raise AssertionError(f"{f} not found in remaining input")

    @given(
        spec=specifier_sets(),
        versions=st.lists(pep440_versions(), min_size=0, max_size=15),
    )
    @SETTINGS
    def test_filter_is_subset_of_input(
        self, spec: SpecifierSet, versions: list[Version]
    ) -> None:
        """Every version in filter output was in the input."""
        strs = [str(v) for v in versions]
        filtered = list(spec.filter(strs, prereleases=True))
        for v in filtered:
            assert v in strs


class TestSpecifierSetAndConsistency:
    """Implied by the definition of SpecifierSet.__and__: the & operator
    combines two specifier sets, and the result should match a version iff
    both operands match it."""

    @given(
        specifier_a=specifier_sets(),
        specifier_b=specifier_sets(),
        version=pep440_versions(),
    )
    @SETTINGS
    def test_and_matches_iff_both_match(
        self,
        specifier_a: SpecifierSet,
        specifier_b: SpecifierSet,
        version: Version,
    ) -> None:
        """(a & b).contains(v) iff a.contains(v) and b.contains(v)."""
        combined = specifier_a & specifier_b
        both = specifier_a.contains(version, prereleases=True) and specifier_b.contains(
            version, prereleases=True
        )
        assert combined.contains(version, prereleases=True) == both

    @given(
        specifier_a=specifier_sets(),
        specifier_b=specifier_sets(),
        version=pep440_versions(),
    )
    @SETTINGS
    def test_and_is_commutative(
        self,
        specifier_a: SpecifierSet,
        specifier_b: SpecifierSet,
        version: Version,
    ) -> None:
        """a & b and b & a accept the same versions."""
        ab = specifier_a & specifier_b
        b_and_a = specifier_b & specifier_a
        assert ab.contains(version, prereleases=True) == b_and_a.contains(
            version, prereleases=True
        )


class TestSpecifierRoundTrip:
    """Implied by the normalization rules: parsing a specifier and converting
    it back to a string should produce a stable, equivalent representation."""

    @given(version=nonlocal_versions())
    @SETTINGS
    def test_specifier_str_round_trip(self, version: Version) -> None:
        """Specifier(str(Specifier(s))) == Specifier(s)."""
        for op in [">=", "<=", ">", "<", "==", "!="]:
            s = f"{op}{version}"
            assert Specifier(str(Specifier(s))) == Specifier(s)

    @given(version=nonlocal_versions())
    @SETTINGS
    def test_specifier_set_str_round_trip(self, version: Version) -> None:
        """SpecifierSet(str(SpecifierSet(s))) == SpecifierSet(s)."""
        s = f">={version},<={version}"
        assert SpecifierSet(str(SpecifierSet(s))) == SpecifierSet(s)

    @given(spec=specifier_sets())
    @SETTINGS
    def test_specifier_set_str_round_trip_general(self, spec: SpecifierSet) -> None:
        """Any SpecifierSet round-trips through str."""
        assert SpecifierSet(str(spec)) == spec


class TestVersionPropertyConsistency:
    """Implied by the version scheme: the .public, .base_version, .major,
    .minor, .micro properties must be consistent with the parsed version
    components."""

    @given(version=pep440_versions())
    @SETTINGS
    def test_public_strips_local(self, version: Version) -> None:
        """Version(v.public) equals v with local removed."""
        pub = Version(version.public)
        assert pub == version.__replace__(local=None)

    @given(version=pep440_versions())
    @SETTINGS
    def test_base_version_strips_suffixes(self, version: Version) -> None:
        """Version(v.base_version) has no pre/post/dev/local."""
        base = Version(version.base_version)
        assert base.pre is None
        assert base.post is None
        assert base.dev is None
        assert base.local is None
        assert base.release == version.release
        assert base.epoch == version.epoch

    @given(version=pep440_versions())
    @SETTINGS
    def test_major_minor_micro_agree_with_release(self, version: Version) -> None:
        """major/minor/micro are the first three release components."""
        assert version.major == version.release[0]
        assert version.minor == (version.release[1] if len(version.release) > 1 else 0)
        assert version.micro == (version.release[2] if len(version.release) > 2 else 0)

    @given(version=pep440_versions())
    @SETTINGS
    def test_is_prerelease_iff_pre_or_dev(self, version: Version) -> None:
        """is_prerelease is True iff pre or dev is set."""
        assert version.is_prerelease == (
            version.pre is not None or version.dev is not None
        )

    @given(version=pep440_versions())
    @SETTINGS
    def test_is_postrelease_iff_post(self, version: Version) -> None:
        """is_postrelease is True iff post is set."""
        assert version.is_postrelease == (version.post is not None)

    @given(version=pep440_versions())
    @SETTINGS
    def test_is_devrelease_iff_dev(self, version: Version) -> None:
        """is_devrelease is True iff dev is set."""
        assert version.is_devrelease == (version.dev is not None)

    @given(version=pep440_versions())
    @SETTINGS
    def test_public_version_ordering(self, version: Version) -> None:
        """A version with local is >= its public version."""
        pub = Version(version.public)
        assert version >= pub


class TestMetamorphicVersionModifications:
    """Implied by the ordering rules: known modifications to a version
    should produce predictable ordering changes."""

    @given(version=release_versions())
    @SETTINGS
    def test_adding_post_increases(self, version: Version) -> None:
        """V.postN > V for any final release V."""
        post = Version(f"{version}.post0")
        assert post > version

    @given(version=release_versions())
    @SETTINGS
    def test_adding_dev_decreases(self, version: Version) -> None:
        """V.devN < V for any final release V."""
        dev = Version(f"{version}.dev0")
        assert dev < version

    @given(version=release_versions(), tag=pre_tags, number=small_ints)
    @SETTINGS
    def test_adding_pre_decreases(
        self, version: Version, tag: str, number: int
    ) -> None:
        """V.aN/bN/rcN < V for any final release V."""
        pre = Version(f"{version}{tag}{number}")
        assert pre < version

    @given(version=pep440_versions())
    @SETTINGS
    def test_bumping_last_segment_increases(self, version: Version) -> None:
        """Incrementing the last release segment produces a greater version."""
        release = list(version.release)
        release[-1] += 1
        bumped_str = ".".join(str(s) for s in release)
        if version.epoch:
            bumped_str = f"{version.epoch}!{bumped_str}"
        bumped = Version(bumped_str)
        assert bumped > version

    @given(
        version=pep440_versions(),
        higher_epoch=st.integers(min_value=1, max_value=5),
    )
    @SETTINGS
    def test_higher_epoch_always_wins(
        self, version: Version, higher_epoch: int
    ) -> None:
        """A version with a higher epoch is always greater."""
        epoch = version.epoch + higher_epoch
        other = Version(f"{epoch}!0")
        assert other > version

    @given(version=release_versions())
    @SETTINGS
    def test_appending_zero_segment_is_equal(self, version: Version) -> None:
        """V.0 == V due to zero-padding rules."""
        extended = Version(f"{version}.0")
        assert extended == version

    @given(
        version=nonlocal_versions(),
        local=local_labels,
    )
    @SETTINGS
    def test_adding_local_does_not_decrease(self, version: Version, local: str) -> None:
        """V+local >= V for any version."""
        with_local = Version(f"{version}+{local}")
        assert with_local >= version


class TestCompatibleReleaseBounds:
    """Implied by the compatible release definition: ~=V.N is equivalent
    to >=V.N, ==V.*, which means it has a clear lower and upper bound."""

    @given(version=release_versions(), candidate=pep440_versions())
    @SETTINGS
    def test_compatible_lower_bound(self, version: Version, candidate: Version) -> None:
        """If candidate matches ~=V then candidate >= V."""
        assume(candidate.local is None and len(version.release) >= 2)
        spec = Specifier(f"~={version}")
        if spec.contains(candidate, prereleases=True):
            assert candidate >= version

    @given(version=release_versions(), candidate=pep440_versions())
    @SETTINGS
    def test_compatible_upper_bound(self, version: Version, candidate: Version) -> None:
        """If candidate matches ~=V.N then candidate < (V_prefix+1).0."""
        assume(candidate.local is None and len(version.release) >= 2)
        spec = Specifier(f"~={version}")
        if spec.contains(candidate, prereleases=True):
            # Build the upper bound: bump the second-to-last segment.
            prefix = list(version.release[:-1])
            prefix[-1] += 1
            upper = Version(".".join(str(s) for s in prefix))
            if version.epoch:
                upper = Version(f"{version.epoch}!{upper}")
            assert candidate < upper

    @given(version=release_versions(), candidate=pep440_versions())
    @SETTINGS
    def test_compatible_matches_iff_expansion_matches(
        self, version: Version, candidate: Version
    ) -> None:
        """~=V.N matches iff >=V.N, ==V.* both match."""
        assume(candidate.local is None and len(version.release) >= 2)
        tilde = Specifier(f"~={version}")
        # Build the expansion: >=V, ==prefix.*
        prefix = ".".join(str(s) for s in version.release[:-1])
        if version.epoch:
            prefix = f"{version.epoch}!{prefix}"
        expanded = SpecifierSet(f">={version},=={prefix}.*")
        assert tilde.contains(candidate, prereleases=True) == expanded.contains(
            candidate, prereleases=True
        )


class TestTrichotomy:
    """Implied by the version ordering being a total order and the specifier
    definitions. The inclusive operators (>=, <=) have no exclusion rules
    and together with == form a true trichotomy. The exclusive operators
    (>, <) have pre/post/local exclusions so they are subsets of the
    inclusive operators."""

    @given(
        candidate=pep440_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_inclusive_trichotomy(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """Exactly one of <=S (and not ==S), ==S, >=S (and not ==S) holds.

        Equivalently: >=S and <=S partition the version space into three
        disjoint groups (less, equal, greater) with ==S being the middle."""
        less_equal = Specifier(f"<={specifier_version}").contains(
            candidate, prereleases=True
        )
        equal = Specifier(f"=={specifier_version}").contains(
            candidate, prereleases=True
        )
        greater_equal = Specifier(f">={specifier_version}").contains(
            candidate, prereleases=True
        )
        # If equal, both inclusive ops match.
        if equal:
            assert less_equal
            assert greater_equal
        else:
            # Exactly one of <=S or >=S matches (not both, since == is
            # excluded, and at least one must hold by totality).
            assert less_equal != greater_equal, (
                f"candidate={candidate}, spec={specifier_version}: "
                f"<={less_equal}, =={equal}, >={greater_equal}"
            )

    @given(
        candidate=pep440_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_greater_equal_equals_greater_than_or_equal(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """>=S matches iff >S or ==S matches.

        This may fail for pre/post/local-excluded versions (where >S
        rejects a version that is strictly greater in ordering). When
        it does, it reveals the exclusion gaps in > and <."""
        greater_equal = Specifier(f">={specifier_version}").contains(
            candidate, prereleases=True
        )
        greater_than = Specifier(f">{specifier_version}").contains(
            candidate, prereleases=True
        )
        equal = Specifier(f"=={specifier_version}").contains(
            candidate, prereleases=True
        )
        # >V is a subset of >=V, and ==V is a subset of >=V, so
        # (greater_than or equal) implies greater_equal. The reverse also
        # holds: >=V matches only if the candidate is either strictly greater
        # or equal, and the exclusions in >V only reduce its set.
        if greater_than or equal:
            assert greater_equal
        # The converse (greater_equal implies greater_than or equal) can fail
        # when >V excludes a post/pre/local of V. That gap is tested by the
        # cross-operator consistency tests elsewhere.

    @given(
        candidate=pep440_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_less_equal_equals_less_than_or_equal(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """<=S matches iff  None:
        """spec.contains(V) == spec.contains(V.0) for all specifiers."""
        padded = candidate.__replace__(release=(*candidate.release, 0))
        for op in [">=", "<=", ">", "<", "==", "!="]:
            spec = Specifier(f"{op}{version}")
            assert spec.contains(candidate, prereleases=True) == spec.contains(
                padded, prereleases=True
            ), f"{op}{version}: {candidate} and {padded} disagree"


class TestPrereleaseFlagOnlyAffectsPreReleases:
    """Implied by the pre-release handling rules: the prereleases flag
    should only affect versions that are actually pre-releases."""

    @given(spec=specifier_sets(), version=pep440_versions())
    @SETTINGS
    def test_non_prerelease_unaffected_by_flag(
        self, spec: SpecifierSet, version: Version
    ) -> None:
        """For non-prerelease versions, prereleases flag has no effect."""
        assume(not version.is_prerelease and version.local is None)
        assert spec.contains(version, prereleases=True) == spec.contains(
            version, prereleases=False
        )


class TestAndAgreesWithStringConcatenation:
    """Implied by SpecifierSet.__and__ semantics: the & operator should
    produce the same containment results as comma-joining the specifier
    strings."""

    @given(
        specifier_a=specifier_sets(),
        specifier_b=specifier_sets(),
        version=pep440_versions(),
    )
    @SETTINGS
    def test_and_equals_comma_join(
        self,
        specifier_a: SpecifierSet,
        specifier_b: SpecifierSet,
        version: Version,
    ) -> None:
        """(a & b).contains(v) == SpecifierSet(f"{a},{b}").contains(v)."""
        via_and = (specifier_a & specifier_b).contains(version, prereleases=True)
        joined = str(specifier_a) + ("," + str(specifier_b) if str(specifier_b) else "")
        via_str = SpecifierSet(joined).contains(version, prereleases=True)
        assert via_and == via_str


class TestLocalInvarianceForOrderingSpecifiers:
    """Implied by the spec: local version labels MUST be ignored entirely
    when checking if candidate versions match a given version specifier
    (except == with a local label)."""

    @given(
        version=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
        local=local_labels,
    )
    @SETTINGS
    def test_local_ignored_for_all_ordering_ops(
        self, version: Version, specifier_version: Version, local: str
    ) -> None:
        """Adding local to a candidate doesn't change ordering specifier
        results."""
        with_local = Version(f"{version}+{local}")
        for op in [">=", "<=", ">", "<", "~="]:
            if op == "~=" and len(specifier_version.release) < 2:
                continue
            spec = Specifier(f"{op}{specifier_version}")
            assert spec.contains(version, prereleases=True) == spec.contains(
                with_local, prereleases=True
            ), f"{op}{specifier_version}: {version} and {with_local} disagree"


class TestComplementFilterPartition:
    """Implied by != being the exact complement of ==: filtering with
    == and != should partition the input list exactly."""

    @given(
        specifier_version=nonlocal_versions(),
        versions=st.lists(pep440_versions(), min_size=0, max_size=15),
    )
    @SETTINGS
    def test_equal_not_equal_partition_versions(
        self, specifier_version: Version, versions: list[Version]
    ) -> None:
        """filter(==V, vs) + filter(!=V, vs) == vs (as multisets)."""
        strs = [str(v) for v in versions if v.local is None]
        equal_spec = SpecifierSet(f"=={specifier_version}")
        not_equal_spec = SpecifierSet(f"!={specifier_version}")
        equal_filtered = list(equal_spec.filter(strs, prereleases=True))
        not_equal_filtered = list(not_equal_spec.filter(strs, prereleases=True))
        assert sorted(equal_filtered + not_equal_filtered) == sorted(strs)

    @given(
        specifier_version=release_versions(),
        versions=st.lists(pep440_versions(), min_size=0, max_size=15),
    )
    @SETTINGS
    def test_equal_not_equal_wildcard_partition_versions(
        self, specifier_version: Version, versions: list[Version]
    ) -> None:
        """filter(==V.*, vs) + filter(!=V.*, vs) == vs (as multisets)."""
        strs = [str(v) for v in versions if v.local is None]
        equal_spec = SpecifierSet(f"=={specifier_version}.*")
        not_equal_spec = SpecifierSet(f"!={specifier_version}.*")
        equal_filtered = list(equal_spec.filter(strs, prereleases=True))
        not_equal_filtered = list(not_equal_spec.filter(strs, prereleases=True))
        assert sorted(equal_filtered + not_equal_filtered) == sorted(strs)


class TestCrossOperatorConsistency:
    """Implied by the combination of the inclusive and exclusive ordered
    comparison sections, plus the version matching and exclusion sections.

    The six comparison operators (>=, <=, >, <, ==, !=) are defined
    independently but their semantics must be consistent with each other
    and with the version ordering."""

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_greater_than_is_subset_of_greater_equal(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """If v matches >V then v must also match >=V."""
        greater_than = Specifier(f">{specifier_version}")
        greater_equal = Specifier(f">={specifier_version}")
        if greater_than.contains(candidate, prereleases=True):
            assert greater_equal.contains(candidate, prereleases=True), (
                f">{specifier_version} accepts {candidate} "
                f"but >={specifier_version} rejects it"
            )

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_less_than_is_subset_of_less_equal(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """If v matches  None:
        """No version can match both >V and {specifier_version}")
        less_than = Specifier(f"<{specifier_version}")
        assert not (
            greater_than.contains(candidate, prereleases=True)
            and less_than.contains(candidate, prereleases=True)
        ), f"{candidate} matches both >{specifier_version} and <{specifier_version}"

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_greater_equal_and_less_equal_intersection_implies_equal(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """If v matches both >=V and <=V then v must match ==V."""
        greater_equal = Specifier(f">={specifier_version}")
        less_equal = Specifier(f"<={specifier_version}")
        equal = Specifier(f"=={specifier_version}")
        if greater_equal.contains(candidate, prereleases=True) and less_equal.contains(
            candidate, prereleases=True
        ):
            assert equal.contains(candidate, prereleases=True), (
                f"{candidate} matches >={specifier_version} and "
                f"<={specifier_version} but not =={specifier_version}"
            )

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_not_equal_accepts_everything_greater_than_accepts(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """If v matches >V then v must also match !=V."""
        greater_than = Specifier(f">{specifier_version}")
        not_equal = Specifier(f"!={specifier_version}")
        if greater_than.contains(candidate, prereleases=True):
            assert not_equal.contains(candidate, prereleases=True), (
                f">{specifier_version} accepts {candidate} "
                f"but !={specifier_version} rejects it"
            )

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_not_equal_accepts_everything_less_than_accepts(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """If v matches  None:
        """If a matches >=V and b >= a, then b must also match >=V."""
        spec = Specifier(f">={specifier_version}")
        if spec.contains(version_a, prereleases=True) and version_b >= version_a:
            assert spec.contains(version_b, prereleases=True), (
                f">={specifier_version} accepts {version_a} but rejects "
                f"{version_b} even though {version_b} >= {version_a}"
            )

    @given(
        specifier_version=nonlocal_versions(),
        version_a=nonlocal_versions(),
        version_b=nonlocal_versions(),
    )
    @SETTINGS
    def test_less_equal_monotonic(
        self, specifier_version: Version, version_a: Version, version_b: Version
    ) -> None:
        """If a matches <=V and b <= a, then b must also match <=V."""
        spec = Specifier(f"<={specifier_version}")
        if spec.contains(version_a, prereleases=True) and version_b <= version_a:
            assert spec.contains(version_b, prereleases=True), (
                f"<={specifier_version} accepts {version_a} but rejects "
                f"{version_b} even though {version_b} <= {version_a}"
            )

    @given(
        candidate=nonlocal_versions(),
        specifier_version=nonlocal_versions(),
    )
    @SETTINGS
    def test_equal_wildcard_is_superset_of_equal(
        self, candidate: Version, specifier_version: Version
    ) -> None:
        """If v matches ==V then v must also match ==V.*."""
        # Wildcards are only valid on pure release segments.
        assume(
            not specifier_version.is_devrelease
            and not specifier_version.is_prerelease
            and not specifier_version.is_postrelease
        )
        equal = Specifier(f"=={specifier_version}")
        equal_wild = Specifier(f"=={specifier_version}.*")
        if equal.contains(candidate, prereleases=True):
            assert equal_wild.contains(candidate, prereleases=True), (
                f"=={specifier_version} accepts {candidate} "
                f"but =={specifier_version}.* rejects it"
            )

    @given(
        specifier_version=nonlocal_versions(),
        version_a=nonlocal_versions(),
        version_b=nonlocal_versions(),
    )
    @SETTINGS
    def test_greater_than_monotonic(
        self,
        specifier_version: Version,
        version_a: Version,
        version_b: Version,
    ) -> None:
        """If a matches >V and b > a, then b must also match >V."""
        spec = Specifier(f">{specifier_version}")
        if spec.contains(version_a, prereleases=True) and version_b > version_a:
            assert spec.contains(version_b, prereleases=True), (
                f">{specifier_version} accepts {version_a} "
                f"but rejects {version_b} even though "
                f"{version_b} > {version_a}"
            )

    @given(triple=related_version_triple())
    @SETTINGS
    def test_greater_than_monotonic_related(
        self, triple: tuple[Version, Version, Version]
    ) -> None:
        """If a matches >V and b > a, then b must also match >V.

        Same property as above but with versions sharing a release segment."""
        specifier_version, version_a, version_b = triple
        spec = Specifier(f">{specifier_version}")
        if spec.contains(version_a, prereleases=True) and version_b > version_a:
            assert spec.contains(version_b, prereleases=True), (
                f">{specifier_version} accepts {version_a} "
                f"but rejects {version_b} even though "
                f"{version_b} > {version_a}"
            )

    @given(
        specifier_version=nonlocal_versions(),
        version_a=nonlocal_versions(),
        version_b=nonlocal_versions(),
    )
    @SETTINGS
    def test_less_than_monotonic(
        self,
        specifier_version: Version,
        version_a: Version,
        version_b: Version,
    ) -> None:
        """If a matches  None:
        """If a matches  None:
        """A version matches a multi-clause specifier iff it matches every clause."""
        clauses = [f">={version}", f"<={version}"]
        combined = SpecifierSet(",".join(clauses))
        individual = [SpecifierSet(c) for c in clauses]
        matches_all = all(version in s for s in individual)
        assert (version in combined) == matches_all

    @given(candidate=pep440_versions(), data=st.data())
    @SETTINGS
    def test_adding_clause_can_only_narrow(
        self, candidate: Version, data: st.DataObject
    ) -> None:
        """Adding a clause to a specifier set can never cause a previously
        excluded version to start matching."""
        base_op = data.draw(ops)
        base_ver = data.draw(release_versions())
        extra_op = data.draw(ops)
        extra_ver = data.draw(release_versions())

        base_spec = SpecifierSet(f"{base_op}{base_ver}")
        combined = SpecifierSet(f"{base_op}{base_ver},{extra_op}{extra_ver}")
        if candidate in combined:
            assert candidate in base_spec

    @given(
        first_op=ops,
        first_ver=release_versions(),
        second_op=ops,
        second_ver=release_versions(),
        candidate=pep440_versions(),
    )
    @SETTINGS
    def test_intersection_is_idempotent(
        self,
        first_op: str,
        first_ver: Version,
        second_op: str,
        second_ver: Version,
        candidate: Version,
    ) -> None:
        """(A & B) & B accepts the same versions as A & B."""
        combined = SpecifierSet(f"{first_op}{first_ver},{second_op}{second_ver}")
        combined_double = SpecifierSet(
            f"{first_op}{first_ver},{second_op}{second_ver},{second_op}{second_ver}"
        )
        assert combined.contains(
            candidate, prereleases=True
        ) == combined_double.contains(candidate, prereleases=True)

    @given(
        first_op=ops,
        first_ver=release_versions(),
        second_op=ops,
        second_ver=release_versions(),
        third_op=ops,
        third_ver=release_versions(),
        candidate=pep440_versions(),
    )
    @SETTINGS
    def test_intersection_is_associative(
        self,
        first_op: str,
        first_ver: Version,
        second_op: str,
        second_ver: Version,
        third_op: str,
        third_ver: Version,
        candidate: Version,
    ) -> None:
        """(A & B) & C accepts the same versions as A & (B & C)."""
        combined = SpecifierSet(
            f"{first_op}{first_ver},{second_op}{second_ver},{third_op}{third_ver}"
        )
        # Since comma is AND regardless of grouping, any ordering
        # of the same clauses must agree on containment.
        assert (candidate in combined) == (
            SpecifierSet(f"{first_op}{first_ver}").contains(candidate, prereleases=True)
            and SpecifierSet(f"{second_op}{second_ver}").contains(
                candidate, prereleases=True
            )
            and SpecifierSet(f"{third_op}{third_ver}").contains(
                candidate, prereleases=True
            )
        )


class TestSpecifierWhitespace:
    """Whitespace between a conditional operator and the following version
    identifier is optional, as is the whitespace around the commas."""

    @given(spec_ver=release_versions(), spaces=st.integers(min_value=0, max_value=3))
    @SETTINGS
    def test_whitespace_between_op_and_version(
        self, spec_ver: Version, spaces: int
    ) -> None:
        """Whitespace between operator and version doesn't change semantics."""
        ws = " " * spaces
        spec_no_ws = Specifier(f"=={spec_ver}")
        spec_ws = Specifier(f"=={ws}{spec_ver}")
        assert spec_no_ws == spec_ws

    @given(
        v1=release_versions(),
        v2=release_versions(),
        spaces=st.integers(min_value=0, max_value=3),
    )
    @SETTINGS
    def test_whitespace_around_commas(
        self, v1: Version, v2: Version, spaces: int
    ) -> None:
        """Whitespace around commas doesn't change semantics."""
        ws = " " * spaces
        spec_no_ws = SpecifierSet(f">={v1},<={v2}")
        spec_ws = SpecifierSet(f">={v1}{ws},{ws}<={v2}")
        assert spec_no_ws == spec_ws


class TestLocalVersionIgnoredInSpecifiers:
    """Except where specifically noted below, local version identifiers MUST NOT be
    permitted in version specifiers, and local version labels MUST be ignored
    entirely when checking if candidate versions match a given version
    specifier."""

    @given(version=versions_with_local())
    @SETTINGS
    def test_local_ignored_for_ordering_specifiers(self, version: Version) -> None:
        """A version with a local label matches >= and <= on its public version."""
        public = Version(str(version).split("+")[0])
        spec = SpecifierSet(f">={public}")
        assert version in spec

    @given(version=versions_with_local())
    @SETTINGS
    def test_local_ignored_for_gt(self, version: Version) -> None:
        """Local labels are stripped before comparison for > specifiers."""
        public = Version(str(version).split("+")[0])
        # version's local is ignored, so it compares as public; public is not > public
        spec = Specifier(f">{public}")
        assert version not in spec

    @given(version=versions_with_local())
    @SETTINGS
    def test_local_ignored_for_lt(self, version: Version) -> None:
        """Local labels are stripped before comparison for < specifiers."""
        public = Version(str(version).split("+")[0])
        spec = Specifier(f"<{public}")
        assert version not in spec

    @given(spec_ver=release_versions(), local=st.integers(min_value=0, max_value=5))
    @SETTINGS
    def test_local_not_permitted_in_ordering_specifiers(
        self, spec_ver: Version, local: int
    ) -> None:
        """Local version identifiers must not be permitted in
        >=, <=, >, < specifiers."""
        local_str = f"+local{local}"
        for op in [">=", "<=", ">", "<"]:
            with pytest.raises(InvalidSpecifier):
                Specifier(f"{op}{spec_ver}{local_str}")


class TestCompatibleReleaseDefinition:
    """A compatible release clause consists of the compatible release operator ``~=``
    and a version identifier. It matches any candidate version that is expected
    to be compatible with the specified version."""

    @given(spec_ver=multi_segment_versions(), candidate=pep440_versions())
    @SETTINGS
    def test_compatible_release_matches_expected_compatible(
        self, spec_ver: Version, candidate: Version
    ) -> None:
        """~=V matches candidate iff candidate >= V and candidate matches the
        prefix wildcard derived from V."""
        assume(spec_ver.epoch == candidate.epoch)
        spec = Specifier(f"~={spec_ver}")
        result = candidate in spec
        # Also check via the expanded form
        release = spec_ver.release
        prefix = ".".join(str(s) for s in release[:-1])
        epoch_prefix = f"{spec_ver.epoch}!" if spec_ver.epoch else ""
        expanded = SpecifierSet(f">={spec_ver},=={epoch_prefix}{prefix}.*")
        expanded_result = candidate in expanded
        assert result == expanded_result


class TestCompatibleReleaseNoLocal:
    """The specified version identifier must be in the standard format described in
    `Version scheme`_. Local version identifiers are NOT permitted in this
    version specifier."""

    @given(spec_ver=release_versions(), local=st.integers(min_value=0, max_value=5))
    @SETTINGS
    def test_local_not_permitted_in_compatible(
        self, spec_ver: Version, local: int
    ) -> None:
        """~= with a local version identifier must raise InvalidSpecifier."""
        assume(len(spec_ver.release) >= 2)
        with pytest.raises(InvalidSpecifier):
            Specifier(f"~={spec_ver}+local{local}")


class TestCompatibleReleaseEquivalence:
    r"""For a given release identifier ``V.N``, the compatible release clause is
    approximately equivalent to the pair of comparison clauses::

        >= V.N, == V.*

    This operator MUST NOT be used with a single segment version number such as
    ``~=1``."""

    @given(
        major=small_ints,
        minor=small_ints,
        candidate=pep440_versions(),
    )
    @SETTINGS
    def test_two_segment_equivalence(
        self, major: int, minor: int, candidate: Version
    ) -> None:
        """~= V.N is equivalent to >= V.N, == V.* for two-segment versions."""
        v_str = f"{major}.{minor}"
        spec_compat = Specifier(f"~={v_str}")
        spec_expanded = SpecifierSet(f">={v_str},=={major}.*")
        assert (candidate in spec_compat) == (candidate in spec_expanded)

    @given(
        major=small_ints,
        minor=small_ints,
        patch=small_ints,
        candidate=pep440_versions(),
    )
    @SETTINGS
    def test_three_segment_equivalence(
        self, major: int, minor: int, patch: int, candidate: Version
    ) -> None:
        """~= V.N.P is equivalent to >= V.N.P, == V.N.*"""
        v_str = f"{major}.{minor}.{patch}"
        spec_compat = Specifier(f"~={v_str}")
        spec_expanded = SpecifierSet(f">={v_str},=={major}.{minor}.*")
        assert (candidate in spec_compat) == (candidate in spec_expanded)

    @given(major=small_ints)
    @SETTINGS
    def test_single_segment_rejected(self, major: int) -> None:
        """~= with a single segment version number must be rejected."""
        with pytest.raises(InvalidSpecifier):
            Specifier(f"~={major}")


class TestCompatibleReleaseSuffixIgnored:
    r"""If a pre-release, post-release or developmental release is named in a
    compatible release clause as ``V.N.suffix``, then the suffix is ignored
    when determining the required prefix match::

        ~= 2.2.post3
        >= 2.2.post3, == 2.*

        ~= 1.4.5a4
        >= 1.4.5a4, == 1.4.*"""

    @given(candidate=pep440_versions())
    @SETTINGS
    def test_post_release_suffix_ignored(self, candidate: Version) -> None:
        """~= 2.2.post3 is equivalent to >= 2.2.post3, == 2.*"""
        spec = Specifier("~=2.2.post3")
        expanded = SpecifierSet(">=2.2.post3,==2.*")
        assert (candidate in spec) == (candidate in expanded)

    @given(candidate=pep440_versions())
    @SETTINGS
    def test_pre_release_suffix_ignored(self, candidate: Version) -> None:
        """~= 1.4.5a4 is equivalent to >= 1.4.5a4, == 1.4.*"""
        spec = Specifier("~=1.4.5a4")
        expanded = SpecifierSet(">=1.4.5a4,==1.4.*")
        assert (candidate in spec) == (candidate in expanded)

    @given(
        base=multi_segment_versions(),
        post=small_ints,
        candidate=pep440_versions(),
    )
    @SETTINGS
    def test_post_suffix_general(
        self, base: Version, post: int, candidate: Version
    ) -> None:
        """~= V.N.postP uses V.* as the prefix (suffix ignored)."""
        assume(base.pre is None and base.post is None and base.dev is None)
        assume(len(base.release) >= 2)
        v_str = f"{base}.post{post}"
        release = base.release
        prefix = ".".join(str(s) for s in release[:-1])
        epoch_prefix = f"{base.epoch}!" if base.epoch else ""
        spec = Specifier(f"~={v_str}")
        expanded = SpecifierSet(f">={v_str},=={epoch_prefix}{prefix}.*")
        assert (candidate in spec) == (candidate in expanded)


class TestCompatibleReleasePaddingZeros:
    r"""The padding rules for release segment comparisons means that the assumed
    degree of forward compatibility in a compatible release clause can be
    controlled by appending additional zeros to the version specifier::

        ~= 2.2.0
        >= 2.2.0, == 2.2.*

        ~= 1.4.5.0
        >= 1.4.5.0, == 1.4.5.*"""

    @given(candidate=pep440_versions())
    @SETTINGS
    def test_padding_narrows_two_to_three(self, candidate: Version) -> None:
        """~= 2.2.0 is equivalent to >= 2.2.0, == 2.2.*"""
        spec = Specifier("~=2.2.0")
        expanded = SpecifierSet(">=2.2.0,==2.2.*")
        assert (candidate in spec) == (candidate in expanded)

    @given(candidate=pep440_versions())
    @SETTINGS
    def test_padding_narrows_three_to_four(self, candidate: Version) -> None:
        """~= 1.4.5.0 is equivalent to >= 1.4.5.0, == 1.4.5.*"""
        spec = Specifier("~=1.4.5.0")
        expanded = SpecifierSet(">=1.4.5.0,==1.4.5.*")
        assert (candidate in spec) == (candidate in expanded)

    @given(
        major=small_ints,
        minor=small_ints,
        candidate=pep440_versions(),
    )
    @SETTINGS
    def test_padding_zero_changes_prefix_depth(
        self, major: int, minor: int, candidate: Version
    ) -> None:
        """~= X.Y.0 matches a narrower set than ~= X.Y because the prefix
        is == X.Y.* instead of == X.*"""
        broad = Specifier(f"~={major}.{minor}")
        narrow = Specifier(f"~={major}.{minor}.0")
        if candidate in narrow:
            assert candidate in broad


class TestVersionMatchingStrict:
    r"""By default, the version matching operator is based on a strict equality
    comparison: the specified version must be exactly the same as the requested
    version. The *only* substitution performed is the zero padding of the
    release segment to ensure the release segments are compared with the same
    length."""

    @given(version=nonlocal_versions())
    @SETTINGS
    def test_version_matches_itself(self, version: Version) -> None:
        """== V always matches V."""
        spec = Specifier(f"=={version}")
        assert version in spec

    @given(version=release_versions())
    @SETTINGS
    def test_zero_padding_matches(self, version: Version) -> None:
        """== V.0 matches V due to zero padding (for final releases)."""
        padded_str = f"{version}.0"
        spec_from_padded = Specifier(f"=={padded_str}")
        assert version in spec_from_padded

    @given(version=release_versions())
    @SETTINGS
    def test_zero_padding_symmetric(self, version: Version) -> None:
        """If V matches == V.0, then V.0 matches == V."""
        padded = Version(f"{version}.0")
        spec_original = Specifier(f"=={version}")
        assert padded in spec_original


class TestVersionPrefixMatching:
    r"""Prefix matching may be requested instead of strict comparison, by appending
    a trailing ``.*`` to the version identifier in the version matching clause.
    This means that additional trailing segments will be ignored when
    determining whether or not a version identifier matches the clause. If the
    specified version includes only a release segment, then trailing components
    (or the lack thereof) in the release segment are also ignored."""

    @given(spec_ver=release_versions(), extra=small_ints)
    @SETTINGS
    def test_prefix_match_ignores_trailing_segments(
        self, spec_ver: Version, extra: int
    ) -> None:
        """== V.* matches V.extra for any extra segment."""
        spec = Specifier(f"=={spec_ver}.*")
        extended = Version(f"{spec_ver}.{extra}")
        assert extended in spec

    @given(spec_ver=release_versions())
    @SETTINGS
    def test_prefix_match_includes_exact(self, spec_ver: Version) -> None:
        """== V.* matches V itself (exact match is a prefix match)."""
        spec = Specifier(f"=={spec_ver}.*")
        assert spec_ver in spec

    @given(
        major=small_ints,
        minor=small_ints,
        patch=small_ints,
    )
    @SETTINGS
    def test_prefix_match_with_pre_release(
        self, major: int, minor: int, patch: int
    ) -> None:
        """== X.Y.* matches X.Y.Z.aN (pre-releases under the prefix)."""
        spec = Specifier(f"=={major}.{minor}.*")
        candidate = Version(f"{major}.{minor}.{patch}a1")
        assert candidate in spec

    @given(
        major=small_ints,
        minor=small_ints,
        post=small_ints,
    )
    @SETTINGS
    def test_prefix_match_with_post_release(
        self, major: int, minor: int, post: int
    ) -> None:
        """== X.Y.* matches X.Y.postN."""
        spec = Specifier(f"=={major}.{minor}.*")
        candidate = Version(f"{major}.{minor}.post{post}")
        assert candidate in spec


class TestVersionMatchingPost1Examples:
    r"""For example, given the version ``1.1.post1``, the following clauses would
    match or not as shown::

        == 1.1        # Not equal, so 1.1.post1 does not match clause
        == 1.1.post1  # Equal, so 1.1.post1 matches clause
        == 1.1.*      # Same prefix, so 1.1.post1 matches clause"""

    def test_strict_no_match(self) -> None:
        """== 1.1 does not match 1.1.post1."""
        assert Version("1.1.post1") not in Specifier("==1.1")

    def test_strict_exact_match(self) -> None:
        """== 1.1.post1 matches 1.1.post1."""
        assert Version("1.1.post1") in Specifier("==1.1.post1")

    def test_prefix_match(self) -> None:
        """== 1.1.* matches 1.1.post1."""
        assert Version("1.1.post1") in Specifier("==1.1.*")


class TestVersionMatchingAlphaExamples:
    r"""For purposes of prefix matching, the pre-release segment is considered to
    have an implied preceding ``.``, so given the version ``1.1a1``, the
    following clauses would match or not as shown::

        == 1.1        # Not equal, so 1.1a1 does not match clause
        == 1.1a1      # Equal, so 1.1a1 matches clause
        == 1.1.*      # Same prefix, so 1.1a1 matches clause
                      # if pre-releases are requested"""

    def test_strict_no_match(self) -> None:
        """== 1.1 does not match 1.1a1."""
        assert Version("1.1a1") not in Specifier("==1.1")

    def test_strict_exact_match(self) -> None:
        """== 1.1a1 matches 1.1a1."""
        assert Version("1.1a1") in Specifier("==1.1a1")

    def test_prefix_match_with_prereleases(self) -> None:
        """== 1.1.* matches 1.1a1 when pre-releases are requested."""
        spec = Specifier("==1.1.*")
        assert Version("1.1a1") in spec


class TestVersionMatchingExactExamples:
    r"""An exact match is also considered a prefix match (this interpretation is
    implied by the usual zero padding rules for the release segment of version
    identifiers). Given the version ``1.1``, the following clauses would
    match or not as shown::

        == 1.1        # Equal, so 1.1 matches clause
        == 1.1.0      # Zero padding expands 1.1 to 1.1.0, so it matches clause
        == 1.1.dev1   # Not equal (dev-release), so 1.1 does not match clause
        == 1.1a1      # Not equal (pre-release), so 1.1 does not match clause
        == 1.1.post1  # Not equal (post-release), so 1.1 does not match clause
        == 1.1.*      # Same prefix, so 1.1 matches clause"""

    def test_equal(self) -> None:
        """== 1.1 matches 1.1."""
        assert Version("1.1") in Specifier("==1.1")

    def test_zero_padding(self) -> None:
        """== 1.1.0 matches 1.1 via zero padding."""
        assert Version("1.1") in Specifier("==1.1.0")

    def test_dev_not_equal(self) -> None:
        """== 1.1.dev1 does not match 1.1."""
        assert Version("1.1") not in Specifier("==1.1.dev1")

    def test_pre_not_equal(self) -> None:
        """== 1.1a1 does not match 1.1."""
        assert Version("1.1") not in Specifier("==1.1a1")

    def test_post_not_equal(self) -> None:
        """== 1.1.post1 does not match 1.1."""
        assert Version("1.1") not in Specifier("==1.1.post1")

    def test_prefix_match(self) -> None:
        """== 1.1.* matches 1.1."""
        assert Version("1.1") in Specifier("==1.1.*")


class TestPrefixMatchInvalidForms:
    r"""It is invalid to have a prefix match containing a development or local release
    such as ``1.0.dev1.*`` or ``1.0+foo1.*``. If present, the development release
    segment is always the final segment in the public version, and the local version
    is ignored for comparison purposes, so using either in a prefix match wouldn't
    make any sense."""

    def test_dev_prefix_match_invalid(self) -> None:
        """== 1.0.dev1.* must be rejected."""
        with pytest.raises(InvalidSpecifier):
            Specifier("==1.0.dev1.*")

    def test_local_prefix_match_invalid(self) -> None:
        """== 1.0+foo1.* must be rejected."""
        with pytest.raises(InvalidSpecifier):
            Specifier("==1.0+foo1.*")

    @given(spec_ver=release_versions(), dev=small_ints)
    @SETTINGS
    def test_dev_prefix_match_invalid_general(
        self, spec_ver: Version, dev: int
    ) -> None:
        """== V.devN.* must always be rejected."""
        with pytest.raises(InvalidSpecifier):
            Specifier(f"=={spec_ver}.dev{dev}.*")


class TestLocalVersionMatchingPublic:
    r"""If the specified version identifier is a public version identifier (no
    local version label), then the local version label of any candidate versions
    MUST be ignored when matching versions."""

    @given(spec_ver=release_versions(), local=st.integers(min_value=0, max_value=5))
    @SETTINGS
    def test_public_specifier_ignores_local_label(
        self, spec_ver: Version, local: int
    ) -> None:
        """== V (public) matches V+localN because local label is ignored."""
        spec = Specifier(f"=={spec_ver}")
        candidate = Version(f"{spec_ver}+local{local}")
        assert candidate in spec

    @given(spec_ver=release_versions(), local=st.integers(min_value=0, max_value=5))
    @SETTINGS
    def test_public_wildcard_ignores_local_label(
        self, spec_ver: Version, local: int
    ) -> None:
        """== V.* (public) matches V.0+localN because local label is ignored."""
        spec = Specifier(f"=={spec_ver}.*")
        candidate = Version(f"{spec_ver}.0+local{local}")
        assert candidate in spec

    @given(
        spec_ver=release_versions(),
        local1=st.integers(min_value=0, max_value=5),
        local2=st.integers(min_value=0, max_value=5),
    )
    @SETTINGS
    def test_public_specifier_matches_any_local(
        self, spec_ver: Version, local1: int, local2: int
    ) -> None:
        """== V (public) matches V+localX for any local label."""
        spec = Specifier(f"=={spec_ver}")
        c1 = Version(f"{spec_ver}+local{local1}")
        c2 = Version(f"{spec_ver}+local{local2}")
        assert c1 in spec
        assert c2 in spec


class TestLocalVersionMatchingLocal:
    r"""If the specified version identifier is a local version identifier, then the
    local version labels of candidate versions MUST be considered when matching
    versions, with the public version identifier being matched as described
    above, and the local version label being checked for equivalence using a
    strict string equality comparison."""

    @given(spec_ver=release_versions(), local=st.integers(min_value=0, max_value=5))
    @SETTINGS
    def test_local_specifier_matches_same_local(
        self, spec_ver: Version, local: int
    ) -> None:
        """== V+localN matches V+localN (same local label)."""
        local_str = f"local{local}"
        spec = Specifier(f"=={spec_ver}+{local_str}")
        candidate = Version(f"{spec_ver}+{local_str}")
        assert candidate in spec

    @given(spec_ver=release_versions())
    @SETTINGS
    def test_local_specifier_does_not_match_different_local(
        self, spec_ver: Version
    ) -> None:
        """== V+local0 does not match V+local1 (different local label)."""
        spec = Specifier(f"=={spec_ver}+local0")
        candidate = Version(f"{spec_ver}+local1")
        assert candidate not in spec

    @given(spec_ver=release_versions(), local=st.integers(min_value=0, max_value=5))
    @SETTINGS
    def test_local_specifier_does_not_match_no_local(
        self, spec_ver: Version, local: int
    ) -> None:
        """== V+localN does not match V (no local label on candidate)."""
        spec = Specifier(f"=={spec_ver}+local{local}")
        assert spec_ver not in spec


class TestVersionExclusion:
    r"""A version exclusion clause includes the version exclusion operator ``!=``
    and a version identifier.

    The allowed version identifiers and comparison semantics are the same as
    those of the `Version matching`_ operator, except that the sense of any
    match is inverted."""

    @given(version=nonlocal_versions())
    @SETTINGS
    def test_exclusion_is_inverse_of_match(self, version: Version) -> None:
        """!= V is the logical inverse of == V for any version."""
        eq_spec = Specifier(f"=={version}")
        ne_spec = Specifier(f"!={version}")
        assert (version in eq_spec) != (version in ne_spec)

    @given(spec_ver=nonlocal_versions(), candidate=pep440_versions())
    @SETTINGS
    def test_exclusion_inverse_general(
        self, spec_ver: Version, candidate: Version
    ) -> None:
        """For any candidate, != V gives the opposite result of == V."""
        eq_spec = Specifier(f"=={spec_ver}")
        ne_spec = Specifier(f"!={spec_ver}")
        assert (candidate in eq_spec) != (candidate in ne_spec)

    @given(spec_ver=release_versions(), candidate=pep440_versions())
    @SETTINGS
    def test_prefix_exclusion_inverse(
        self, spec_ver: Version, candidate: Version
    ) -> None:
        """!= V.* is the inverse of == V.* for prefix matching."""
        eq_spec = Specifier(f"=={spec_ver}.*")
        ne_spec = Specifier(f"!={spec_ver}.*")
        assert (candidate in eq_spec) != (candidate in ne_spec)


class TestVersionExclusionPost1Examples:
    r"""For example, given the version ``1.1.post1``, the following clauses would
    match or not as shown::

        != 1.1        # Not equal, so 1.1.post1 matches clause
        != 1.1.post1  # Equal, so 1.1.post1 does not match clause
        != 1.1.*      # Same prefix, so 1.1.post1 does not match clause"""

    def test_not_equal_matches(self) -> None:
        """!= 1.1 matches 1.1.post1 (they are not equal)."""
        assert Version("1.1.post1") in Specifier("!=1.1")

    def test_equal_excludes(self) -> None:
        """!= 1.1.post1 does not match 1.1.post1 (they are equal)."""
        assert Version("1.1.post1") not in Specifier("!=1.1.post1")

    def test_prefix_excludes(self) -> None:
        """!= 1.1.* does not match 1.1.post1 (same prefix)."""
        assert Version("1.1.post1") not in Specifier("!=1.1.*")
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/test_version_format.py0000644000000000000000000006503715172742311020027 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

import pytest
from hypothesis import assume, given
from hypothesis import strategies as st

from packaging.version import InvalidVersion, Version
from tests.property.strategies import SETTINGS, VERSION_POOL, pre_tags

pytestmark = pytest.mark.property

versions = st.sampled_from(VERSION_POOL)


@st.composite
def generated_versions(draw: st.DrawFn) -> Version:
    """Generate a random valid PEP 440 version from parts."""
    epoch = draw(st.integers(min_value=0, max_value=3))
    num_release = draw(st.integers(min_value=1, max_value=5))
    release = tuple(
        draw(st.integers(min_value=0, max_value=99)) for _ in range(num_release)
    )

    has_pre = draw(st.booleans())
    pre = None
    if has_pre:
        pre_letter = draw(pre_tags)
        pre_num = draw(st.integers(min_value=0, max_value=10))
        pre = (pre_letter, pre_num)

    has_post = draw(st.booleans())
    post = draw(st.integers(min_value=0, max_value=10)) if has_post else None

    has_dev = draw(st.booleans())
    dev = draw(st.integers(min_value=0, max_value=10)) if has_dev else None

    has_local = draw(st.booleans())
    local = None
    if has_local:
        num_segs = draw(st.integers(min_value=1, max_value=3))
        segs = []
        for _ in range(num_segs):
            if draw(st.booleans()):
                segs.append(str(draw(st.integers(min_value=0, max_value=99))))
            else:
                segs.append(
                    draw(
                        st.text(
                            alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz"),
                            min_size=1,
                            max_size=4,
                        )
                    )
                )
        local = ".".join(segs)

    return Version.from_parts(
        epoch=epoch, release=release, pre=pre, post=post, dev=dev, local=local
    )


# to test whitespace stripping behavior.
@st.composite
def version_with_whitespace(draw: st.DrawFn) -> str:
    """Generate a version string potentially wrapped in whitespace."""
    v = draw(versions)
    leading = draw(st.sampled_from(["", " ", "  ", "\t"]))
    trailing = draw(st.sampled_from(["", " ", "  ", "\t"]))
    return leading + str(v) + trailing


class TestPublicVersionScheme:
    """The canonical public version identifiers MUST comply with the following
    scheme::

        [N!]N(.N)*[{a|b|rc}N][.postN][.devN]"""

    @given(version=generated_versions())
    @SETTINGS
    def test_canonical_format_matches_scheme(self, version: Version) -> None:
        """Every generated version, when stringified, matches the canonical
        pattern [N!]N(.N)*[{a|b|rc}N][.postN][.devN] (plus optional local)."""
        s = str(version)
        public = s.split("+", maxsplit=1)[0]
        # This regex matches the canonical public version format
        pattern = re.compile(
            r"^(?:(?P[0-9]+)!)?"
            r"(?P[0-9]+(?:\.[0-9]+)*)"
            r"(?:(?P
(?:a|b|rc)[0-9]+))?"
            r"(?:\.post(?P[0-9]+))?"
            r"(?:\.dev(?P[0-9]+))?$"
        )
        assert pattern.match(public), f"{public!r} does not match canonical format"

    @given(version=generated_versions())
    @SETTINGS
    def test_str_round_trip_is_canonical(self, version: Version) -> None:
        """The string representation of a parsed version is already canonical,
        so parsing it again yields the same string."""
        assert str(Version(str(version))) == str(version)


class TestPublicVersionNoWhitespace:
    """Public version identifiers MUST NOT include leading or trailing whitespace."""

    @given(vs=version_with_whitespace())
    @SETTINGS
    def test_whitespace_stripped_on_parse(self, vs: str) -> None:
        """Leading/trailing whitespace is stripped during parsing. The
        resulting normalized string has no whitespace."""
        v = Version(vs)
        s = str(v)
        assert s == s.strip()
        assert not s.startswith(" ")
        assert not s.endswith(" ")


class TestPublicVersionUniqueness:
    """Public version identifiers MUST be unique within a given distribution."""

    def test_no_properties(self) -> None:
        # Advisory/definitional text about distribution-level uniqueness,
        # no testable properties at the version object level.
        pass


class TestNonCompliantVersionHandling:
    """Installation tools SHOULD ignore any public versions which do not comply with
    this scheme but MUST also include the normalizations specified below.
    Installation tools MAY warn the user when non-compliant or ambiguous versions
    are detected."""

    @given(
        garbage=st.text(
            alphabet=st.sampled_from("!@#$%^&()={}[]|\\:;<>,?/~`"),
            min_size=1,
            max_size=10,
        )
    )
    @SETTINGS
    def test_non_compliant_strings_raise(self, garbage: str) -> None:
        """Strings that are clearly not PEP 440 versions raise InvalidVersion."""
        with pytest.raises(InvalidVersion):
            Version(garbage)


class TestVersionRegexReference:
    """See also :ref:`version-specifiers-regex` which provides a regular
    expression to check strict conformance with the canonical format, as
    well as a more permissive regular expression accepting inputs that may
    require subsequent normalization."""

    def test_no_properties(self) -> None:
        # Reference text, no testable properties.
        pass


class TestVersionSegments:
    """Public version identifiers are separated into up to five segments:

    * Epoch segment: ``N!``
    * Release segment: ``N(.N)*``
    * Pre-release segment: ``{a|b|rc}N``
    * Post-release segment: ``.postN``
    * Development release segment: ``.devN``"""

    @given(version=generated_versions())
    @SETTINGS
    def test_epoch_is_nonnegative_int(self, version: Version) -> None:
        """The epoch segment is a non-negative integer."""
        assert isinstance(version.epoch, int)
        assert version.epoch >= 0

    @given(version=generated_versions())
    @SETTINGS
    def test_release_is_tuple_of_nonneg_ints(self, version: Version) -> None:
        """The release segment is a non-empty tuple of non-negative integers."""
        assert isinstance(version.release, tuple)
        assert len(version.release) >= 1
        for component in version.release:
            assert isinstance(component, int)
            assert component >= 0

    @given(version=generated_versions())
    @SETTINGS
    def test_pre_format(self, version: Version) -> None:
        """If present, pre is a tuple (letter, number) where letter is
        a, b, or rc and number is a non-negative int."""
        if version.pre is not None:
            letter, number = version.pre
            assert letter in ("a", "b", "rc")
            assert isinstance(number, int)
            assert number >= 0

    @given(version=generated_versions())
    @SETTINGS
    def test_post_format(self, version: Version) -> None:
        """If present, post is a non-negative integer."""
        if version.post is not None:
            assert isinstance(version.post, int)
            assert version.post >= 0

    @given(version=generated_versions())
    @SETTINGS
    def test_dev_format(self, version: Version) -> None:
        """If present, dev is a non-negative integer."""
        if version.dev is not None:
            assert isinstance(version.dev, int)
            assert version.dev >= 0


class TestReleaseKinds:
    """Any given release will be a "final release", "pre-release", "post-release" or
    "developmental release" as defined in the following sections."""

    @given(version=generated_versions())
    @SETTINGS
    def test_release_kind_categories(self, version: Version) -> None:
        """Every version falls into at least one of the recognized release
        kinds: final, pre-release, post-release, or developmental release."""
        is_final = version.pre is None and version.post is None and version.dev is None
        is_pre = version.is_prerelease
        is_post = version.is_postrelease
        is_dev = version.is_devrelease
        # At least one category must apply
        assert is_final or is_pre or is_post or is_dev


class TestNumericComponentsNonNegative:
    """All numeric components MUST be non-negative integers represented as sequences
    of ASCII digits."""

    @given(version=generated_versions())
    @SETTINGS
    def test_all_numeric_components_nonneg(self, version: Version) -> None:
        """Every numeric component of a version is a non-negative integer."""
        assert version.epoch >= 0
        for r in version.release:
            assert r >= 0
        if version.pre is not None:
            assert version.pre[1] >= 0
        if version.post is not None:
            assert version.post >= 0
        if version.dev is not None:
            assert version.dev >= 0

    @given(version=generated_versions())
    @SETTINGS
    def test_stringified_numerics_are_ascii_digits(self, version: Version) -> None:
        """When stringified, all numeric parts are pure ASCII digit sequences."""
        s = str(version)
        # Extract all numeric runs from the version string
        for num in re.findall(r"[0-9]+", s):
            assert num.isascii()
            assert num.isdigit()


class TestNumericComponentOrdering:
    """All numeric components MUST be interpreted and ordered according to their
    numeric value, not as text strings."""

    @given(
        number_a=st.integers(min_value=0, max_value=200),
        number_b=st.integers(min_value=0, max_value=200),
    )
    @SETTINGS
    def test_release_numeric_ordering(self, number_a: int, number_b: int) -> None:
        """Release segment components are compared numerically: 9 < 10,
        not lexicographically where "9" > "10"."""
        va = Version(f"{number_a}.0")
        vb = Version(f"{number_b}.0")
        if number_a < number_b:
            assert va < vb
        elif number_a == number_b:
            assert va == vb
        else:
            assert va > vb

    @given(
        number_a=st.integers(min_value=0, max_value=200),
        number_b=st.integers(min_value=0, max_value=200),
    )
    @SETTINGS
    def test_epoch_numeric_ordering(self, number_a: int, number_b: int) -> None:
        """Epoch components are compared numerically."""
        va = Version(f"{number_a}!1.0")
        vb = Version(f"{number_b}!1.0")
        if number_a < number_b:
            assert va < vb
        elif number_a == number_b:
            assert va == vb
        else:
            assert va > vb

    @given(
        number_a=st.integers(min_value=0, max_value=50),
        number_b=st.integers(min_value=0, max_value=50),
    )
    @SETTINGS
    def test_post_numeric_ordering(self, number_a: int, number_b: int) -> None:
        """Post-release numbers are compared numerically."""
        va = Version(f"1.0.post{number_a}")
        vb = Version(f"1.0.post{number_b}")
        if number_a < number_b:
            assert va < vb
        elif number_a == number_b:
            assert va == vb
        else:
            assert va > vb

    @given(
        number_a=st.integers(min_value=0, max_value=50),
        number_b=st.integers(min_value=0, max_value=50),
    )
    @SETTINGS
    def test_dev_numeric_ordering(self, number_a: int, number_b: int) -> None:
        """Dev-release numbers are compared numerically."""
        va = Version(f"1.0.dev{number_a}")
        vb = Version(f"1.0.dev{number_b}")
        if number_a < number_b:
            assert va < vb
        elif number_a == number_b:
            assert va == vb
        else:
            assert va > vb

    @given(
        number_a=st.integers(min_value=0, max_value=50),
        number_b=st.integers(min_value=0, max_value=50),
    )
    @SETTINGS
    def test_pre_numeric_ordering(self, number_a: int, number_b: int) -> None:
        """Pre-release numbers within the same kind are compared numerically."""
        va = Version(f"1.0a{number_a}")
        vb = Version(f"1.0a{number_b}")
        if number_a < number_b:
            assert va < vb
        elif number_a == number_b:
            assert va == vb
        else:
            assert va > vb


class TestNumericComponentZero:
    """All numeric components MAY be zero. Except as described below for the
    release segment, a numeric component of zero has no special significance
    aside from always being the lowest possible value in the version ordering."""

    @given(
        number=st.integers(min_value=1, max_value=50),
    )
    @SETTINGS
    def test_zero_is_lowest_pre(self, number: int) -> None:
        """a0 is the lowest alpha pre-release."""
        assert Version("1.0a0") <= Version(f"1.0a{number}")

    @given(
        number=st.integers(min_value=1, max_value=50),
    )
    @SETTINGS
    def test_zero_is_lowest_post(self, number: int) -> None:
        """post0 is the lowest post-release."""
        assert Version("1.0.post0") <= Version(f"1.0.post{number}")

    @given(
        number=st.integers(min_value=1, max_value=50),
    )
    @SETTINGS
    def test_zero_is_lowest_dev(self, number: int) -> None:
        """dev0 is the lowest dev-release."""
        assert Version("1.0.dev0") <= Version(f"1.0.dev{number}")

    @given(
        number=st.integers(min_value=1, max_value=50),
    )
    @SETTINGS
    def test_zero_is_lowest_epoch(self, number: int) -> None:
        """Epoch 0 is the lowest epoch value."""
        assert Version("0!1.0") <= Version(f"{number}!1.0")

    def test_zero_components_are_valid(self) -> None:
        """All segments accept zero values without error."""
        v = Version("0!0.0.0a0.post0.dev0")
        assert v.epoch == 0
        assert v.release == (0, 0, 0)
        assert v.pre == ("a", 0)
        assert v.post == 0
        assert v.dev == 0


class TestVersioningPracticesNote:
    """.. note::

    Some hard to read version identifiers are permitted by this scheme in
    order to better accommodate the wide range of versioning practices
    across existing public and private Python projects.

    Accordingly, some of the versioning practices which are technically
    permitted by the specification are strongly discouraged for new projects. Where
    this is the case, the relevant details are noted in the following
    sections."""

    def test_no_properties(self) -> None:
        # Advisory note about versioning practices, no testable properties.
        pass


class TestLocalVersionScheme:
    """Local version identifiers MUST comply with the following scheme::

        [+]

    They consist of a normal public version identifier (as defined in the
    previous section), along with an arbitrary "local version label", separated
    from the public version identifier by a plus. Local version labels have
    no specific semantics assigned, but some syntactic restrictions are imposed."""

    @given(version=generated_versions())
    @SETTINGS
    def test_local_separated_by_plus(self, version: Version) -> None:
        """If a version has a local segment, its string representation
        contains exactly one '+' separating public and local parts."""
        s = str(version)
        if version.local is not None:
            assert "+" in s
            parts = s.split("+", 1)
            assert len(parts) == 2
            assert parts[1] == version.local
        else:
            assert "+" not in s

    @given(version=generated_versions())
    @SETTINGS
    def test_public_property_strips_local(self, version: Version) -> None:
        """The .public property returns the version without the local label."""
        public = version.public
        assert "+" not in public
        if version.local is not None:
            assert str(version).startswith(public + "+")
        else:
            assert public == str(version)


class TestLocalVersionPurpose:
    """Local version identifiers are used to denote fully API (and, if applicable,
    ABI) compatible patched versions of upstream projects. For example, these
    may be created by application developers and system integrators by applying
    specific backported bug fixes when upgrading to a new upstream release would
    be too disruptive to the application or other integrated system (such as a
    Linux distribution)."""

    def test_no_properties(self) -> None:
        # Advisory/definitional text about the purpose of local versions,
        # no testable properties.
        pass


class TestLocalVersionDifferentiation:
    """The inclusion of the local version label makes it possible to differentiate
    upstream releases from potentially altered rebuilds by downstream
    integrators. The use of a local version identifier does not affect the kind
    of a release but, when applied to a source distribution, does indicate that
    it may not contain the exact same code as the corresponding upstream release."""

    @given(version=generated_versions())
    @SETTINGS
    def test_local_does_not_affect_release_kind(self, version: Version) -> None:
        """Adding a local label does not change is_prerelease, is_postrelease,
        or is_devrelease."""
        assume(version.local is None)
        v_with_local = Version(str(version) + "+local1")
        assert version.is_prerelease == v_with_local.is_prerelease
        assert version.is_postrelease == v_with_local.is_postrelease
        assert version.is_devrelease == v_with_local.is_devrelease


class TestLocalVersionPermittedCharacters:
    """To ensure local version identifiers can be readily incorporated as part of
    filenames and URLs, and to avoid formatting inconsistencies in hexadecimal
    hash representations, local version labels MUST be limited to the following
    set of permitted characters:

    * ASCII letters (``[a-zA-Z]``)
    * ASCII digits (``[0-9]``)
    * periods (``.``)"""

    @given(version=generated_versions())
    @SETTINGS
    def test_local_label_characters(self, version: Version) -> None:
        """The normalized local label contains only ASCII letters, digits,
        and periods."""
        if version.local is not None:
            for ch in version.local:
                assert ch in "abcdefghijklmnopqrstuvwxyz0123456789.", (
                    f"Unexpected character {ch!r} in local label {version.local!r}"
                )

    @given(
        bad_local=st.text(
            alphabet=st.sampled_from("!@#$%^&*()={}[]|\\:;<>,?/~` "),
            min_size=1,
            max_size=5,
        )
    )
    @SETTINGS
    def test_invalid_local_characters_rejected(self, bad_local: str) -> None:
        """Versions with local labels containing forbidden characters
        are rejected."""
        with pytest.raises(InvalidVersion):
            Version(f"1.0+{bad_local}")


class TestLocalVersionStartEnd:
    """Local version labels MUST start and end with an ASCII letter or digit."""

    def test_local_cannot_start_with_period(self) -> None:
        """A local label starting with a period is rejected."""
        with pytest.raises(InvalidVersion):
            Version("1.0+.abc")

    def test_local_cannot_end_with_period(self) -> None:
        """A local label ending with a period is rejected."""
        with pytest.raises(InvalidVersion):
            Version("1.0+abc.")

    @given(version=generated_versions())
    @SETTINGS
    def test_normalized_local_starts_ends_alnum(self, version: Version) -> None:
        """The normalized local label always starts and ends with an
        alphanumeric character."""
        if version.local is not None:
            assert version.local[0].isalnum()
            assert version.local[-1].isalnum()


class TestLocalVersionComparison:
    """Comparison and ordering of local versions considers each segment of the local
    version (divided by a ``.``) separately. If a segment consists entirely of
    ASCII digits then that section should be considered an integer for comparison
    purposes and if a segment contains any ASCII letters then that segment is
    compared lexicographically with case insensitivity. When comparing a numeric
    and lexicographic segment, the numeric section always compares as greater than
    the lexicographic segment. Additionally a local version with a greater number of
    segments will always compare as greater than a local version with fewer
    segments, as long as the shorter local version's segments match the beginning
    of the longer local version's segments exactly."""

    @given(
        number_a=st.integers(min_value=0, max_value=200),
        number_b=st.integers(min_value=0, max_value=200),
    )
    @SETTINGS
    def test_numeric_segments_compared_as_integers(
        self, number_a: int, number_b: int
    ) -> None:
        """Purely numeric local segments are compared as integers, not strings."""
        va = Version(f"1.0+{number_a}")
        vb = Version(f"1.0+{number_b}")
        if number_a < number_b:
            assert va < vb
        elif number_a == number_b:
            assert va == vb
        else:
            assert va > vb

    @given(
        label=st.text(
            alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz"),
            min_size=1,
            max_size=6,
        )
    )
    @SETTINGS
    def test_alpha_segments_case_insensitive(self, label: str) -> None:
        """Local version segments with letters compare case-insensitively."""
        lower = Version(f"1.0+{label.lower()}")
        upper = Version(f"1.0+{label.upper()}")
        assert lower == upper

    @given(
        number=st.integers(min_value=0, max_value=100),
        label=st.text(
            alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz"),
            min_size=1,
            max_size=6,
        ),
    )
    @SETTINGS
    def test_numeric_greater_than_lexicographic(self, number: int, label: str) -> None:
        """A numeric local segment always compares greater than a
        lexicographic segment."""
        v_num = Version(f"1.0+{number}")
        v_str = Version(f"1.0+{label}")
        assert v_num > v_str

    @given(
        seg=st.text(
            alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz0123456789"),
            min_size=1,
            max_size=4,
        ),
        extra=st.text(
            alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz0123456789"),
            min_size=1,
            max_size=4,
        ),
    )
    @SETTINGS
    def test_longer_local_greater_when_prefix_matches(
        self, seg: str, extra: str
    ) -> None:
        """A local version with more segments compares greater when the
        shorter one's segments match the beginning of the longer exactly."""
        v_short = Version(f"1.0+{seg}")
        v_long = Version(f"1.0+{seg}.{extra}")
        assert v_long > v_short

    @given(
        label_a=st.text(
            alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz"),
            min_size=1,
            max_size=5,
        ),
        label_b=st.text(
            alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz"),
            min_size=1,
            max_size=5,
        ),
    )
    @SETTINGS
    def test_alpha_segments_lexicographic_order(
        self, label_a: str, label_b: str
    ) -> None:
        """Purely alphabetic local segments compare lexicographically
        (case insensitive)."""
        va = Version(f"1.0+{label_a}")
        vb = Version(f"1.0+{label_b}")
        a_low = label_a.lower()
        b_low = label_b.lower()
        if a_low < b_low:
            assert va < vb
        elif a_low == b_low:
            assert va == vb
        else:
            assert va > vb


class TestUpstreamDownstreamDefinition:
    """An "upstream project" is a project that defines its own public versions. A
    "downstream project" is one which tracks and redistributes an upstream project,
    potentially backporting security and bug fixes from later versions of the
    upstream project."""

    def test_no_properties(self) -> None:
        # Definitional text, no testable properties.
        pass


class TestLocalVersionPublishingGuidance:
    """Local version identifiers SHOULD NOT be used when publishing upstream
    projects to a public index server, but MAY be used to identify private
    builds created directly from the project source. Local
    version identifiers SHOULD be used by downstream projects when releasing a
    version that is API compatible with the version of the upstream project
    identified by the public version identifier, but contains additional changes
    (such as bug fixes). As the Python Package Index is intended solely for
    indexing and hosting upstream projects, it MUST NOT allow the use of local
    version identifiers."""

    def test_no_properties(self) -> None:
        # Policy/advisory text about publishing, no testable properties
        # at the version object level.
        pass


class TestSourceDistributionMetadata:
    """Source distributions using a local version identifier SHOULD provide the
    ``python.integrator`` extension metadata (as defined in :pep:`459`)."""

    def test_no_properties(self) -> None:
        # Advisory text about source distribution metadata,
        # no testable properties at the version object level.
        pass


class TestLocalVersionDoesNotAffectPublicOrdering:
    """Comparison and ordering of local versions considers each segment of the local
    version (divided by a ``.``) separately. If a segment consists entirely of
    ASCII digits then that section should be considered an integer for comparison
    purposes and if a segment contains any ASCII letters then that segment is
    compared lexicographically with case insensitivity. When comparing a numeric
    and lexicographic segment, the numeric section always compares as greater than
    the lexicographic segment. Additionally a local version with a greater number of
    segments will always compare as greater than a local version with fewer
    segments, as long as the shorter local version's segments match the beginning
    of the longer local version's segments exactly."""

    @given(version=versions)
    @SETTINGS
    def test_version_with_local_greater_than_without(self, version: Version) -> None:
        """A version with a local segment is greater than the same version
        without one (local versions sort after the public version)."""
        assume(version.local is None)
        v_local = Version(str(version) + "+1")
        assert v_local > version

    @given(version=versions)
    @SETTINGS
    def test_two_locals_share_public(self, version: Version) -> None:
        """Two versions differing only in local label share the same
        .public property."""
        assume(version.local is None)
        v1 = Version(str(version) + "+abc")
        v2 = Version(str(version) + "+xyz")
        assert v1.public == v2.public == str(version)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/test_version_normalization.py0000644000000000000000000006010715172742311021416 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 hypothesis import given
from hypothesis import strategies as st

from packaging.version import InvalidVersion, Version
from tests.property.strategies import (
    SETTINGS,
    pre_tags,
    release_segment,
    small_ints,
)

pytestmark = pytest.mark.property

# Values of varying digit lengths for leading-zero stripping ("007" -> "7").
_ints_for_padding = st.sampled_from([0, 5, 12, 123, 1234, 99999])


@st.composite
def padded_int(draw: st.DrawFn) -> str:
    """An integer with optional leading zeros, e.g. '007'."""
    val = draw(_ints_for_padding)
    padding = draw(st.integers(min_value=0, max_value=4))
    return "0" * padding + str(val)


@st.composite
def padded_release(draw: st.DrawFn) -> tuple[str, str]:
    """A release segment with padded ints, returning (padded, normalized)."""
    count = draw(st.integers(min_value=1, max_value=4))
    padded_parts = []
    normal_parts = []
    for _ in range(count):
        val = draw(_ints_for_padding)
        padding = draw(st.integers(min_value=0, max_value=4))
        padded_parts.append("0" * padding + str(val))
        normal_parts.append(str(val))
    return ".".join(padded_parts), ".".join(normal_parts)


class TestCaseSensitivity:
    """In order to maintain better compatibility with existing versions there are a
    number of "alternative" syntaxes that MUST be taken into account when parsing
    versions. These syntaxes MUST be considered when parsing a version, however
    they should be "normalized" to the standard syntax defined above.

    All ascii letters should be interpreted case insensitively within a version and
    the normal form is lowercase. This allows versions such as ``1.1RC1`` which
    would be normalized to ``1.1rc1``."""

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_num=small_ints,
    )
    @SETTINGS
    def test_pre_release_case_insensitive(
        self, release: str, pre_type: str, pre_num: int
    ) -> None:
        """Pre-release letters parse the same regardless of case."""
        lower = f"{release}{pre_type}{pre_num}"
        upper = f"{release}{pre_type.upper()}{pre_num}"
        mixed = f"{release}{pre_type.capitalize()}{pre_num}"
        v_lower = Version(lower)
        assert Version(upper) == v_lower
        assert Version(mixed) == v_lower

    @given(release=release_segment, post_num=small_ints)
    @SETTINGS
    def test_post_release_case_insensitive(self, release: str, post_num: int) -> None:
        """'post' is case insensitive."""
        normal = Version(f"{release}.post{post_num}")
        assert Version(f"{release}.POST{post_num}") == normal
        assert Version(f"{release}.Post{post_num}") == normal

    @given(release=release_segment, dev_num=small_ints)
    @SETTINGS
    def test_dev_release_case_insensitive(self, release: str, dev_num: int) -> None:
        """'dev' is case insensitive."""
        normal = Version(f"{release}.dev{dev_num}")
        assert Version(f"{release}.DEV{dev_num}") == normal
        assert Version(f"{release}.Dev{dev_num}") == normal

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_num=small_ints,
    )
    @SETTINGS
    def test_normal_form_is_lowercase(
        self, release: str, pre_type: str, pre_num: int
    ) -> None:
        """The normalized string form uses lowercase."""
        v = Version(f"{release}{pre_type.upper()}{pre_num}")
        assert pre_type in str(v)
        assert pre_type.upper() not in str(v) or pre_type == pre_type.upper()


class TestIntegerNormalization:
    """All integers are interpreted via the ``int()`` built in and normalize to the
    string form of the output. This means that an integer version of ``00`` would
    normalize to ``0`` while ``09000`` would normalize to ``9000``. This does not
    hold true for integers inside of an alphanumeric segment of a local version
    such as ``1.0+foo0100`` which is already in its normalized form."""

    @given(data=padded_release())
    @SETTINGS
    def test_release_integers_normalized(self, data: tuple[str, str]) -> None:
        """Leading zeros in release segments are stripped."""
        padded, normalized = data
        v = Version(padded)
        assert str(v) == normalized

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_num=padded_int(),
    )
    @SETTINGS
    def test_pre_release_integer_normalized(
        self, release: str, pre_type: str, pre_num: str
    ) -> None:
        """Leading zeros in pre-release numbers are stripped."""
        v = Version(f"{release}{pre_type}{pre_num}")
        expected_num = str(int(pre_num))
        assert str(v).endswith(f"{pre_type}{expected_num}")

    @given(release=release_segment, post_num=padded_int())
    @SETTINGS
    def test_post_release_integer_normalized(self, release: str, post_num: str) -> None:
        """Leading zeros in post-release numbers are stripped."""
        v = Version(f"{release}.post{post_num}")
        assert f".post{int(post_num)}" in str(v)

    @given(release=release_segment, dev_num=padded_int())
    @SETTINGS
    def test_dev_release_integer_normalized(self, release: str, dev_num: str) -> None:
        """Leading zeros in dev-release numbers are stripped."""
        v = Version(f"{release}.dev{dev_num}")
        assert f".dev{int(dev_num)}" in str(v)

    @given(
        release=release_segment,
        alpha_segment=st.from_regex(r"[a-zA-Z]+[0-9]+", fullmatch=True),
    )
    @SETTINGS
    def test_local_alphanumeric_not_normalized(
        self, release: str, alpha_segment: str
    ) -> None:
        """Integers inside alphanumeric local segments are preserved."""
        version_str = f"{release}+{alpha_segment}"
        v = Version(version_str)
        local_str = str(v).split("+", 1)[1]
        # The local part should preserve the alphanumeric segment as-is
        # (lowercased, but digits unchanged).
        assert local_str == alpha_segment.lower()


class TestPreReleaseSeparators:
    """Pre-releases should allow a ``.``, ``-``, or ``_`` separator between the
    release segment and the pre-release segment. The normal form for this is
    without a separator. This allows versions such as ``1.1.a1`` or ``1.1-a1``
    which would be normalized to ``1.1a1``. It should also allow a separator to
    be used between the pre-release signifier and the numeral. This allows versions
    such as ``1.0a.1`` which would be normalized to ``1.0a1``."""

    @given(
        release=release_segment,
        sep=st.sampled_from([".", "-", "_"]),
        pre_type=pre_tags,
        pre_num=small_ints,
    )
    @SETTINGS
    def test_separator_before_pre_release(
        self, release: str, sep: str, pre_type: str, pre_num: int
    ) -> None:
        """Separators between release and pre-release normalize away."""
        with_sep = Version(f"{release}{sep}{pre_type}{pre_num}")
        without_sep = Version(f"{release}{pre_type}{pre_num}")
        assert with_sep == without_sep
        assert str(with_sep) == str(without_sep)

    @given(
        release=release_segment,
        sep=st.sampled_from([".", "-", "_"]),
        pre_type=pre_tags,
        pre_num=small_ints,
    )
    @SETTINGS
    def test_separator_between_signifier_and_numeral(
        self, release: str, sep: str, pre_type: str, pre_num: int
    ) -> None:
        """Separators between pre-release signifier and number normalize away."""
        with_sep = Version(f"{release}{pre_type}{sep}{pre_num}")
        without_sep = Version(f"{release}{pre_type}{pre_num}")
        assert with_sep == without_sep
        assert str(with_sep) == str(without_sep)

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_num=small_ints,
    )
    @SETTINGS
    def test_normal_form_has_no_separator(
        self, release: str, pre_type: str, pre_num: int
    ) -> None:
        """The normalized string has no separator before the pre-release."""
        v = Version(f"{release}.{pre_type}{pre_num}")
        normalized = str(v)
        # The normalized form should directly adjoin release digits and pre type.
        # Verify by reparsing: the str form shouldn't have ..
        assert f".{pre_type}" not in normalized or normalized.count(
            "."
        ) == release.count(".")


class TestPreReleaseSpelling:
    """Pre-releases allow the additional spellings of ``alpha``, ``beta``, ``c``,
    ``pre``, and ``preview`` for ``a``, ``b``, ``rc``, ``rc``, and ``rc``
    respectively. This allows versions such as ``1.1alpha1``, ``1.1beta2``, or
    ``1.1c3`` which normalize to ``1.1a1``, ``1.1b2``, and ``1.1rc3``. In every
    case the additional spelling should be considered equivalent to their normal
    forms."""

    @given(release=release_segment, pre_num=small_ints)
    @SETTINGS
    def test_alpha_spelling(self, release: str, pre_num: int) -> None:
        """'alpha' normalizes to 'a'."""
        assert Version(f"{release}alpha{pre_num}") == Version(f"{release}a{pre_num}")
        assert "a" in str(Version(f"{release}alpha{pre_num}"))

    @given(release=release_segment, pre_num=small_ints)
    @SETTINGS
    def test_beta_spelling(self, release: str, pre_num: int) -> None:
        """'beta' normalizes to 'b'."""
        assert Version(f"{release}beta{pre_num}") == Version(f"{release}b{pre_num}")
        assert "b" in str(Version(f"{release}beta{pre_num}"))

    @given(
        release=release_segment,
        alt=st.sampled_from(["c", "pre", "preview"]),
        pre_num=small_ints,
    )
    @SETTINGS
    def test_rc_spellings(self, release: str, alt: str, pre_num: int) -> None:
        """'c', 'pre', and 'preview' all normalize to 'rc'."""
        assert Version(f"{release}{alt}{pre_num}") == Version(f"{release}rc{pre_num}")
        assert "rc" in str(Version(f"{release}{alt}{pre_num}"))

    @given(
        release=release_segment,
        spelling=st.sampled_from(
            [
                ("alpha", "a"),
                ("beta", "b"),
                ("c", "rc"),
                ("pre", "rc"),
                ("preview", "rc"),
            ]
        ),
        pre_num=small_ints,
    )
    @SETTINGS
    def test_normalized_form_uses_short_spelling(
        self, release: str, spelling: tuple[str, str], pre_num: int
    ) -> None:
        """The str() output always uses the short form."""
        alt, short = spelling
        v = Version(f"{release}{alt}{pre_num}")
        normalized = str(v)
        assert short in normalized
        # The long spelling should not appear in the output. For 'c' -> 'rc',
        # 'c' is a substring of 'rc' so we check that the pre-release tag is
        # exactly 'rc', not just 'c'.
        if alt in ("alpha", "beta", "preview"):
            assert alt not in normalized
        elif alt == "pre":
            # 'pre' should not appear outside of being part of another word
            assert "pre" not in normalized.split("rc", maxsplit=1)[0]


class TestImplicitPreReleaseNumber:
    """Pre releases allow omitting the numeral in which case it is implicitly assumed
    to be ``0``. The normal form for this is to include the ``0`` explicitly. This
    allows versions such as ``1.2a`` which is normalized to ``1.2a0``."""

    @given(
        release=release_segment,
        pre_type=pre_tags,
    )
    @SETTINGS
    def test_omitted_numeral_equals_zero(self, release: str, pre_type: str) -> None:
        """Omitting the pre-release number is the same as 0."""
        assert Version(f"{release}{pre_type}") == Version(f"{release}{pre_type}0")

    @given(
        release=release_segment,
        pre_type=pre_tags,
    )
    @SETTINGS
    def test_normalized_form_includes_zero(self, release: str, pre_type: str) -> None:
        """The normalized string explicitly includes 0."""
        v = Version(f"{release}{pre_type}")
        assert str(v).endswith(f"{pre_type}0")


class TestPostReleaseSeparators:
    """Post releases allow a ``.``, ``-``, or ``_`` separator as well as omitting the
    separator all together. The normal form of this is with the ``.`` separator.
    This allows versions such as ``1.2-post2`` or ``1.2post2`` which normalize to
    ``1.2.post2``. Like the pre-release separator this also allows an optional
    separator between the post release signifier and the numeral. This allows
    versions like ``1.2.post-2`` which would normalize to ``1.2.post2``."""

    @given(
        release=release_segment,
        sep=st.sampled_from([".", "-", "_", ""]),
        post_num=small_ints,
    )
    @SETTINGS
    def test_separator_before_post(self, release: str, sep: str, post_num: int) -> None:
        """All separators (and none) before 'post' normalize to '.'."""
        v = Version(f"{release}{sep}post{post_num}")
        expected = Version(f"{release}.post{post_num}")
        assert v == expected
        assert str(v) == str(expected)

    @given(
        release=release_segment,
        sep=st.sampled_from([".", "-", "_"]),
        post_num=small_ints,
    )
    @SETTINGS
    def test_separator_between_post_and_numeral(
        self, release: str, sep: str, post_num: int
    ) -> None:
        """Separators between 'post' and the number normalize away."""
        v = Version(f"{release}.post{sep}{post_num}")
        expected = Version(f"{release}.post{post_num}")
        assert v == expected
        assert str(v) == str(expected)

    @given(release=release_segment, post_num=small_ints)
    @SETTINGS
    def test_normal_form_uses_dot_separator(self, release: str, post_num: int) -> None:
        """The normalized string uses '.' before 'post'."""
        v = Version(f"{release}-post{post_num}")
        assert f".post{post_num}" in str(v)


class TestPostReleaseSpelling:
    """Post-releases allow the additional spellings of ``rev`` and ``r``. This allows
    versions such as ``1.0-r4`` which normalizes to ``1.0.post4``. As with the
    pre-releases the additional spellings should be considered equivalent to their
    normal forms."""

    @given(
        release=release_segment,
        alt=st.sampled_from(["rev", "r"]),
        post_num=small_ints,
    )
    @SETTINGS
    def test_alt_spellings_equal_post(
        self, release: str, alt: str, post_num: int
    ) -> None:
        """'rev' and 'r' normalize to 'post'."""
        v_alt = Version(f"{release}-{alt}{post_num}")
        v_normal = Version(f"{release}.post{post_num}")
        assert v_alt == v_normal
        assert str(v_alt) == str(v_normal)

    @given(
        release=release_segment,
        alt=st.sampled_from(["rev", "r"]),
        post_num=small_ints,
    )
    @SETTINGS
    def test_normalized_form_uses_post(
        self, release: str, alt: str, post_num: int
    ) -> None:
        """The str() output uses 'post', not the alternative spelling."""
        v = Version(f"{release}-{alt}{post_num}")
        assert ".post" in str(v)
        assert alt not in str(v) or alt == "r"  # 'r' appears in many words


class TestImplicitPostReleaseNumber:
    """Post releases allow omitting the numeral in which case it is implicitly assumed
    to be ``0``. The normal form for this is to include the ``0`` explicitly. This
    allows versions such as ``1.2.post`` which is normalized to ``1.2.post0``."""

    @given(release=release_segment)
    @SETTINGS
    def test_omitted_numeral_equals_zero(self, release: str) -> None:
        """Omitting the post number is the same as post0."""
        assert Version(f"{release}.post") == Version(f"{release}.post0")

    @given(release=release_segment)
    @SETTINGS
    def test_normalized_form_includes_zero(self, release: str) -> None:
        """The normalized string explicitly includes 0."""
        v = Version(f"{release}.post")
        assert str(v).endswith(".post0")


class TestImplicitPostReleases:
    """Post releases allow omitting the ``post`` signifier all together. When using
    this form the separator MUST be ``-`` and no other form is allowed. This allows
    versions such as ``1.0-1`` to be normalized to ``1.0.post1``. This particular
    normalization MUST NOT be used in conjunction with the implicit post release
    number rule. In other words, ``1.0-`` is *not* a valid version and it does *not*
    normalize to ``1.0.post0``."""

    @given(
        release=release_segment,
        post_num=st.integers(min_value=1, max_value=999),
    )
    @SETTINGS
    def test_dash_number_is_implicit_post(self, release: str, post_num: int) -> None:
        """'release-N' normalizes to 'release.postN'."""
        v = Version(f"{release}-{post_num}")
        expected = Version(f"{release}.post{post_num}")
        assert v == expected
        assert str(v) == str(expected)

    @given(release=release_segment)
    @SETTINGS
    def test_dash_without_number_is_invalid(self, release: str) -> None:
        """'release-' is not a valid version."""
        with pytest.raises(InvalidVersion):
            Version(f"{release}-")


class TestDevelopmentReleaseSeparators:
    """Development releases allow a ``.``, ``-``, or a ``_`` separator as well as
    omitting the separator all together. The normal form of this is with the ``.``
    separator. This allows versions such as ``1.2-dev2`` or ``1.2dev2`` which
    normalize to ``1.2.dev2``."""

    @given(
        release=release_segment,
        sep=st.sampled_from([".", "-", "_", ""]),
        dev_num=small_ints,
    )
    @SETTINGS
    def test_all_separators_normalize_to_dot(
        self, release: str, sep: str, dev_num: int
    ) -> None:
        """All separators (and none) before 'dev' normalize to '.'."""
        v = Version(f"{release}{sep}dev{dev_num}")
        expected = Version(f"{release}.dev{dev_num}")
        assert v == expected
        assert str(v) == str(expected)

    @given(release=release_segment, dev_num=small_ints)
    @SETTINGS
    def test_normal_form_uses_dot_separator(self, release: str, dev_num: int) -> None:
        """The normalized string uses '.' before 'dev'."""
        v = Version(f"{release}-dev{dev_num}")
        assert f".dev{dev_num}" in str(v)


class TestImplicitDevelopmentReleaseNumber:
    """Development releases allow omitting the numeral in which case it is implicitly
    assumed to be ``0``. The normal form for this is to include the ``0``
    explicitly. This allows versions such as ``1.2.dev`` which is normalized to
    ``1.2.dev0``."""

    @given(release=release_segment)
    @SETTINGS
    def test_omitted_numeral_equals_zero(self, release: str) -> None:
        """Omitting the dev number is the same as dev0."""
        assert Version(f"{release}.dev") == Version(f"{release}.dev0")

    @given(release=release_segment)
    @SETTINGS
    def test_normalized_form_includes_zero(self, release: str) -> None:
        """The normalized string explicitly includes 0."""
        v = Version(f"{release}.dev")
        assert str(v).endswith(".dev0")


class TestLocalVersionSegments:
    """With a local version, in addition to the use of ``.`` as a separator of
    segments, the use of ``-`` and ``_`` is also acceptable. The normal form is
    using the ``.`` character. This allows versions such as ``1.0+ubuntu-1`` to be
    normalized to ``1.0+ubuntu.1``."""

    @given(
        release=release_segment,
        local_parts=st.lists(
            st.from_regex(r"[a-zA-Z0-9]+", fullmatch=True),
            min_size=1,
            max_size=4,
        ),
        sep=st.sampled_from([".", "-", "_"]),
    )
    @SETTINGS
    def test_local_separators_normalize_to_dot(
        self, release: str, local_parts: list[str], sep: str
    ) -> None:
        """'-' and '_' in local segments normalize to '.'."""
        local = sep.join(local_parts)
        v = Version(f"{release}+{local}")

        def _normalize_local_part(p: str) -> str:
            # Purely numeric local segments are normalized via int().
            if p.isdigit():
                return str(int(p))
            return p.lower()

        expected_local = ".".join(_normalize_local_part(p) for p in local_parts)
        assert str(v).endswith(f"+{expected_local}")

    @given(
        release=release_segment,
        local_parts=st.lists(
            st.from_regex(r"[a-zA-Z0-9]+", fullmatch=True),
            min_size=2,
            max_size=4,
        ),
    )
    @SETTINGS
    def test_mixed_separators_normalize(
        self, release: str, local_parts: list[str]
    ) -> None:
        """Mixed separators all become dots."""
        seps = ["-", "_", "."]
        # Join with alternating separators
        local = local_parts[0]
        for i, part in enumerate(local_parts[1:]):
            local += seps[i % len(seps)] + part
        v = Version(f"{release}+{local}")

        def _normalize_local_part(p: str) -> str:
            if p.isdigit():
                return str(int(p))
            return p.lower()

        expected_local = ".".join(_normalize_local_part(p) for p in local_parts)
        assert str(v).endswith(f"+{expected_local}")


class TestPrecedingVCharacter:
    """In order to support the common version notation of ``v1.0`` versions may be
    preceded by a single literal ``v`` character. This character MUST be ignored
    for all purposes and should be omitted from all normalized forms of the
    version. The same version with and without the ``v`` is considered equivalent."""

    @given(release=release_segment)
    @SETTINGS
    def test_v_prefix_ignored(self, release: str) -> None:
        """'v' prefix is stripped and versions are equal."""
        assert Version(f"v{release}") == Version(release)

    @given(release=release_segment)
    @SETTINGS
    def test_uppercase_v_prefix_ignored(self, release: str) -> None:
        """'V' prefix is also stripped."""
        assert Version(f"V{release}") == Version(release)

    @given(release=release_segment)
    @SETTINGS
    def test_normalized_form_omits_v(self, release: str) -> None:
        """The normalized string does not start with 'v'."""
        v = Version(f"v{release}")
        assert not str(v).startswith("v")
        assert not str(v).startswith("V")

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_num=small_ints,
    )
    @SETTINGS
    def test_v_prefix_with_pre_release(
        self, release: str, pre_type: str, pre_num: int
    ) -> None:
        """'v' prefix works with pre-release versions."""
        v_str = f"v{release}{pre_type}{pre_num}"
        normal_str = f"{release}{pre_type}{pre_num}"
        assert Version(v_str) == Version(normal_str)
        assert str(Version(v_str)) == str(Version(normal_str))


class TestLeadingAndTrailingWhitespace:
    r"""Leading and trailing whitespace must be silently ignored and removed from all
    normalized forms of a version. This includes ``" "``, ``\t``, ``\n``, ``\r``,
    ``\f``, and ``\v``. This allows accidental whitespace to be handled sensibly,
    such as a version like ``1.0\n`` which normalizes to ``1.0``."""

    @given(
        release=release_segment,
        leading=st.text(
            alphabet=st.sampled_from([" ", "\t", "\n", "\r", "\f", "\v"]),
            min_size=0,
            max_size=3,
        ),
        trailing=st.text(
            alphabet=st.sampled_from([" ", "\t", "\n", "\r", "\f", "\v"]),
            min_size=0,
            max_size=3,
        ),
    )
    @SETTINGS
    def test_whitespace_stripped(
        self, release: str, leading: str, trailing: str
    ) -> None:
        """Leading and trailing whitespace is ignored."""
        v_padded = Version(f"{leading}{release}{trailing}")
        v_clean = Version(release)
        assert v_padded == v_clean
        assert str(v_padded) == str(v_clean)

    @given(release=release_segment)
    @SETTINGS
    def test_tab_whitespace(self, release: str) -> None:
        r"""Tab characters are stripped."""
        assert Version(f"\t{release}\t") == Version(release)

    @given(release=release_segment)
    @SETTINGS
    def test_newline_whitespace(self, release: str) -> None:
        r"""Newline characters are stripped."""
        assert Version(f"\n{release}\n") == Version(release)

    @given(release=release_segment)
    @SETTINGS
    def test_normalized_form_has_no_whitespace(self, release: str) -> None:
        """The normalized string has no leading or trailing whitespace."""
        v = Version(f"  {release}  ")
        s = str(v)
        assert s == s.strip()
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/test_version_ordering.py0000644000000000000000000004105515172742311020342 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 pytest
from hypothesis import given
from hypothesis import strategies as st

from packaging.version import Version
from tests.property.strategies import SETTINGS, pre_tags, release_segment, small_ints

pytestmark = pytest.mark.property

_epoch_ints = st.integers(min_value=0, max_value=5)


class TestEpochOrdering:
    """
    The epoch segment of version identifiers MUST be sorted according to the
    numeric value of the given epoch. If no epoch segment is present, the
    implicit numeric value is ``0``.
    """

    @given(epoch_a=_epoch_ints, epoch_b=_epoch_ints, release=release_segment)
    @SETTINGS
    def test_epoch_sorts_by_numeric_value(
        self, epoch_a: int, epoch_b: int, release: str
    ) -> None:
        """Higher epoch always sorts higher, same release."""
        v1 = Version(f"{epoch_a}!{release}")
        v2 = Version(f"{epoch_b}!{release}")
        if epoch_a < epoch_b:
            assert v1 < v2
        elif epoch_a > epoch_b:
            assert v1 > v2
        else:
            assert v1 == v2

    @given(release=release_segment)
    @SETTINGS
    def test_implicit_epoch_is_zero(self, release: str) -> None:
        """Omitting the epoch is the same as epoch 0."""
        v_no_epoch = Version(release)
        v_explicit_zero = Version(f"0!{release}")
        assert v_no_epoch == v_explicit_zero

    @given(
        epoch=st.integers(min_value=1, max_value=5),
        release_a=release_segment,
        release_b=release_segment,
    )
    @SETTINGS
    def test_higher_epoch_beats_any_release(
        self, epoch: int, release_a: str, release_b: str
    ) -> None:
        """A higher epoch always wins regardless of release segments."""
        v_low = Version(f"0!{release_a}")
        v_high = Version(f"{epoch}!{release_b}")
        assert v_high > v_low


class TestReleaseSegmentOrdering:
    """
    The release segment of version identifiers MUST be sorted in
    the same order as Python's tuple sorting when the normalized release segment is
    parsed as follows::

        tuple(map(int, release_segment.split(".")))
    """

    @given(
        release_a=st.lists(
            st.integers(min_value=0, max_value=50), min_size=1, max_size=4
        ),
        release_b=st.lists(
            st.integers(min_value=0, max_value=50), min_size=1, max_size=4
        ),
    )
    @SETTINGS
    def test_release_sorts_like_tuple(
        self, release_a: list[int], release_b: list[int]
    ) -> None:
        """Release segment ordering matches tuple ordering with zero padding."""
        v1 = Version(".".join(str(x) for x in release_a))
        v2 = Version(".".join(str(x) for x in release_b))
        # Pad to equal length with zeros, like the spec requires.
        maxlen = max(len(release_a), len(release_b))
        t1 = tuple(release_a) + (0,) * (maxlen - len(release_a))
        t2 = tuple(release_b) + (0,) * (maxlen - len(release_b))
        if t1 < t2:
            assert v1 < v2
        elif t1 > t2:
            assert v1 > v2
        else:
            assert v1 == v2


class TestReleaseSegmentZeroPadding:
    """
    All release segments involved in the comparison MUST be converted to a
    consistent length by padding shorter segments with zeros as needed.
    """

    @given(
        base=st.lists(st.integers(min_value=0, max_value=20), min_size=1, max_size=3),
        extra_zeros=st.integers(min_value=1, max_value=3),
    )
    @SETTINGS
    def test_trailing_zeros_are_equal(self, base: list[int], extra_zeros: int) -> None:
        """Appending trailing zeros does not change ordering."""
        short = ".".join(str(x) for x in base)
        long = short + ".0" * extra_zeros
        assert Version(short) == Version(long)


class TestSuffixOrdering:
    """
    Within a numeric release (``1.0``, ``2.7.3``), the following suffixes
    are permitted and MUST be ordered as shown::

       .devN, aN, bN, rcN, , .postN
    """

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_dev_before_alpha(self, release: str, number: int) -> None:
        """.devN < aN for the same release."""
        dev = Version(f"{release}.dev{number}")
        alpha = Version(f"{release}a{number}")
        assert dev < alpha

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_alpha_before_beta(self, release: str, number: int) -> None:
        """aN < bN for the same release."""
        alpha = Version(f"{release}a{number}")
        beta = Version(f"{release}b{number}")
        assert alpha < beta

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_beta_before_rc(self, release: str, number: int) -> None:
        """bN < rcN for the same release."""
        beta = Version(f"{release}b{number}")
        rc = Version(f"{release}rc{number}")
        assert beta < rc

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_rc_before_release(self, release: str, number: int) -> None:
        """rcN <  for the same release."""
        rc = Version(f"{release}rc{number}")
        final = Version(release)
        assert rc < final

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_release_before_post(self, release: str, number: int) -> None:
        """ < .postN for the same release."""
        final = Version(release)
        post = Version(f"{release}.post{number}")
        assert final < post

    @given(release=release_segment, number=small_ints, post_number=small_ints)
    @SETTINGS
    def test_full_suffix_chain(
        self, release: str, number: int, post_number: int
    ) -> None:
        """The full chain: .devN < aN < bN < rcN < (none) < .postN."""
        dev = Version(f"{release}.dev{number}")
        alpha = Version(f"{release}a{number}")
        beta = Version(f"{release}b{number}")
        rc = Version(f"{release}rc{number}")
        final = Version(release)
        post = Version(f"{release}.post{post_number}")
        assert dev < alpha < beta < rc < final < post


class TestCRcEquivalence:
    """
    Note that ``c`` is considered to be semantically equivalent to ``rc`` and must
    be sorted as if it were ``rc``. Tools MAY reject the case of having the same
    ``N`` for both a ``c`` and a ``rc`` in the same release segment as ambiguous
    and remain in compliance with the specification.
    """

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_c_equals_rc(self, release: str, number: int) -> None:
        """cN and rcN for the same release and N are equal."""
        c_ver = Version(f"{release}c{number}")
        rc_ver = Version(f"{release}rc{number}")
        assert c_ver == rc_ver

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_c_and_rc_same_hash(self, release: str, number: int) -> None:
        """cN and rcN hash to the same value."""
        c_ver = Version(f"{release}c{number}")
        rc_ver = Version(f"{release}rc{number}")
        assert hash(c_ver) == hash(rc_ver)

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_c_sorts_after_beta(self, release: str, number: int) -> None:
        """cN sorts the same as rcN, which is after bN."""
        c_ver = Version(f"{release}c{number}")
        beta = Version(f"{release}b{number}")
        assert beta < c_ver


class TestPreReleaseSuffixOrdering:
    """
    Within an alpha (``1.0a1``), beta (``1.0b1``), or release candidate
    (``1.0rc1``, ``1.0c1``), the following suffixes are permitted and MUST be
    ordered as shown::

       .devN, , .postN
    """

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_n=small_ints,
        number=small_ints,
    )
    @SETTINGS
    def test_dev_before_plain_pre(
        self, release: str, pre_type: str, pre_n: int, number: int
    ) -> None:
        """.devN <  within a pre-release."""
        dev = Version(f"{release}{pre_type}{pre_n}.dev{number}")
        plain = Version(f"{release}{pre_type}{pre_n}")
        assert dev < plain

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_n=small_ints,
        number=small_ints,
    )
    @SETTINGS
    def test_plain_pre_before_post(
        self, release: str, pre_type: str, pre_n: int, number: int
    ) -> None:
        """ < .postN within a pre-release."""
        plain = Version(f"{release}{pre_type}{pre_n}")
        post = Version(f"{release}{pre_type}{pre_n}.post{number}")
        assert plain < post

    @given(
        release=release_segment,
        pre_type=pre_tags,
        pre_n=small_ints,
        dev_n=small_ints,
        post_n=small_ints,
    )
    @SETTINGS
    def test_full_pre_suffix_chain(
        self, release: str, pre_type: str, pre_n: int, dev_n: int, post_n: int
    ) -> None:
        """.devN <  < .postN within a pre-release."""
        dev = Version(f"{release}{pre_type}{pre_n}.dev{dev_n}")
        plain = Version(f"{release}{pre_type}{pre_n}")
        post = Version(f"{release}{pre_type}{pre_n}.post{post_n}")
        assert dev < plain < post


class TestPostReleaseSuffixOrdering:
    """
    Within a post-release (``1.0.post1``), the following suffixes are permitted
    and MUST be ordered as shown::

        .devN, 
    """

    @given(release=release_segment, post_n=small_ints, dev_n=small_ints)
    @SETTINGS
    def test_dev_before_plain_post(self, release: str, post_n: int, dev_n: int) -> None:
        """.devN <  within a post-release."""
        dev = Version(f"{release}.post{post_n}.dev{dev_n}")
        plain = Version(f"{release}.post{post_n}")
        assert dev < plain


class TestDotSeparation:
    """
    Note that ``devN`` and ``postN`` MUST always be preceded by a dot, even
    when used immediately following a numeric version (e.g. ``1.0.dev456``,
    ``1.0.post1``).
    """

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_dev_with_dot_parses(self, release: str, number: int) -> None:
        """Dot-prefixed .devN is valid and parseable."""
        v = Version(f"{release}.dev{number}")
        assert v.dev == number

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_post_with_dot_parses(self, release: str, number: int) -> None:
        """Dot-prefixed .postN is valid and parseable."""
        v = Version(f"{release}.post{number}")
        assert v.post == number

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_dev_normalized_form_has_dot(self, release: str, number: int) -> None:
        """The normalized string form of a dev release uses a dot."""
        v = Version(f"{release}.dev{number}")
        assert f".dev{number}" in str(v)

    @given(release=release_segment, number=small_ints)
    @SETTINGS
    def test_post_normalized_form_has_dot(self, release: str, number: int) -> None:
        """The normalized string form of a post release uses a dot."""
        v = Version(f"{release}.post{number}")
        assert f".post{number}" in str(v)


class TestNumericOrderingWithinSharedPrefix:
    """
    Within a pre-release, post-release or development release segment with a
    shared prefix, ordering MUST be by the value of the numeric component.
    """

    @given(
        release=release_segment,
        number_a=small_ints,
        number_b=small_ints,
    )
    @SETTINGS
    def test_dev_numeric_ordering(
        self, release: str, number_a: int, number_b: int
    ) -> None:
        """dev releases order by numeric component."""
        v1 = Version(f"{release}.dev{number_a}")
        v2 = Version(f"{release}.dev{number_b}")
        if number_a < number_b:
            assert v1 < v2
        elif number_a > number_b:
            assert v1 > v2
        else:
            assert v1 == v2

    @given(
        release=release_segment,
        pre_type=pre_tags,
        number_a=small_ints,
        number_b=small_ints,
    )
    @SETTINGS
    def test_pre_release_numeric_ordering(
        self, release: str, pre_type: str, number_a: int, number_b: int
    ) -> None:
        """Pre-releases of the same type order by numeric component."""
        v1 = Version(f"{release}{pre_type}{number_a}")
        v2 = Version(f"{release}{pre_type}{number_b}")
        if number_a < number_b:
            assert v1 < v2
        elif number_a > number_b:
            assert v1 > v2
        else:
            assert v1 == v2

    @given(
        release=release_segment,
        number_a=small_ints,
        number_b=small_ints,
    )
    @SETTINGS
    def test_post_release_numeric_ordering(
        self, release: str, number_a: int, number_b: int
    ) -> None:
        """Post-releases order by numeric component."""
        v1 = Version(f"{release}.post{number_a}")
        v2 = Version(f"{release}.post{number_b}")
        if number_a < number_b:
            assert v1 < v2
        elif number_a > number_b:
            assert v1 > v2
        else:
            assert v1 == v2


class TestComprehensiveOrderingExample:
    """
    The following example covers many of the possible combinations::

        1.dev0
        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.0rc1.dev456
        1.0rc1
        1.0
        1.0+abc.5
        1.0+abc.7
        1.0+5
        1.0.post456.dev34
        1.0.post456
        1.0.15
        1.1.dev1
    """

    # The spec example as an ordered list of version strings. Each version
    # in this list MUST sort strictly less than the one that follows it,
    # with the exception of local versions which compare equal to the
    # non-local version they are based on.
    ORDERED_VERSIONS = (
        "1.dev0",
        "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.0rc1.dev456",
        "1.0rc1",
        "1.0",
        "1.0+abc.5",
        "1.0+abc.7",
        "1.0+5",
        "1.0.post456.dev34",
        "1.0.post456",
        "1.0.15",
        "1.1.dev1",
    )

    # Indices where local versions appear (they compare equal to 1.0 for
    # ordering purposes, so they are not strictly greater than 1.0).
    LOCAL_INDICES = frozenset({13, 14, 15})

    def test_pairwise_ordering(self) -> None:
        """Each version in the spec example sorts before the next.

        Local versions are excluded from strict less-than checks because
        they compare equal to their public version for ordering.
        """
        versions = [Version(s) for s in self.ORDERED_VERSIONS]
        for i in range(len(versions) - 1):
            a, b = versions[i], versions[i + 1]
            # Skip pairs that involve local versions (indices 12-15 are
            # 1.0, 1.0+abc.5, 1.0+abc.7, 1.0+5) since locals compare
            # equal to their public counterpart.
            va = self.ORDERED_VERSIONS[i]
            vb = self.ORDERED_VERSIONS[i + 1]
            if i + 1 in self.LOCAL_INDICES or i in self.LOCAL_INDICES:
                assert a <= b, f"{va} should be <= {vb}"
            else:
                assert a < b, f"{va} should be < {vb}"

    def test_sorted_matches_spec_order(self) -> None:
        """Sorting the spec example versions produces the spec order.

        Local versions are removed since they do not participate in
        public ordering and sorted() cannot guarantee their relative
        positions among equal elements (it is stable, but they parse
        as equal to 1.0).
        """
        public_strings = [
            s
            for i, s in enumerate(self.ORDERED_VERSIONS)
            if i not in self.LOCAL_INDICES
        ]
        versions = [Version(s) for s in public_strings]
        assert sorted(versions) == versions

    def test_all_pairs_consistent(self) -> None:
        """For every pair (i, j) where i < j, version[i] <= version[j].

        Uses <= to accommodate local version equality.
        """
        versions = [Version(s) for s in self.ORDERED_VERSIONS]
        for i, j in itertools.combinations(range(len(versions)), 2):
            # Skip comparisons across the local version cluster since
            # those are equal to 1.0 in public ordering.
            if i in self.LOCAL_INDICES or j in self.LOCAL_INDICES:
                continue
            assert versions[i] < versions[j], (
                f"{self.ORDERED_VERSIONS[i]} should be < {self.ORDERED_VERSIONS[j]}"
            )
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1095212
packaging-26.2/tests/property/test_version_releases.py0000644000000000000000000010456315172742311020340 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 hypothesis import assume, given
from hypothesis import strategies as st

from packaging.specifiers import Specifier, SpecifierSet
from packaging.version import Version
from tests.property.strategies import (
    SETTINGS,
    pep440_versions,
    pre_tags,
    release_segment,
    small_ints,
)

pytestmark = pytest.mark.property


@st.composite
def final_versions(draw: st.DrawFn) -> Version:
    """Generate a final release version (release segment only, epoch optional)."""
    rel = draw(release_segment)
    epoch = draw(st.integers(min_value=0, max_value=3))
    if epoch > 0:
        return Version(f"{epoch}!{rel}")
    return Version(rel)


@st.composite
def pre_release_versions(draw: st.DrawFn) -> Version:
    """Generate a pre-release version (X.Y{a,b,rc}N)."""
    rel = draw(release_segment)
    phase = draw(pre_tags)
    num = draw(small_ints)
    return Version(f"{rel}{phase}{num}")


@st.composite
def post_release_versions(draw: st.DrawFn) -> Version:
    """Generate a post-release version (X.Y.postN)."""
    rel = draw(release_segment)
    post_num = draw(small_ints)
    return Version(f"{rel}.post{post_num}")


@st.composite
def dev_release_versions(draw: st.DrawFn) -> Version:
    """Generate a developmental release version (X.Y.devN)."""
    rel = draw(release_segment)
    dev_num = draw(small_ints)
    return Version(f"{rel}.dev{dev_num}")


# Pools of concrete versions for sampled_from strategies.
FINAL_POOL = [
    Version(s)
    for s in [
        "0.9",
        "0.9.1",
        "0.9.2",
        "0.9.10",
        "0.9.11",
        "1.0",
        "1.0.1",
        "1.1",
        "2.0",
        "2.0.1",
        "3.3.1",
        "3.3.5",
        "3.3.9.45",
        "2012.4",
        "2012.7",
        "2012.10",
        "2013.1",
        "2013.6",
    ]
]

PRE_POOL = [
    Version(s)
    for s in [
        "1.0a1",
        "1.0a2",
        "1.0b1",
        "1.0b2",
        "1.0rc1",
        "1.0rc2",
        "2.0a1",
        "2.0b1",
        "2.0rc1",
    ]
]

POST_POOL = [
    Version(s)
    for s in [
        "1.0.post0",
        "1.0.post1",
        "1.0.post2",
        "2.0.post1",
        "1.0a1.post1",
        "1.0b1.post1",
        "1.0rc1.post1",
    ]
]

DEV_POOL = [
    Version(s)
    for s in [
        "1.0.dev0",
        "1.0.dev1",
        "1.0.dev5",
        "2.0.dev0",
        "1.0a1.dev1",
        "1.0b1.dev1",
        "1.0rc1.dev1",
        "1.0.post1.dev1",
    ]
]

EPOCH_POOL = [
    Version(s)
    for s in [
        "1.0",
        "1.1",
        "2.0",
        "2013.10",
        "2014.04",
        "1!1.0",
        "1!1.1",
        "1!2.0",
        "2!1.0",
    ]
]


class TestFinalReleaseDefinition:
    """A version identifier that consists solely of a release segment and optionally
    an epoch identifier is termed a "final release"."""

    @given(version=final_versions())
    @SETTINGS
    def test_final_release_has_no_pre_post_dev(self, version: Version) -> None:
        """A final release has no pre, post, or dev segments."""
        assert version.pre is None
        assert version.post is None
        assert version.dev is None

    @given(version=final_versions())
    @SETTINGS
    def test_final_release_is_not_prerelease(self, version: Version) -> None:
        """A final release is not flagged as a pre-release."""
        assert not version.is_prerelease

    @given(version=final_versions())
    @SETTINGS
    def test_final_release_is_not_postrelease(self, version: Version) -> None:
        """A final release is not flagged as a post-release."""
        assert not version.is_postrelease

    @given(version=final_versions())
    @SETTINGS
    def test_final_release_is_not_devrelease(self, version: Version) -> None:
        """A final release is not flagged as a dev release."""
        assert not version.is_devrelease


class TestReleaseSegmentFormat:
    """The release segment consists of one or more non-negative integer
    values, separated by dots::

        N(.N)*"""

    @given(version=pep440_versions())
    @SETTINGS
    def test_release_tuple_is_non_negative(self, version: Version) -> None:
        """Each component of the release tuple is a non-negative integer."""
        for component in version.release:
            assert isinstance(component, int)
            assert component >= 0

    @given(version=pep440_versions())
    @SETTINGS
    def test_release_has_at_least_one_component(self, version: Version) -> None:
        """The release segment has at least one component."""
        assert len(version.release) >= 1


class TestReleaseSegmentComparison:
    """Comparison and ordering of release segments considers the numeric value
    of each component of the release segment in turn. When comparing release
    segments with different numbers of components, the shorter segment is
    padded out with additional zeros as necessary."""

    @given(
        major=small_ints,
        minor=small_ints,
    )
    @SETTINGS
    def test_zero_padding_two_vs_three(self, major: int, minor: int) -> None:
        """X.Y compares equal to X.Y.0 due to zero-padding."""
        v2 = Version(f"{major}.{minor}")
        v3 = Version(f"{major}.{minor}.0")
        assert v2 == v3

    @given(
        major=small_ints,
        minor=small_ints,
    )
    @SETTINGS
    def test_zero_padding_extended(self, major: int, minor: int) -> None:
        """X.Y compares equal to X.Y.0.0.0 due to zero-padding."""
        v2 = Version(f"{major}.{minor}")
        v5 = Version(f"{major}.{minor}.0.0.0")
        assert v2 == v5

    @given(
        version_a=st.sampled_from(FINAL_POOL),
        version_b=st.sampled_from(FINAL_POOL),
    )
    @SETTINGS
    def test_component_wise_ordering(
        self, version_a: Version, version_b: Version
    ) -> None:
        """Ordering is determined by comparing components left to right."""
        # Pad both release tuples to the same length for comparison.
        len_max = max(len(version_a.release), len(version_b.release))
        a_padded = version_a.release + (0,) * (len_max - len(version_a.release))
        b_padded = version_b.release + (0,) * (len_max - len(version_b.release))
        assert (version_a < version_b) == (a_padded < b_padded)
        assert (version_a == version_b) == (a_padded == b_padded)

    @given(
        components=st.lists(small_ints, min_size=1, max_size=5),
        extra_zeros=st.integers(min_value=1, max_value=4),
    )
    @SETTINGS
    def test_trailing_zeros_are_ignored(
        self, components: list[int], extra_zeros: int
    ) -> None:
        """Trailing zeros do not change the version identity."""
        base = ".".join(str(c) for c in components)
        extended = base + ".0" * extra_zeros
        assert Version(base) == Version(extended)


class TestFinalReleaseExampleOrdering:
    r"""For example::

    0.9
    0.9.1
    0.9.2
    ...
    0.9.10
    0.9.11
    1.0
    1.0.1
    1.1
    2.0
    2.0.1
    ..."""

    @SETTINGS
    @given(data=st.data())
    def test_example_sequence_is_sorted(self, data: st.DataObject) -> None:
        """Any two versions from the example list are ordered correctly."""
        versions = [
            Version("0.9"),
            Version("0.9.1"),
            Version("0.9.2"),
            Version("0.9.10"),
            Version("0.9.11"),
            Version("1.0"),
            Version("1.0.1"),
            Version("1.1"),
            Version("2.0"),
            Version("2.0.1"),
        ]
        i = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        j = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        if i < j:
            assert versions[i] < versions[j]
        elif i == j:
            assert versions[i] == versions[j]
        else:
            assert versions[i] > versions[j]


class TestXYEqualsXY0:
    """.. note::

    ``X.Y`` and ``X.Y.0`` are not considered distinct release numbers, as
    the release segment comparison rules implicitly expand the two component
    form to ``X.Y.0`` when comparing it to any release segment that includes
    three components."""

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_xy_equals_xy0(self, major: int, minor: int) -> None:
        """X.Y == X.Y.0."""
        assert Version(f"{major}.{minor}") == Version(f"{major}.{minor}.0")

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_xy_hash_equals_xy0_hash(self, major: int, minor: int) -> None:
        """hash(X.Y) == hash(X.Y.0) since they are equal."""
        assert hash(Version(f"{major}.{minor}")) == hash(Version(f"{major}.{minor}.0"))

    @given(major=small_ints, minor=small_ints, micro=small_ints)
    @SETTINGS
    def test_specifier_match_equivalent(
        self, major: int, minor: int, micro: int
    ) -> None:
        """X.Y and X.Y.0 match the same specifiers involving
        three-component versions."""
        v2 = Version(f"{major}.{minor}")
        v3 = Version(f"{major}.{minor}.0")
        spec = SpecifierSet(f">={major}.{minor}.{micro}")
        assert (v2 in spec) == (v3 in spec)


class TestDateBasedReleases:
    """Date-based release segments are also permitted. An example of a date-based
    release scheme using the year and month of the release::

        2012.4
        2012.7
        2012.10
        2013.1
        2013.6
        ..."""

    @SETTINGS
    @given(data=st.data())
    def test_date_based_example_ordering(self, data: st.DataObject) -> None:
        """The example date-based versions are in strictly increasing order."""
        versions = [
            Version("2012.4"),
            Version("2012.7"),
            Version("2012.10"),
            Version("2013.1"),
            Version("2013.6"),
        ]
        i = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        j = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        if i < j:
            assert versions[i] < versions[j]
        elif i == j:
            assert versions[i] == versions[j]
        else:
            assert versions[i] > versions[j]

    @given(
        year=st.integers(min_value=2000, max_value=2030),
        month=st.integers(min_value=1, max_value=12),
    )
    @SETTINGS
    def test_date_based_versions_are_valid(self, year: int, month: int) -> None:
        """Date-based versions parse as valid PEP 440 versions."""
        v = Version(f"{year}.{month}")
        assert v.release == (year, month)
        assert v.epoch == 0


class TestPreReleaseIndicators:
    r"""If used as part of a project's development cycle, these pre-releases are
    indicated by including a pre-release segment in the version identifier::

        X.YaN   # Alpha release
        X.YbN   # Beta release
        X.YrcN  # Release Candidate
        X.Y     # Final release"""

    @given(version=pre_release_versions())
    @SETTINGS
    def test_pre_release_has_pre_segment(self, version: Version) -> None:
        """A pre-release version has a non-None pre attribute."""
        assert version.pre is not None

    @given(version=pre_release_versions())
    @SETTINGS
    def test_pre_release_phase_is_valid(self, version: Version) -> None:
        """The pre-release phase is one of a, b, or rc."""
        assert version.pre is not None
        phase, _ = version.pre
        assert phase in ("a", "b", "rc")

    @given(
        major=small_ints,
        minor=small_ints,
        phase=pre_tags,
        num=small_ints,
    )
    @SETTINGS
    def test_pre_release_before_final(
        self, major: int, minor: int, phase: str, num: int
    ) -> None:
        """Any pre-release X.Y{a,b,rc}N sorts before the final release X.Y."""
        pre = Version(f"{major}.{minor}{phase}{num}")
        final = Version(f"{major}.{minor}")
        assert pre < final


class TestPreReleaseDefinition:
    """A version identifier that consists solely of a release segment and a
    pre-release segment is termed a "pre-release"."""

    @given(version=pre_release_versions())
    @SETTINGS
    def test_pre_release_is_prerelease(self, version: Version) -> None:
        """A pre-release version has is_prerelease == True."""
        assert version.is_prerelease

    @given(version=pre_release_versions())
    @SETTINGS
    def test_pre_release_is_not_postrelease(self, version: Version) -> None:
        """A bare pre-release is not a post-release."""
        assert not version.is_postrelease

    @given(version=pre_release_versions())
    @SETTINGS
    def test_pre_release_is_not_devrelease(self, version: Version) -> None:
        """A bare pre-release is not a dev release."""
        assert not version.is_devrelease


class TestPreReleasePhaseOrdering:
    """The pre-release segment consists of an alphabetical identifier for the
    pre-release phase, along with a non-negative integer value. Pre-releases for
    a given release are ordered first by phase (alpha, beta, release candidate)
    and then by the numerical component within that phase."""

    @given(
        major=small_ints,
        minor=small_ints,
        num=small_ints,
    )
    @SETTINGS
    def test_alpha_before_beta(self, major: int, minor: int, num: int) -> None:
        """Alpha comes before beta for the same release and number."""
        alpha = Version(f"{major}.{minor}a{num}")
        beta = Version(f"{major}.{minor}b{num}")
        assert alpha < beta

    @given(
        major=small_ints,
        minor=small_ints,
        num=small_ints,
    )
    @SETTINGS
    def test_beta_before_rc(self, major: int, minor: int, num: int) -> None:
        """Beta comes before release candidate for the same release and number."""
        beta = Version(f"{major}.{minor}b{num}")
        rc = Version(f"{major}.{minor}rc{num}")
        assert beta < rc

    @given(
        major=small_ints,
        minor=small_ints,
        num=small_ints,
    )
    @SETTINGS
    def test_alpha_before_rc(self, major: int, minor: int, num: int) -> None:
        """Alpha comes before release candidate for the same release and number."""
        alpha = Version(f"{major}.{minor}a{num}")
        rc = Version(f"{major}.{minor}rc{num}")
        assert alpha < rc

    @given(
        major=small_ints,
        minor=small_ints,
        phase=pre_tags,
        number_a=small_ints,
        number_b=small_ints,
    )
    @SETTINGS
    def test_numerical_ordering_within_phase(
        self, major: int, minor: int, phase: str, number_a: int, number_b: int
    ) -> None:
        """Within the same phase, ordering is by the numerical component."""
        assume(number_a != number_b)
        v1 = Version(f"{major}.{minor}{phase}{number_a}")
        v2 = Version(f"{major}.{minor}{phase}{number_b}")
        assert (v1 < v2) == (number_a < number_b)


class TestCEquivalentToRc:
    """Installation tools MAY accept both ``c`` and ``rc`` releases for a common
    release segment in order to handle some existing legacy distributions."""

    @given(
        major=small_ints,
        minor=small_ints,
        num=small_ints,
    )
    @SETTINGS
    def test_c_parses_as_rc(self, major: int, minor: int, num: int) -> None:
        """A 'c' pre-release is accepted and parsed as 'rc'."""
        v = Version(f"{major}.{minor}c{num}")
        assert v.pre is not None
        assert v.pre[0] == "rc"


class TestCVersionEquivalence:
    """Installation tools SHOULD interpret ``c`` versions as being equivalent to
    ``rc`` versions (that is, ``c1`` indicates the same version as ``rc1``)."""

    @given(
        major=small_ints,
        minor=small_ints,
        num=small_ints,
    )
    @SETTINGS
    def test_c_equals_rc(self, major: int, minor: int, num: int) -> None:
        """Version('X.YcN') == Version('X.YrcN')."""
        c_ver = Version(f"{major}.{minor}c{num}")
        rc_ver = Version(f"{major}.{minor}rc{num}")
        assert c_ver == rc_ver

    @given(
        major=small_ints,
        minor=small_ints,
        num=small_ints,
    )
    @SETTINGS
    def test_c_hash_equals_rc_hash(self, major: int, minor: int, num: int) -> None:
        """hash(Version('X.YcN')) == hash(Version('X.YrcN'))."""
        c_ver = Version(f"{major}.{minor}c{num}")
        rc_ver = Version(f"{major}.{minor}rc{num}")
        assert hash(c_ver) == hash(rc_ver)


class TestPostReleaseIndicator:
    """If used as part of a project's development cycle, these post-releases are
    indicated by including a post-release segment in the version identifier::

        X.Y.postN    # Post-release"""

    @given(version=post_release_versions())
    @SETTINGS
    def test_post_release_has_post_segment(self, version: Version) -> None:
        """A post-release version has a non-None post attribute."""
        assert version.post is not None

    @given(
        major=small_ints,
        minor=small_ints,
        post_num=small_ints,
    )
    @SETTINGS
    def test_post_release_string_contains_post(
        self, major: int, minor: int, post_num: int
    ) -> None:
        """The string representation contains '.postN'."""
        v = Version(f"{major}.{minor}.post{post_num}")
        assert f".post{post_num}" in str(v)


class TestPostReleaseDefinition:
    """A version identifier that includes a post-release segment without a
    developmental release segment is termed a "post-release"."""

    @given(version=post_release_versions())
    @SETTINGS
    def test_post_release_is_postrelease(self, version: Version) -> None:
        """A post-release has is_postrelease == True."""
        assert version.is_postrelease

    @given(version=post_release_versions())
    @SETTINGS
    def test_post_release_is_not_devrelease(self, version: Version) -> None:
        """A bare post-release is not a dev release."""
        assert not version.is_devrelease


class TestPostReleaseOrdering:
    """The post-release segment consists of the string ``.post``, followed by a
    non-negative integer value. Post-releases are ordered by their
    numerical component, immediately following the corresponding release,
    and ahead of any subsequent release."""

    @given(
        major=small_ints,
        minor=small_ints,
        number_a=small_ints,
        number_b=small_ints,
    )
    @SETTINGS
    def test_post_numerical_ordering(
        self, major: int, minor: int, number_a: int, number_b: int
    ) -> None:
        """Post-releases are ordered by their numerical component."""
        assume(number_a != number_b)
        v1 = Version(f"{major}.{minor}.post{number_a}")
        v2 = Version(f"{major}.{minor}.post{number_b}")
        assert (v1 < v2) == (number_a < number_b)

    @given(
        major=small_ints,
        minor=small_ints,
        post_num=st.integers(min_value=0, max_value=20),
    )
    @SETTINGS
    def test_post_release_after_final(
        self, major: int, minor: int, post_num: int
    ) -> None:
        """A post-release immediately follows its corresponding final release."""
        final = Version(f"{major}.{minor}")
        post = Version(f"{major}.{minor}.post{post_num}")
        assert post > final

    @given(
        major=small_ints,
        minor=small_ints,
        post_num=small_ints,
        next_micro=st.integers(min_value=1, max_value=20),
    )
    @SETTINGS
    def test_post_release_before_subsequent_release(
        self, major: int, minor: int, post_num: int, next_micro: int
    ) -> None:
        """A post-release comes before any subsequent release."""
        post = Version(f"{major}.{minor}.post{post_num}")
        subsequent = Version(f"{major}.{minor}.{next_micro}")
        assert post < subsequent


class TestPostReleasesOfPreReleases:
    r"""Post-releases are also permitted for pre-releases::

    X.YaN.postM   # Post-release of an alpha release
    X.YbN.postM   # Post-release of a beta release
    X.YrcN.postM  # Post-release of a release candidate"""

    @given(
        major=small_ints,
        minor=small_ints,
        phase=pre_tags,
        pre_num=small_ints,
        post_num=small_ints,
    )
    @SETTINGS
    def test_post_of_pre_is_valid(
        self, major: int, minor: int, phase: str, pre_num: int, post_num: int
    ) -> None:
        """Post-releases of pre-releases parse successfully."""
        v = Version(f"{major}.{minor}{phase}{pre_num}.post{post_num}")
        assert v.pre is not None
        assert v.pre[0] == phase
        assert v.pre[1] == pre_num
        assert v.post == post_num

    @given(
        major=small_ints,
        minor=small_ints,
        phase=pre_tags,
        pre_num=small_ints,
        post_num=small_ints,
    )
    @SETTINGS
    def test_post_of_pre_after_pre(
        self, major: int, minor: int, phase: str, pre_num: int, post_num: int
    ) -> None:
        """A post-release of a pre-release sorts after the pre-release itself."""
        pre = Version(f"{major}.{minor}{phase}{pre_num}")
        post_of_pre = Version(f"{major}.{minor}{phase}{pre_num}.post{post_num}")
        assert post_of_pre > pre

    @given(
        major=small_ints,
        minor=small_ints,
        phase=pre_tags,
        pre_num=small_ints,
        post_num=small_ints,
    )
    @SETTINGS
    def test_post_of_pre_is_postrelease(
        self, major: int, minor: int, phase: str, pre_num: int, post_num: int
    ) -> None:
        """A post-release of a pre-release is flagged as both pre and post."""
        v = Version(f"{major}.{minor}{phase}{pre_num}.post{post_num}")
        assert v.is_prerelease
        assert v.is_postrelease


class TestDevReleaseIndicator:
    """If used as part of a project's development cycle, these developmental
    releases are indicated by including a developmental release segment in the
    version identifier::

        X.Y.devN    # Developmental release"""

    @given(version=dev_release_versions())
    @SETTINGS
    def test_dev_release_has_dev_segment(self, version: Version) -> None:
        """A developmental release has a non-None dev attribute."""
        assert version.dev is not None

    @given(
        major=small_ints,
        minor=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_release_string_contains_dev(
        self, major: int, minor: int, dev_num: int
    ) -> None:
        """The string representation contains '.devN'."""
        v = Version(f"{major}.{minor}.dev{dev_num}")
        assert f".dev{dev_num}" in str(v)


class TestDevReleaseDefinition:
    """A version identifier that includes a developmental release segment is
    termed a "developmental release"."""

    @given(version=dev_release_versions())
    @SETTINGS
    def test_dev_release_is_devrelease(self, version: Version) -> None:
        """A developmental release has is_devrelease == True."""
        assert version.is_devrelease


class TestDevReleaseOrdering:
    """The developmental release segment consists of the string ``.dev``,
    followed by a non-negative integer value. Developmental releases are ordered
    by their numerical component, immediately before the corresponding release
    (and before any pre-releases with the same release segment), and following
    any previous release (including any post-releases)."""

    @given(
        major=small_ints,
        minor=small_ints,
        number_a=small_ints,
        number_b=small_ints,
    )
    @SETTINGS
    def test_dev_numerical_ordering(
        self, major: int, minor: int, number_a: int, number_b: int
    ) -> None:
        """Dev releases are ordered by their numerical component."""
        assume(number_a != number_b)
        v1 = Version(f"{major}.{minor}.dev{number_a}")
        v2 = Version(f"{major}.{minor}.dev{number_b}")
        assert (v1 < v2) == (number_a < number_b)

    @given(
        major=small_ints,
        minor=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_before_corresponding_release(
        self, major: int, minor: int, dev_num: int
    ) -> None:
        """A dev release sorts before its corresponding final release."""
        dev = Version(f"{major}.{minor}.dev{dev_num}")
        final = Version(f"{major}.{minor}")
        assert dev < final

    @given(
        major=small_ints,
        minor=small_ints,
        dev_num=small_ints,
        phase=pre_tags,
        pre_num=small_ints,
    )
    @SETTINGS
    def test_dev_before_pre_releases(
        self, major: int, minor: int, dev_num: int, phase: str, pre_num: int
    ) -> None:
        """A dev release sorts before any pre-release with the same release segment."""
        dev = Version(f"{major}.{minor}.dev{dev_num}")
        pre = Version(f"{major}.{minor}{phase}{pre_num}")
        assert dev < pre

    @given(
        major=small_ints,
        minor=small_ints,
        dev_num=small_ints,
        prev_micro=st.integers(min_value=0, max_value=20),
        prev_post=small_ints,
    )
    @SETTINGS
    def test_dev_after_previous_post_release(
        self, major: int, minor: int, dev_num: int, prev_micro: int, prev_post: int
    ) -> None:
        """A dev release follows any previous release including post-releases.

        For X.Y.Z.devN, the previous release segment is X.Y.(Z-1). We test
        that X.Y.1.devN > X.Y.0.postM.
        """
        # Use a concrete case: X.Y.1.devN should be after X.Y.0.postM
        prev = Version(f"{major}.{minor}.{prev_micro}.post{prev_post}")
        dev = Version(f"{major}.{minor}.{prev_micro + 1}.dev{dev_num}")
        assert dev > prev


class TestDevReleasesOfPreAndPost:
    r"""Developmental releases are also permitted for pre-releases and
    post-releases::

        X.YaN.devM       # Developmental release of an alpha release
        X.YbN.devM       # Developmental release of a beta release
        X.YrcN.devM      # Developmental release of a release candidate
        X.Y.postN.devM   # Developmental release of a post-release"""

    @given(
        major=small_ints,
        minor=small_ints,
        phase=pre_tags,
        pre_num=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_of_pre_is_valid(
        self, major: int, minor: int, phase: str, pre_num: int, dev_num: int
    ) -> None:
        """Dev releases of pre-releases parse successfully."""
        v = Version(f"{major}.{minor}{phase}{pre_num}.dev{dev_num}")
        assert v.pre is not None
        assert v.pre[0] == phase
        assert v.pre[1] == pre_num
        assert v.dev == dev_num

    @given(
        major=small_ints,
        minor=small_ints,
        post_num=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_of_post_is_valid(
        self, major: int, minor: int, post_num: int, dev_num: int
    ) -> None:
        """Dev releases of post-releases parse successfully."""
        v = Version(f"{major}.{minor}.post{post_num}.dev{dev_num}")
        assert v.post == post_num
        assert v.dev == dev_num

    @given(
        major=small_ints,
        minor=small_ints,
        phase=pre_tags,
        pre_num=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_of_pre_before_pre(
        self, major: int, minor: int, phase: str, pre_num: int, dev_num: int
    ) -> None:
        """A dev release of a pre-release sorts before the pre-release itself."""
        dev_of_pre = Version(f"{major}.{minor}{phase}{pre_num}.dev{dev_num}")
        pre = Version(f"{major}.{minor}{phase}{pre_num}")
        assert dev_of_pre < pre

    @given(
        major=small_ints,
        minor=small_ints,
        post_num=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_of_post_before_post(
        self, major: int, minor: int, post_num: int, dev_num: int
    ) -> None:
        """A dev release of a post-release sorts before the post-release itself."""
        dev_of_post = Version(f"{major}.{minor}.post{post_num}.dev{dev_num}")
        post = Version(f"{major}.{minor}.post{post_num}")
        assert dev_of_post < post


class TestDevReleasesArePreReleases:
    """Do note that development releases are considered a type of pre-release when
    handling them."""

    @given(version=dev_release_versions())
    @SETTINGS
    def test_dev_is_prerelease(self, version: Version) -> None:
        """A dev release has is_prerelease == True."""
        assert version.is_prerelease

    @given(
        major=small_ints,
        minor=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_excluded_by_default_from_specifier(
        self, major: int, minor: int, dev_num: int
    ) -> None:
        """Dev releases are excluded from specifier matching by default
        (since they are pre-releases)."""
        dev = Version(f"{major}.{minor}.dev{dev_num}")
        spec = SpecifierSet(f">={major}.{minor}.dev0")
        # When prereleases=False (the default behavior for non-pre specifiers),
        # dev releases should be excluded. But a specifier that itself references
        # a pre-release enables pre-release matching.
        assert dev in spec

    @given(
        major=small_ints,
        minor=small_ints,
        dev_num=small_ints,
    )
    @SETTINGS
    def test_dev_excluded_by_non_pre_specifier(
        self, major: int, minor: int, dev_num: int
    ) -> None:
        """Dev releases are excluded from a non-pre-release specifier by default."""
        dev = Version(f"{major}.{minor}.dev{dev_num}")
        # Use a specifier that does not reference pre-releases.
        spec = Specifier(f">={major}.{minor}")
        # With prereleases not explicitly set, dev releases should be excluded.
        assert not spec.contains(dev)


class TestEpochFormat:
    """If included in a version identifier, the epoch appears before all other
    components, separated from the release segment by an exclamation mark::

        E!X.Y  # Version identifier with epoch"""

    @given(
        epoch=st.integers(min_value=1, max_value=10),
        major=small_ints,
        minor=small_ints,
    )
    @SETTINGS
    def test_epoch_parsed_correctly(self, epoch: int, major: int, minor: int) -> None:
        """The epoch is parsed from E!X.Y format."""
        v = Version(f"{epoch}!{major}.{minor}")
        assert v.epoch == epoch
        assert v.release == (major, minor)

    @given(
        epoch=st.integers(min_value=1, max_value=10),
        major=small_ints,
        minor=small_ints,
    )
    @SETTINGS
    def test_epoch_in_string_representation(
        self, epoch: int, major: int, minor: int
    ) -> None:
        """The string representation includes the epoch when non-zero."""
        v = Version(f"{epoch}!{major}.{minor}")
        assert str(v).startswith(f"{epoch}!")


class TestImplicitEpochZero:
    """If no explicit epoch is given, the implicit epoch is ``0``."""

    @given(version=pep440_versions())
    @SETTINGS
    def test_no_epoch_means_zero(self, version: Version) -> None:
        """Versions without an explicit epoch have epoch == 0."""
        assume("!" not in str(version))
        assert version.epoch == 0

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_explicit_zero_epoch_equals_implicit(self, major: int, minor: int) -> None:
        """0!X.Y is equivalent to X.Y."""
        explicit = Version(f"0!{major}.{minor}")
        implicit = Version(f"{major}.{minor}")
        assert explicit == implicit

    @given(major=small_ints, minor=small_ints)
    @SETTINGS
    def test_explicit_zero_epoch_hash(self, major: int, minor: int) -> None:
        """hash(0!X.Y) == hash(X.Y)."""
        explicit = Version(f"0!{major}.{minor}")
        implicit = Version(f"{major}.{minor}")
        assert hash(explicit) == hash(implicit)


class TestEpochMotivation:
    """Most version identifiers will not include an epoch, as an explicit epoch is
    only needed if a project *changes* the way it handles version numbering in
    a way that means the normal version ordering rules will give the wrong
    answer. For example, if a project is using date based versions like
    ``2014.04`` and would like to switch to semantic versions like ``1.0``, then
    the new releases would be identified as *older* than the date based releases
    when using the normal sorting scheme::

        1.0
        1.1
        2.0
        2013.10
        2014.04"""

    @SETTINGS
    @given(data=st.data())
    def test_without_epoch_date_sorts_after_semver(self, data: st.DataObject) -> None:
        """Without epochs, date-based versions sort after smaller semver versions."""
        versions = [
            Version("1.0"),
            Version("1.1"),
            Version("2.0"),
            Version("2013.10"),
            Version("2014.04"),
        ]
        i = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        j = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        if i < j:
            assert versions[i] < versions[j]
        elif i == j:
            assert versions[i] == versions[j]
        else:
            assert versions[i] > versions[j]


class TestEpochReorderingExample:
    """However, by specifying an explicit epoch, the sort order can be changed
    appropriately, as all versions from a later epoch are sorted after versions
    from an earlier epoch::

        2013.10
        2014.04
        1!1.0
        1!1.1
        1!2.0"""

    @SETTINGS
    @given(data=st.data())
    def test_epoch_example_ordering(self, data: st.DataObject) -> None:
        """The example with epochs produces the expected ordering."""
        versions = [
            Version("2013.10"),
            Version("2014.04"),
            Version("1!1.0"),
            Version("1!1.1"),
            Version("1!2.0"),
        ]
        i = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        j = data.draw(st.integers(min_value=0, max_value=len(versions) - 1))
        if i < j:
            assert versions[i] < versions[j]
        elif i == j:
            assert versions[i] == versions[j]
        else:
            assert versions[i] > versions[j]

    @given(
        epoch_a=st.integers(min_value=0, max_value=5),
        epoch_b=st.integers(min_value=0, max_value=5),
        rel_a=st.tuples(small_ints, small_ints),
        rel_b=st.tuples(small_ints, small_ints),
    )
    @SETTINGS
    def test_later_epoch_always_greater(
        self,
        epoch_a: int,
        epoch_b: int,
        rel_a: tuple[int, int],
        rel_b: tuple[int, int],
    ) -> None:
        """All versions from a later epoch sort after versions from an earlier epoch."""
        assume(epoch_a != epoch_b)
        va_str = (
            f"{rel_a[0]}.{rel_a[1]}"
            if epoch_a == 0
            else f"{epoch_a}!{rel_a[0]}.{rel_a[1]}"
        )
        vb_str = (
            f"{rel_b[0]}.{rel_b[1]}"
            if epoch_b == 0
            else f"{epoch_b}!{rel_b[0]}.{rel_b[1]}"
        )
        va = Version(va_str)
        vb = Version(vb_str)
        if epoch_a < epoch_b:
            assert va < vb
        else:
            assert va > vb
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1103568
packaging-26.2/tests/pylock/pylock.spec-example.toml0000644000000000000000000000532415172742311017547 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=1777059017.1103568
packaging-26.2/tests/test_dependency_groups.py0000644000000000000000000003524215172742311016616 0ustar00from __future__ import annotations

import re
import sys
import unittest.mock
from typing import Any

import pytest

from packaging.dependency_groups import (
    CyclicDependencyGroup,
    DependencyGroupInclude,
    DependencyGroupResolver,
    DuplicateGroupNames,
    InvalidDependencyGroupObject,
    resolve_dependency_groups,
)
from packaging.errors import ExceptionGroup
from packaging.requirements import Requirement

if sys.version_info >= (3, 10):
    from typing import TypeAlias
else:
    from typing_extensions import TypeAlias

GroupsTable: TypeAlias = "dict[str, list[str | dict[str, str]]]"


def _group_contains(
    excinfo: pytest.ExceptionInfo[ExceptionGroup],
    exc_type: type[BaseException],
    *,
    match: str | re.Pattern[str] | None = None,
) -> bool:
    """
    pytest.raises().group_contains() cannot be used on ExceptionGroup
    because it doesn't inherit from `exceptiongroup.BaseExceptionGroup` on
    python versions < 3.11 .

    This is a similar helper, just for these tests.
    """
    exc_group = excinfo.value
    assert isinstance(exc_group, ExceptionGroup)

    for exc in exc_group.exceptions:
        if not isinstance(exc, exc_type):
            continue
        if match is not None and not re.search(match, str(exc)):
            continue
        return True

    return False


def test_resolver_init_catches_normalization_conflict() -> None:
    groups: GroupsTable = {"test": ["pytest"], "Test": ["pytest", "coverage"]}
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data was invalid"
    ) as excinfo:
        DependencyGroupResolver(groups)

    assert _group_contains(
        excinfo, DuplicateGroupNames, match="Duplicate dependency group names"
    )


def test_lookup_on_trivial_normalization() -> None:
    groups: GroupsTable = {"test": ["pytest"]}
    resolver = DependencyGroupResolver(groups)
    parsed_group = resolver.lookup("Test")
    assert len(parsed_group) == 1
    assert isinstance(parsed_group[0], Requirement)
    req = parsed_group[0]
    assert req.name == "pytest"


def test_lookup_with_include_result() -> None:
    groups: GroupsTable = {
        "test": ["pytest", {"include-group": "runtime"}],
        "runtime": ["click"],
    }
    resolver = DependencyGroupResolver(groups)
    parsed_group = resolver.lookup("test")
    assert len(parsed_group) == 2

    assert isinstance(parsed_group[0], Requirement)
    assert parsed_group[0].name == "pytest"

    assert isinstance(parsed_group[1], DependencyGroupInclude)
    assert parsed_group[1].include_group == "runtime"


def test_lookup_does_not_trigger_cyclic_include() -> None:
    groups: GroupsTable = {
        "group1": [{"include-group": "group2"}],
        "group2": [{"include-group": "group1"}],
    }
    resolver = DependencyGroupResolver(groups)
    parsed_group = resolver.lookup("group1")
    assert len(parsed_group) == 1

    assert isinstance(parsed_group[0], DependencyGroupInclude)
    assert parsed_group[0].include_group == "group2"


def test_expand_contract_model_only_does_inner_lookup_once() -> None:
    groups: GroupsTable = {
        "root": [
            {"include-group": "mid1"},
            {"include-group": "mid2"},
            {"include-group": "mid3"},
            {"include-group": "mid4"},
        ],
        "mid1": [{"include-group": "contract"}],
        "mid2": [{"include-group": "contract"}],
        "mid3": [{"include-group": "contract"}],
        "mid4": [{"include-group": "contract"}],
        "contract": [{"include-group": "leaf"}],
        "leaf": ["attrs"],
    }
    resolver = DependencyGroupResolver(groups)

    real_inner_resolve = resolver._resolve
    with unittest.mock.patch(
        "packaging.dependency_groups.DependencyGroupResolver._resolve",
        side_effect=real_inner_resolve,
    ) as spy:
        resolved = resolver.resolve("root")
        assert len(resolved) == 4
        assert all(item.name == "attrs" for item in resolved)

        # each of the `mid` nodes will call resolution with `contract`, but only the
        # first of those evaluations should call for resolution of `leaf` -- after that,
        # `contract` will be in the cache and `leaf` will not need to be resolved
        spy.assert_any_call("leaf", "root", unittest.mock.ANY)
        leaf_calls = [c for c in spy.mock_calls if c.args[0] == "leaf"]
        assert len(leaf_calls) == 1


def test_no_double_parse() -> None:
    groups: GroupsTable = {
        "test": [{"include-group": "runtime"}],
        "runtime": ["click"],
    }
    resolver = DependencyGroupResolver(groups)

    parse = resolver.lookup("test")
    assert len(parse) == 1
    assert isinstance(parse[0], DependencyGroupInclude)
    assert parse[0].include_group == "runtime"

    mock_include = DependencyGroupInclude(include_group="perfidy")

    with unittest.mock.patch(
        "packaging.dependency_groups.DependencyGroupInclude",
        return_value=mock_include,
    ):
        # rerunning with that resolver will not re-resolve
        reparse = resolver.lookup("test")
        assert len(reparse) == 1
        assert isinstance(reparse[0], DependencyGroupInclude)
        assert reparse[0].include_group == "runtime"

        # but verify that a fresh resolver (no cache) will get the mock
        deceived_resolver = DependencyGroupResolver(groups)
        deceived_parse = deceived_resolver.lookup("test")
        assert len(deceived_parse) == 1
        assert isinstance(deceived_parse[0], DependencyGroupInclude)
        assert deceived_parse[0].include_group == "perfidy"


@pytest.mark.parametrize("group_name_declared", ["foo-bar", "foo_bar", "foo..bar"])
@pytest.mark.parametrize("group_name_used", ["foo-bar", "foo_bar", "foo..bar"])
def test_normalized_name_is_used_for_include_group_lookups(
    group_name_declared: str, group_name_used: str
) -> None:
    groups: GroupsTable = {
        group_name_declared: ["spam"],
        "eggs": [{"include-group": group_name_used}],
    }
    resolver = DependencyGroupResolver(groups)

    result = resolver.resolve("eggs")
    assert len(result) == 1
    assert isinstance(result[0], Requirement)
    req = result[0]
    assert req.name == "spam"


def test_empty_group() -> None:
    groups: GroupsTable = {"test": []}
    assert resolve_dependency_groups(groups, "test") == ()


def test_str_list_group() -> None:
    groups: GroupsTable = {"test": ["pytest"]}
    assert resolve_dependency_groups(groups, "test") == ("pytest",)


def test_single_include_group() -> None:
    groups: GroupsTable = {
        "test": [
            "pytest",
            {"include-group": "runtime"},
        ],
        "runtime": ["sqlalchemy"],
    }
    assert set(resolve_dependency_groups(groups, "test")) == {"pytest", "sqlalchemy"}


def test_sdual_include_group() -> None:
    groups: GroupsTable = {
        "test": [
            "pytest",
        ],
        "runtime": ["sqlalchemy"],
    }
    assert set(resolve_dependency_groups(groups, "test", "runtime")) == {
        "pytest",
        "sqlalchemy",
    }


def test_normalized_group_name() -> None:
    groups: GroupsTable = {
        "TEST": ["pytest"],
    }
    assert resolve_dependency_groups(groups, "test") == ("pytest",)


def test_no_such_group_name() -> None:
    groups: GroupsTable = {
        "test": ["pytest"],
    }
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'testing' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "testing")

    assert _group_contains(excinfo, LookupError, match="'testing' not found")


def test_duplicate_normalized_name() -> None:
    groups: GroupsTable = {
        "test": ["pytest"],
        "TEST": ["nose2"],
    }
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data was invalid"
    ) as excinfo:
        resolve_dependency_groups(groups, "test")

    assert _group_contains(
        excinfo,
        DuplicateGroupNames,
        match=r"Duplicate dependency group names: test \((test, TEST)|(TEST, test)\)",
    )


def test_cyclic_include() -> None:
    groups: GroupsTable = {
        "group1": [
            {"include-group": "group2"},
        ],
        "group2": [
            {"include-group": "group1"},
        ],
    }
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'group1' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "group1")

    assert _group_contains(
        excinfo,
        CyclicDependencyGroup,
        match=(
            "Cyclic dependency group include while resolving group1: "
            "group1 -> group2, group2 -> group1"
        ),
    )


def test_cyclic_include_many_steps() -> None:
    groups: GroupsTable = {}
    for i in range(100):
        groups[f"group{i}"] = [{"include-group": f"group{i + 1}"}]
    groups["group100"] = [{"include-group": "group0"}]
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'group0' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "group0")

    assert _group_contains(
        excinfo,
        CyclicDependencyGroup,
        match="Cyclic dependency group include while resolving group0: ",
    )


def test_cyclic_include_self() -> None:
    groups: GroupsTable = {
        "group1": [
            {"include-group": "group1"},
        ],
    }

    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'group1' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "group1")

    assert _group_contains(
        excinfo,
        CyclicDependencyGroup,
        match=(
            "Cyclic dependency group include while resolving group1: "
            "group1 includes itself"
        ),
    )


def test_cyclic_include_ring_under_root() -> None:
    groups: GroupsTable = {
        "root": [
            {"include-group": "group1"},
        ],
        "group1": [
            {"include-group": "group2"},
        ],
        "group2": [
            {"include-group": "group1"},
        ],
    }
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'root' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "root")

    assert _group_contains(
        excinfo,
        CyclicDependencyGroup,
        match=(
            "Cyclic dependency group include while resolving root: "
            "group1 -> group2, group2 -> group1"
        ),
    )


# each access to a cyclic group should raise an error
def test_cyclic_include_accessed_repeatedly_on_resolver_instance() -> None:
    groups: GroupsTable = {
        "group1": [
            {"include-group": "group2"},
        ],
        "group2": [
            {"include-group": "group1"},
        ],
    }
    resolver = DependencyGroupResolver(groups)

    # each access raises an exception group of the same shape
    for _ in range(3):
        with pytest.raises(
            ExceptionGroup,
            match=r"\[dependency-groups\] data for 'group1' was malformed",
        ) as excinfo:
            resolver.resolve("group1")
        assert _group_contains(
            excinfo,
            CyclicDependencyGroup,
            match=(
                "Cyclic dependency group include while resolving group1: "
                "group1 -> group2, group2 -> group1"
            ),
        )


# a string is a Sequence[str] but is explicitly checked and rejected
def test_non_str_data() -> None:
    groups: Any = {"test": "pytest, coverage"}
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'test' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "test")

    assert _group_contains(
        excinfo,
        TypeError,
        match=r"Dependency group 'test' contained a string rather than a list.",
    )


def test_non_list_data() -> None:
    groups: Any = {"test": 101}
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'test' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "test")

    assert _group_contains(
        excinfo, TypeError, match=r"Dependency group 'test' is not a sequence type."
    )


@pytest.mark.parametrize(
    "item",
    [
        {},
        {"foo": "bar"},
        {"include-group": "testing", "foo": "bar"},
    ],
)
def test_unknown_object_shape(item: dict[str, str] | object) -> None:
    groups: Any = {"test": [item]}
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'test' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "test")

    assert _group_contains(
        excinfo, InvalidDependencyGroupObject, match="Invalid dependency group item:"
    )


def test_non_unexpected_item_type() -> None:
    groups: Any = {"test": [object()]}
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'test' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "test")

    assert _group_contains(excinfo, TypeError, match="Invalid dependency group item")


def test_dependency_group_include_repr() -> None:
    include = DependencyGroupInclude("test")
    assert repr(include) == "DependencyGroupInclude('test')"


def test_resolution_can_capture_multiple_errors_at_once() -> None:
    groups: Any = {
        "all": [
            {"include-group": "all-invalid"},
            {"include-group": "all-valid"},
        ],
        "all-valid": [
            {"include-group": "empty"},
            {"include-group": "simple"},
        ],
        "all-invalid": [
            {"include-group": "self-reference"},
            {"include-group": "invalid-object"},
            {"include-group": "invalid-type"},
            {"include-group": "invalid-type"},
        ],
        "self-reference": [{"include-group": "self-reference"}],
        "invalid-object": [{}],
        "invalid-type": "foo",
        "empty": [],
        "simple": ["jsonschema<5"],
    }

    # sanity check: even in the presence of these invalid data, we can extract the valid
    # parts
    valid_resolution = resolve_dependency_groups(groups, "all-valid")
    assert len(valid_resolution) == 1
    assert valid_resolution[0] == "jsonschema<5"

    # however, resolving everything triggers *multiple* errors, from the various
    # incorrect pieces of data, collected in an exception group
    with pytest.raises(
        ExceptionGroup, match=r"\[dependency-groups\] data for 'all' was malformed"
    ) as excinfo:
        resolve_dependency_groups(groups, "all")

    assert _group_contains(
        excinfo,
        CyclicDependencyGroup,
        match=(
            "Cyclic dependency group include while resolving all: "
            "self-reference includes itself"
        ),
    )
    assert _group_contains(
        excinfo,
        TypeError,
        match=r"Dependency group 'invalid-type' contained a string rather than a list.",
    )
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1103568
packaging-26.2/tests/test_direct_url.py0000644000000000000000000002147415172742311015237 0ustar00from __future__ import annotations

import pytest

from packaging.direct_url import (
    ArchiveInfo,
    DirectUrl,
    DirectUrlValidationError,
    DirInfo,
    VcsInfo,
    _strip_url,
)


@pytest.mark.parametrize(
    "direct_url_dict",
    [
        {
            "url": "file:///projects/myproject",
            "dir_info": {},
        },
        {
            "url": "file:///projects/myproject",
            "dir_info": {"editable": True},
        },
        {
            "url": "file:///projects/myproject",
            "dir_info": {"editable": False},
        },
        {
            "url": "https://example.com/archive.zip",
            "archive_info": {
                "hashes": {"sha256": "f" * 40},
            },
        },
        {
            "url": "https://g.c/user/repo.git",
            "vcs_info": {
                "vcs": "git",
                "commit_id": "a" * 40,
                "requested_revision": "main",
            },
        },
    ],
)
def test_direct_url_round_trips(direct_url_dict: dict[str, object]) -> None:
    assert DirectUrl.from_dict(direct_url_dict).to_dict() == direct_url_dict


def test_legacy_hash_populates_hashes() -> None:
    direct_url = DirectUrl.from_dict(
        {
            "url": "https://example.com/archive.zip",
            "archive_info": {
                "hash": "sha256=" + "f" * 40,
            },
        }
    )
    assert direct_url.archive_info
    assert direct_url.archive_info.hashes == {"sha256": "f" * 40}


def test_to_dict_generate_legacy_hash() -> None:
    direct_url = DirectUrl(
        url="https://example.com/archive.zip",
        archive_info=ArchiveInfo(hashes={"sha256": "f" * 40}),
    )
    assert "hash" not in direct_url.to_dict()["archive_info"]
    assert (
        direct_url.to_dict(generate_legacy_hash=True)["archive_info"]["hash"]
        == "sha256=" + "f" * 40
    )


def test_to_dict_generate_legacy_hash_no_hashes() -> None:
    direct_url = DirectUrl(
        url="https://example.com/archive.zip",
        archive_info=ArchiveInfo(),
    )
    assert "hash" not in direct_url.to_dict(generate_legacy_hash=True)["archive_info"]


def test_to_dict_generate_legacy_hash_multiple_hashes() -> None:
    direct_url = DirectUrl(
        url="https://example.com/archive.zip",
        archive_info=ArchiveInfo(hashes={"sha256": "f" * 40, "md5": "1" * 32}),
    )
    assert (
        direct_url.to_dict(generate_legacy_hash=True)["archive_info"]["hash"]
        == "sha256=" + "f" * 40
    )


def test_validate_archive_info_hashes() -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=r"Hash values must be strings in 'archive_info.hashes'",
    ):
        DirectUrl.from_dict(
            {
                "url": "https://example.com/archive.zip",
                "archive_info": {
                    "hashes": {"md5": 12345},
                },
            }
        )


def test_validate_archive_info_hash_invalid_format() -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=(
            r"Invalid hash format \(expected '='\) "
            r"in 'archive_info.hash'"
        ),
    ):
        DirectUrl.from_dict(
            {
                "url": "https://example.com/archive.zip",
                "archive_info": {
                    "hash": "md5:12345",
                },
            }
        )


def test_validate_archive_info_hash_missing_in_hashes() -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=r"Algorithm 'md5' used in hash field is not present in hashes field",
    ):
        DirectUrl.from_dict(
            {
                "url": "https://example.com/archive.zip",
                "archive_info": {
                    "hashes": {"sha256": "f" * 40},
                    "hash": "md5=12345",
                },
            }
        )


def test_validate_archive_info_hash_different_in_hashes() -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=(
            r"Algorithm 'md5' used in hash field has different value in hashes field "
            r"in 'archive_info.hash'"
        ),
    ):
        DirectUrl.from_dict(
            {
                "url": "https://example.com/archive.zip",
                "archive_info": {
                    "hashes": {"md5": "123456"},
                    "hash": "md5=12345",
                },
            }
        )


def test_validate_archive_info_hash_same_in_hashes() -> None:
    DirectUrl.from_dict(
        {
            "url": "https://example.com/archive.zip",
            "archive_info": {
                "hashes": {"md5": "123456"},
                "hash": "md5=123456",
            },
        }
    )


@pytest.mark.parametrize(
    "direct_url_dict",
    [
        {
            "url": "file:///projects/myproject",
        },
        {
            "url": "https://example.com/archive.zip",
            "archive_info": {},
            "dir_info": {},
        },
        {
            "url": "https://g.c/user/repo.git",
            "vcs_info": {
                "vcs": "git",
                "commit_id": "a" * 40,
            },
            "archive_info": {},
        },
    ],
)
def test_one_info_field(direct_url_dict: dict[str, object]) -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=r"Exactly one of vcs_info, archive_info, dir_info must be present",
    ):
        DirectUrl.from_dict(direct_url_dict)


def test_dir_info_url_scheme_file() -> None:
    DirectUrl.from_dict(
        {
            "url": "file:///home/myproject",
            "dir_info": {},
        }
    )
    with pytest.raises(
        DirectUrlValidationError,
        match=r"URL scheme must be file:// when dir_info is present",
    ):
        DirectUrl.from_dict(
            {
                "url": "https://example.com/projects/myproject",
                "dir_info": {},
            }
        )


def test_missing_url() -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=r"Missing required value in 'url'",
    ):
        DirectUrl.from_dict(
            {
                "dir_info": {},
            }
        )


def test_commit_id_type() -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=r"Unexpected type int \(expected str\) in 'vcs_info.commit_id'",
    ):
        DirectUrl.from_dict(
            {
                "url": "https://g.c/user/repo.git",
                "vcs_info": {"vcs": "git", "commit_id": 12345},
            }
        )


def test_validate() -> None:
    direct_url = DirectUrl(url="file:///projects/myproject", dir_info=DirInfo())
    direct_url.validate()


def test_validate_error() -> None:
    direct_url = DirectUrl(url="file:///projects/myproject")
    with pytest.raises(DirectUrlValidationError):
        direct_url.validate()


@pytest.mark.parametrize(
    ("url", "safe_user_passwords", "expected_url"),
    [
        ("https://g.c/user/repo.git", ["git"], "https://g.c/user/repo.git"),
        ("https://user:pass@g.c/user/repo.git", ["git"], "https://g.c/user/repo.git"),
        ("ssh://git@g.c/user/repo.git", [], "ssh://g.c/user/repo.git"),
        ("ssh://git@g.c/user/repo.git", ["git"], "ssh://git@g.c/user/repo.git"),
        ("ssh://cvs@g.c/user/repo.git", ["git"], "ssh://g.c/user/repo.git"),
        ("ssh://cvs@g.c/user/repo.git", ["git", "cvs"], "ssh://cvs@g.c/user/repo.git"),
        (
            "https://${USER}:${PASSWORD}@g.c/user/repo.git",
            ["git"],
            "https://${USER}:${PASSWORD}@g.c/user/repo.git",
        ),
        (
            "https://user:${PASSWORD}@g.c/user/repo.git",
            ["git"],
            "https://g.c/user/repo.git",
        ),
        (
            "https://git:${PASSWORD}@g.c/user/repo.git",
            ["git"],
            "https://g.c/user/repo.git",
        ),
        (
            "https://${TOKEN}@g.c/user/repo.git",
            ["git"],
            "https://${TOKEN}@g.c/user/repo.git",
        ),
    ],
)
def test_strip_url(url: str, safe_user_passwords: list[str], expected_url: str) -> None:
    assert _strip_url(url, safe_user_passwords) == expected_url


def test_to_dict_strip_url() -> None:
    direct_url = DirectUrl(
        url="https://user:pass@g.c/user/repo.git",
        vcs_info=VcsInfo(vcs="git", commit_id="a" * 40),
    )
    assert direct_url.to_dict()["url"] == "https://g.c/user/repo.git"


def test_to_dict_no_strip_url() -> None:
    direct_url = DirectUrl(
        url="https://user:pass@g.c/user/repo.git",
        vcs_info=VcsInfo(vcs="git", commit_id="a" * 40),
    )
    assert (
        direct_url.to_dict(strip_user_password=False)["url"]
        == "https://user:pass@g.c/user/repo.git"
    )


def test_to_dict_strip_url_git_safe_default() -> None:
    direct_url = DirectUrl(
        url="ssh://git@g.c/user/repo.git",
        vcs_info=VcsInfo(vcs="git", commit_id="a" * 40),
    )
    assert direct_url.to_dict()["url"] == "ssh://git@g.c/user/repo.git"
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1103568
packaging-26.2/tests/test_elffile.py0000644000000000000000000000636415172742311014512 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=1777059017.1103568
packaging-26.2/tests/test_errors.py0000644000000000000000000000706615172742311014420 0ustar00import pytest

import packaging.errors


def test_error_collector_collect() -> None:
    collector = packaging.errors._ErrorCollector()

    with collector.collect():
        raise ValueError("first error")

    with collector.collect():
        raise KeyError("second error")

    collector.error(TypeError("third error"))

    with pytest.raises(packaging.errors.ExceptionGroup) as exc_info:
        collector.finalize("collected errors")

    exception_group = exc_info.value
    assert exception_group.message == "collected errors"
    assert len(exception_group.exceptions) == 3
    assert isinstance(exception_group.exceptions[0], ValueError)
    assert str(exception_group.exceptions[0]) == "first error"
    assert isinstance(exception_group.exceptions[1], KeyError)
    assert str(exception_group.exceptions[1]) == "'second error'"
    assert isinstance(exception_group.exceptions[2], TypeError)
    assert str(exception_group.exceptions[2]) == "third error"


def test_error_collector_no_errors() -> None:
    collector = packaging.errors._ErrorCollector()

    with collector.collect():
        pass  # No error

    collector.finalize("no errors")  # Should not raise


def test_error_collector_exception_group() -> None:
    collector = packaging.errors._ErrorCollector()

    with collector.collect():
        raise packaging.errors.ExceptionGroup(
            "inner group",
            [ValueError("inner error 1"), KeyError("inner error 2")],
        )

    with pytest.raises(packaging.errors.ExceptionGroup) as exc_info:
        collector.finalize("outer group")

    exception_group = exc_info.value
    assert exception_group.message == "outer group"
    assert len(exception_group.exceptions) == 2
    assert isinstance(exception_group.exceptions[0], ValueError)
    assert str(exception_group.exceptions[0]) == "inner error 1"
    assert isinstance(exception_group.exceptions[1], KeyError)
    assert str(exception_group.exceptions[1]) == "'inner error 2'"


def test_error_collector_on_exit() -> None:
    collector = packaging.errors._ErrorCollector()

    with pytest.raises(packaging.errors.ExceptionGroup) as exc_info, collector.on_exit(
        "exiting"
    ):
        collector.error(ValueError("an error"))

    exception_group = exc_info.value
    assert exception_group.message == "exiting"
    assert len(exception_group.exceptions) == 1
    assert isinstance(exception_group.exceptions[0], ValueError)
    assert str(exception_group.exceptions[0]) == "an error"


def test_error_collector_on_exit_no_errors() -> None:
    collector = packaging.errors._ErrorCollector()

    with collector.on_exit("exiting"):
        pass  # No errors added


def test_error_collector_collect_specific_exception() -> None:
    collector = packaging.errors._ErrorCollector()

    with collector.collect(KeyError):
        raise KeyError("a key error")

    with pytest.raises(packaging.errors.ExceptionGroup) as exc_info:
        collector.finalize("collected errors")

    exception_group = exc_info.value
    assert exception_group.message == "collected errors"
    assert len(exception_group.exceptions) == 1
    assert isinstance(exception_group.exceptions[0], KeyError)
    assert str(exception_group.exceptions[0]) == "'a key error'"


def test_error_collector_collect_unmatched_exception() -> None:
    collector = packaging.errors._ErrorCollector()

    # Now test that other exceptions are not collected
    with pytest.raises(
        ValueError, match="a value error"
    ) as exc_info, collector.collect(KeyError):
        raise ValueError("a value error")

    assert str(exc_info.value) == "a value error"
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1103568
packaging-26.2/tests/test_licenses.py0000644000000000000000000000044215172742311014700 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=1777059017.1103568
packaging-26.2/tests/test_manylinux.py0000644000000000000000000001544615172742311015131 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=1777059017.1103568
packaging-26.2/tests/test_markers.py0000644000000000000000000006617315172742311014554 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 os
import pickle
import platform
import sys
from typing import Any, NamedTuple, cast
from unittest import mock

import pytest

from packaging._parser import Node, Op, Value, Variable
from packaging.markers import (
    InvalidMarker,
    Marker,
    UndefinedComparison,
    _format_full_version,
    default_environment,
)

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


class FakeVersionInfo(NamedTuple):
    major: int
    minor: int
    micro: int
    releaselevel: str
    serial: int


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:
        if environment is None:
            assert Marker(marker_string).evaluate() == expected
        else:
            assert Marker(marker_string).evaluate(environment) == 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:
        if environment is None:
            assert Marker(marker_string).evaluate() == expected
        else:
            assert Marker(marker_string).evaluate(environment) == 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


def test_and_operator_evaluates_true() -> None:
    env = {"python_version": "3.8", "os_name": "posix"}

    m = Marker('python_version >= "3.6"') & Marker('os_name == "posix"')
    assert m.evaluate(env) is True


def test_and_operator_str_equality() -> None:
    a = Marker('python_version >= "3.6" and os_name == "posix"')
    b = Marker('python_version >= "3.6"') & Marker('os_name == "posix"')
    assert a == b
    assert str(a) == str(b)


def test_or_operator_evaluates_true() -> None:
    env = {"python_version": "3.7", "os_name": "windows"}

    m = Marker('python_version < "3.6"') | Marker('os_name == "windows"')
    assert m.evaluate(env) is True


def test_or_operator_str_equality() -> None:
    a = Marker('python_version < "3.6" or os_name == "windows"')
    b = Marker('python_version < "3.6"') | Marker('os_name == "windows"')
    assert a == b
    assert str(a) == str(b)


def test_operator_rejects_non_marker() -> None:
    m = Marker('python_version >= "3.6"')
    # dunder returns NotImplemented for non-Marker
    assert m.__and__(cast("Any", "not-a-marker")) is NotImplemented
    assert m.__or__(cast("Any", 123)) is NotImplemented


def test_inplace_operators_fallback() -> None:
    m = Marker('python_version >= "3.6"')
    m &= Marker('os_name == "posix"')
    assert isinstance(m, Marker)
    assert m == Marker('python_version >= "3.6"') & Marker('os_name == "posix"')


def test_right_hand_ops_and_typeerror() -> None:
    m = Marker('python_version >= "3.6"')
    assert m.__and__(cast("Any", "x")) is NotImplemented
    with pytest.raises(TypeError):
        cast("Any", "not-a-marker") & Marker('python_version >= "3.6"')


def test_chaining_associativity_and_str() -> None:
    a = Marker(
        '(python_version >= "3.6" and os_name == "posix") '
        'and platform_system == "Linux"'
    )
    b = (
        Marker('python_version >= "3.6"')
        & Marker('os_name == "posix"')
        & Marker('platform_system == "Linux"')
    )
    assert a == b
    assert str(a) == str(b)


def test_hash_eq_for_combined_markers() -> None:
    assert hash(Marker('python_version >= "3.6" and os_name == "posix"')) == hash(
        Marker('python_version >= "3.6"') & Marker('os_name == "posix"')
    )


def test_evaluation_of_combined_markers() -> None:
    env = {"python_version": "3.8", "os_name": "posix", "platform_system": "Linux"}
    m = (
        Marker('python_version >= "3.6"')
        & Marker('os_name == "posix"')
        & Marker('platform_system == "Linux"')
    )
    assert m.evaluate(env) is True


@pytest.mark.parametrize(
    "marker_str",
    [
        'python_version >= "3.8"',
        'python_version >= "3.8" and os_name == "posix"',
        'python_version >= "3.8" or platform_system == "Windows"',
        'extra == "security"',
    ],
)
def test_pickle_marker_roundtrip(marker_str: str) -> None:
    # Make sure equality and str() work between a pickle/unpickle round trip.
    m = Marker(marker_str)
    loaded = pickle.loads(pickle.dumps(m))
    assert loaded == m
    assert str(loaded) == str(m)


def test_pickle_marker_setstate_rejects_invalid_state() -> None:
    # Cover the TypeError branches in __setstate__ for invalid input.
    m = Marker.__new__(Marker)
    with pytest.raises(TypeError, match="Cannot restore Marker"):
        m.__setstate__(12345)
    with pytest.raises(TypeError, match="Cannot restore Marker"):
        m.__setstate__((1, 2, 3))  # Wrong tuple length


# Pickle bytes generated with packaging==26.1, Python 3.13.1, pickle protocol 2.
# Format: __slots__ (no __getstate__), state is (None, {slot: value}).
_PACKAGING_26_1_PICKLE_MARKER_PYTHON_VERSION_GE_3_8 = (
    b"\x80\x02cpackaging.markers\nMarker\nq\x00)\x81q\x01N}q\x02X\x08\x00"
    b"\x00\x00_markersq\x03]q\x04cpackaging._parser\nVariable\nq\x05)\x81"
    b"q\x06N}q\x07X\x05\x00\x00\x00valueq\x08X\x0e\x00\x00\x00python_vers"
    b"ionq\ts\x86q\nbcpackaging._parser\nOp\nq\x0b)\x81q\x0cN}q\rh\x08X\x02"
    b"\x00\x00\x00>=q\x0es\x86q\x0fbcpackaging._parser\nValue\nq\x10)\x81q"
    b"\x11N}q\x12h\x08X\x03\x00\x00\x003.8q\x13s\x86q\x14b\x87q\x15as\x86"
    b"q\x16b."
)


# Pickle bytes generated with packaging==26.0, Python 3.13.1, pickle protocol 2.
# Format: __slots__ (no __getstate__), state is plain __dict__.
_PACKAGING_26_0_PICKLE_MARKER_PYTHON_VERSION_GE_3_8 = (
    b"\x80\x02cpackaging.markers\nMarker\nq\x00)\x81q\x01}q\x02X\x08\x00\x00"
    b"\x00_markersq\x03]q\x04cpackaging._parser\nVariable\nq\x05)\x81q\x06N}"
    b"q\x07X\x05\x00\x00\x00valueq\x08X\x0e\x00\x00\x00python_versionq\ts\x86"
    b"q\nbcpackaging._parser\nOp\nq\x0b)\x81q\x0cN}q\rh\x08X\x02\x00\x00"
    b"\x00>=q\x0es\x86q\x0fbcpackaging._parser\nValue\nq\x10)\x81q\x11N}q\x12"
    b"h\x08X\x03\x00\x00\x003.8q\x13s\x86q\x14b\x87q\x15asb."
)

# Format: __slots__ with Node objects using __dict__ format (packaging <= 25.0).
# Now loadable because Node classes have __getstate__/__setstate__.
_PACKAGING_25_0_PICKLE_MARKER_PYTHON_VERSION_GE_3_8 = (
    b"\x80\x02cpackaging.markers\nMarker\nq\x00)\x81q\x01}q\x02X\x08\x00\x00"
    b"\x00_markersq\x03]q\x04cpackaging._parser\nVariable\nq\x05)\x81q\x06}q\x07"
    b"X\x05\x00\x00\x00valueq\x08X\x0e\x00\x00\x00python_versionq\tsbcpackaging"
    b"._parser\nOp\nq\n)\x81q\x0b}q\x0ch\x08X\x02\x00\x00\x00>=q\rsbcpackaging"
    b"._parser\nValue\nq\x0e)\x81q\x0f}q\x10h\x08X\x03\x00\x00\x003.8q\x11sb\x87"
    b"q\x12asb."
)


def test_pickle_marker_old_format_loads() -> None:
    # Verify that Marker pickles created with packaging <= 26.1 (__slots__,
    # no __getstate__) can be loaded and produce correct Marker objects.
    m = pickle.loads(_PACKAGING_26_1_PICKLE_MARKER_PYTHON_VERSION_GE_3_8)
    assert isinstance(m, Marker)
    assert str(m) == 'python_version >= "3.8"'
    assert m == Marker('python_version >= "3.8"')


def test_pickle_marker_26_0_format_loads() -> None:
    # Verify that Marker pickles created with packaging 26.0 (plain __dict__)
    # can be loaded and produce correct Marker objects.
    m = pickle.loads(_PACKAGING_26_0_PICKLE_MARKER_PYTHON_VERSION_GE_3_8)
    assert isinstance(m, Marker)
    assert str(m) == 'python_version >= "3.8"'
    assert m == Marker('python_version >= "3.8"')


def test_pickle_marker_25_0_format_loads() -> None:
    # Verify that Marker pickles created with packaging 25.0 (with Node __dict__)
    # can now be loaded thanks to __getstate__/__setstate__ in Node classes.
    m = pickle.loads(_PACKAGING_25_0_PICKLE_MARKER_PYTHON_VERSION_GE_3_8)
    assert isinstance(m, Marker)
    assert str(m) == 'python_version >= "3.8"'
    assert m == Marker('python_version >= "3.8"')


def test_pickle_node_roundtrip() -> None:
    # Cover Node.__getstate__ and Node.__setstate__ with the new string format.
    for node in (Variable("python_version"), Value("3.8"), Op(">=")):
        loaded = pickle.loads(pickle.dumps(node))
        assert loaded.value == node.value
        assert str(loaded) == str(node)


def test_pickle_node_setstate_rejects_invalid_state() -> None:
    # Cover the TypeError branch in Node.__setstate__ for invalid input.
    node = Variable.__new__(Variable)
    with pytest.raises(TypeError, match="Cannot restore Variable"):
        node.__setstate__(12345)

    node2 = Variable.__new__(Variable)
    with pytest.raises(TypeError, match="Cannot restore Variable"):
        node2.__setstate__((1, 2, 3))  # Wrong tuple length

    # Cover the legacy tuple branch where slot_dict doesn't have "value".
    node3 = Variable.__new__(Variable)
    with pytest.raises(TypeError, match="Cannot restore Variable"):
        node3.__setstate__((None, {"wrong_key": "foo"}))

    # Cover the legacy tuple branch where slot_dict has "value" but it's not a str.
    node4 = Variable.__new__(Variable)
    with pytest.raises(TypeError, match="Cannot restore Variable value from 123"):
        node4.__setstate__((None, {"value": 123}))

    # Cover the legacy dict branch where "value" exists but it's not a str.
    node5 = Value.__new__(Value)
    with pytest.raises(TypeError, match="Cannot restore Value value from 456"):
        node5.__setstate__({"value": 456})

    # Cover the legacy dict branch on Op (different subclass to ensure coverage).
    node6 = Op.__new__(Op)
    with pytest.raises(TypeError, match="Cannot restore Op value from 789"):
        node6.__setstate__({"value": 789})


def test_pickle_marker_setstate_legacy_slot_dict_without_markers_key() -> None:
    # Cover Marker.__setstate__ legacy tuple branch where slot_dict has no "_markers".
    m = Marker.__new__(Marker)
    with pytest.raises(TypeError, match="Cannot restore Marker"):
        m.__setstate__((None, {"other_key": "value"}))


def test_pickle_marker_setstate_rejects_invalid_markers_type() -> None:
    # Cover the dict branch where "_markers" exists but is not a list.
    m1 = Marker.__new__(Marker)
    with pytest.raises(TypeError, match="Cannot restore Marker"):
        m1.__setstate__({"_markers": "not a list"})

    # Cover the tuple branch where "_markers" exists but is not a list.
    m2 = Marker.__new__(Marker)
    with pytest.raises(TypeError, match="Cannot restore Marker"):
        m2.__setstate__((None, {"_markers": "not a list"}))


def test_pickle_marker_setstate_rejects_invalid_marker_string() -> None:
    # Cover the string branch where parsing raises ParserSyntaxError.
    m = Marker.__new__(Marker)
    with pytest.raises(TypeError, match="Cannot restore Marker"):
        m.__setstate__("this is not a valid marker")
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1103568
packaging-26.2/tests/test_metadata.py0000644000000000000000000012632315172742311014662 0ustar00from __future__ import annotations

import email
import inspect
import pathlib
import textwrap
import typing

import pytest

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

if typing.TYPE_CHECKING:
    from packaging.metadata import 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 = 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 = 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_invalid_charset_error_message(self) -> None:
        meta = metadata.Metadata.from_raw(
            {"description_content_type": "text/plain; charset=iso-8859-1"},
            validate=False,
        )

        with pytest.raises(metadata.InvalidMetadata, match="iso-8859-1"):
            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=1777059017.1103568
packaging-26.2/tests/test_musllinux.py0000644000000000000000000000552715172742311015144 0ustar00from __future__ import annotations

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


class Proc(typing.NamedTuple):
    stderr: str


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) -> Proc:
        return 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=1777059017.1103568
packaging-26.2/tests/test_pylock.py0000644000000000000000000006044115172742311014401 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,
    PackageSdist,
    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-1.0.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"


@pytest.mark.parametrize(
    ("dist", "expected_filename"),
    [
        # sdists
        (
            PackageSdist(
                name="example-1.0.tar.gz",
                hashes={},
            ),
            "example-1.0.tar.gz",
        ),
        (
            PackageSdist(
                path="./example-1.0.tar.gz",
                hashes={},
            ),
            "example-1.0.tar.gz",
        ),
        (
            PackageSdist(
                path=".\\example-1.0.tar.gz",
                hashes={},
            ),
            "example-1.0.tar.gz",
        ),
        (
            PackageSdist(
                path="example-1.0.tar.gz",
                hashes={},
            ),
            "example-1.0.tar.gz",
        ),
        (
            PackageSdist(
                url="https://example.com/example-1.0.tar.gz",
                hashes={},
            ),
            "example-1.0.tar.gz",
        ),
        (
            # name preferred over path
            PackageSdist(
                name="example-2.0.tar.gz",
                path=".\\example-1.0.tar.gz",
                hashes={},
            ),
            "example-2.0.tar.gz",
        ),
        (
            # name preferred over url
            PackageSdist(
                name="example-2.0.tar.gz",
                url="https://example.com/example-1.0.tar.gz",
                hashes={},
            ),
            "example-2.0.tar.gz",
        ),
        (
            # path preferred over url
            PackageSdist(
                url="https://example.com/example-2.0.tar.gz",
                path="./example-1.0.tar.gz",
                hashes={},
            ),
            "example-1.0.tar.gz",
        ),
        # wheels
        (
            PackageWheel(
                name="example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-1.0-py3-none-any.whl",
        ),
        (
            PackageWheel(
                path="./example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-1.0-py3-none-any.whl",
        ),
        (
            PackageWheel(
                path=".\\example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-1.0-py3-none-any.whl",
        ),
        (
            PackageWheel(
                path="example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-1.0-py3-none-any.whl",
        ),
        (
            PackageWheel(
                url="https://example.com/example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-1.0-py3-none-any.whl",
        ),
        (
            # name preferred over path
            PackageWheel(
                name="example-2.0-py3-none-any.whl",
                path=".\\example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-2.0-py3-none-any.whl",
        ),
        (
            # name preferred over url
            PackageWheel(
                name="example-2.0-py3-none-any.whl",
                url="https://example.com/example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-2.0-py3-none-any.whl",
        ),
        (
            # path preferred over url
            PackageWheel(
                url="https://example.com/example-2.0-py3-none-any.whl",
                path="./example-1.0-py3-none-any.whl",
                hashes={},
            ),
            "example-1.0-py3-none-any.whl",
        ),
    ],
)
def test_dist_filename(
    dist: PackageSdist | PackageWheel, expected_filename: str
) -> None:
    assert dist.filename == expected_filename


def test_missing_sdist_filename() -> None:
    with pytest.raises(PylockValidationError) as exc_info:
        _ = PackageSdist(hashes={}).filename
    assert str(exc_info.value) == "Cannot determine sdist filename"


def test_missing_wheel_filename() -> None:
    with pytest.raises(PylockValidationError) as exc_info:
        _ = PackageWheel(hashes={}).filename
    assert str(exc_info.value) == "Cannot determine wheel filename"


def test_pylock_invalid_wheel_filename() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "wheels": [
                    {
                        "url": "http://example.com/example-1.0.whl",
                        "hashes": {"sha256": "f" * 40},
                    }
                ],
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Invalid wheel filename 'example-1.0.whl' in 'packages[0].wheels[0]'"
    )


def test_pylock_inconsistent_wheel_name() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "foo",
                "wheels": [
                    {
                        "url": "http://example.com/bar-1.0-py3-none-any.whl",
                        "hashes": {"sha256": "f" * 40},
                    }
                ],
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Name in 'bar-1.0-py3-none-any.whl' is not consistent "
        "with package name 'foo' in 'packages[0].wheels[0]'"
    )


def test_pylock_inconsistent_wheel_version() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "bar",
                "version": "2.0",
                "wheels": [
                    {
                        "url": "http://example.com/bar-1.0-py3-none-any.whl",
                        "hashes": {"sha256": "f" * 40},
                    }
                ],
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Version in 'bar-1.0-py3-none-any.whl' is not consistent "
        "with package version '2.0' in 'packages[0].wheels[0]'"
    )


def test_pylock_invalid_sdist_filename() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "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) == (
        "Invalid sdist filename 'example.tar.gz' in 'packages[0].sdist'"
    )


def test_pylock_inconsistent_sdist_name() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "foo",
                "sdist": {
                    "path": "./bar-1.0.tar.gz",
                    "hashes": {"sha256": "f" * 40},
                },
            },
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Name in 'bar-1.0.tar.gz' is not consistent "
        "with package name 'foo' in 'packages[0].sdist'"
    )


def test_pylock_inconsistent_sdist_version() -> None:
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "bar",
                "version": "2.0",
                "sdist": {
                    "path": "./bar-1.0.tar.gz",
                    "hashes": {"sha256": "f" * 40},
                },
            },
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Version in 'bar-1.0.tar.gz' is not consistent "
        "with package version '2.0' in 'packages[0].sdist'"
    )


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=1777059017.1113567
packaging-26.2/tests/test_pylock_select.py0000644000000000000000000002561415172742311015743 0ustar00from __future__ import annotations

import dataclasses
import sys
from pathlib import Path
from typing import TYPE_CHECKING, cast

import pytest

from packaging.markers import Marker
from packaging.pylock import (
    Package,
    PackageArchive,
    PackageDirectory,
    PackageSdist,
    PackageVcs,
    PackageWheel,
    Pylock,
    PylockSelectError,
)
from packaging.specifiers import SpecifierSet
from packaging.tags import Tag
from packaging.version import Version

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

if TYPE_CHECKING:
    from packaging.markers import Environment
    from packaging.utils import NormalizedName


@dataclasses.dataclass
class Platform:
    tags: list[Tag]
    environment: Environment


_py312_linux = Platform(
    tags=[
        Tag("cp312", "cp312", "manylinux_2_17_x86_64"),
        Tag("py3", "none", "any"),
    ],
    environment={
        "implementation_name": "cpython",
        "implementation_version": "3.12.12",
        "os_name": "posix",
        "platform_machine": "x86_64",
        "platform_release": "6.8.0-100-generic",
        "platform_system": "Linux",
        "platform_version": "#100-Ubuntu SMP PREEMPT_DYNAMIC",
        "python_full_version": "3.12.12",
        "platform_python_implementation": "CPython",
        "python_version": "3.12",
        "sys_platform": "linux",
    },
)


def test_smoke_test() -> None:
    pylock_path = Path(__file__).parent / "pylock" / "pylock.spec-example.toml"
    lock = Pylock.from_dict(tomllib.loads(pylock_path.read_text()))
    for package, dist in lock.select(
        tags=_py312_linux.tags,
        environment=_py312_linux.environment,
    ):
        assert isinstance(package, Package)
        assert isinstance(dist, PackageWheel)


def test_lock_no_matching_env() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        environments=[Marker('python_version == "3.14"')],
        packages=[],
    )
    pylock.validate()
    with pytest.raises(
        PylockSelectError,
        match=(
            "Provided environment does not satisfy any of the "
            "environments specified in the lock file"
        ),
    ):
        list(
            pylock.select(
                tags=_py312_linux.tags,
                environment=_py312_linux.environment,
            )
        )


def test_lock_require_python_mismatch() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        requires_python=SpecifierSet("==3.14.*"),
        packages=[],
    )
    pylock.validate()
    with pytest.raises(
        PylockSelectError,
        match="provided environment does not satisfy the Python version requirement",
    ):
        list(
            pylock.select(
                tags=_py312_linux.tags,
                environment=_py312_linux.environment,
            )
        )


def test_package_require_python_mismatch() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=cast("NormalizedName", "foo"),
                version=Version("1.0"),
                requires_python=SpecifierSet("==3.14.*"),
                directory=PackageDirectory(path="."),
            ),
        ],
    )
    pylock.validate()
    with pytest.raises(
        PylockSelectError,
        match=(
            r"provided environment does not satisfy the Python version requirement "
            r".* for package 'foo'"
        ),
    ):
        list(
            pylock.select(
                tags=_py312_linux.tags,
                environment=_py312_linux.environment,
            )
        )


def test_package_select_by_marker() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=cast("NormalizedName", "tomli"),
                marker=Marker('python_version < "3.11"'),
                version=Version("1.0"),
                archive=PackageArchive(
                    path="tomli-1.0.tar.gz", hashes={"sha256": "abc123"}
                ),
            ),
            Package(
                name=cast("NormalizedName", "foo"),
                marker=Marker('python_version >= "3.11"'),
                version=Version("1.0"),
                archive=PackageArchive(
                    path="foo-1.0.tar.gz", hashes={"sha256": "abc123"}
                ),
            ),
        ],
    )
    pylock.validate()
    selected = list(
        pylock.select(
            tags=_py312_linux.tags,
            environment=_py312_linux.environment,
        )
    )
    assert len(selected) == 1
    assert selected[0][0].name == "foo"


def test_duplicate_packages() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=cast("NormalizedName", "foo"),
                version=Version("1.0"),
                archive=PackageArchive(
                    path="tomli-1.0.tar.gz", hashes={"sha256": "abc123"}
                ),
            ),
            Package(
                name=cast("NormalizedName", "foo"),
                version=Version("2.0"),
                archive=PackageArchive(
                    path="foo-1.0.tar.gz", hashes={"sha256": "abc123"}
                ),
            ),
        ],
    )
    pylock.validate()
    with pytest.raises(
        PylockSelectError,
        match=(
            r"Multiple packages with the name 'foo' are selected "
            r"at packages\[1\] and packages\[0\]"
        ),
    ):
        list(
            pylock.select(
                tags=_py312_linux.tags,
                environment=_py312_linux.environment,
            )
        )


def test_yield_all_types() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=cast("NormalizedName", "foo-archive"),
                archive=PackageArchive(
                    path="tomli-1.0.tar.gz", hashes={"sha256": "abc123"}
                ),
            ),
            Package(
                name=cast("NormalizedName", "foo-directory"),
                directory=PackageDirectory(path="./foo-directory"),
            ),
            Package(
                name=cast("NormalizedName", "foo-vcs"),
                vcs=PackageVcs(
                    type="git", url="https://example.com/foo.git", commit_id="fa123"
                ),
            ),
            Package(
                name=cast("NormalizedName", "foo-sdist"),
                sdist=PackageSdist(
                    path="foo_sdist-1.0.tar.gz",
                    hashes={"sha256": "abc123"},
                ),
            ),
            Package(
                name=cast("NormalizedName", "foo-wheel"),
                wheels=[
                    PackageWheel(
                        name="foo_wheel-1.0-py3-none-any.whl",
                        path="./foo_wheel-1.0-py3-none-any.whl",
                        hashes={"sha256": "abc123"},
                    )
                ],
            ),
        ],
    )
    pylock.validate()
    selected = list(pylock.select())
    assert len(selected) == 5


def test_sdist_fallback() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=cast("NormalizedName", "foo"),
                sdist=PackageSdist(
                    path="foo-1.0.tar.gz",
                    hashes={"sha256": "abc123"},
                ),
                wheels=[
                    PackageWheel(
                        path="./foo-1.0-py5-none-any.whl",
                        hashes={"sha256": "abc123"},
                    )
                ],
            ),
        ],
    )
    selected = list(pylock.select())
    assert len(selected) == 1
    assert isinstance(selected[0][1], PackageSdist)


def test_missing_sdist_fallback() -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        packages=[
            Package(
                name=cast("NormalizedName", "foo"),
                wheels=[
                    PackageWheel(
                        name="foo-1.0-py5-none-any.whl",
                        path="./foo-1.0-py5-none-any.whl",
                        hashes={"sha256": "abc123"},
                    )
                ],
            ),
        ],
    )
    pylock.validate()
    with pytest.raises(
        PylockSelectError, match=r"No wheel found matching .* and no sdist available"
    ):
        list(pylock.select())


@pytest.mark.parametrize(
    ("extras", "dependency_groups", "expected"),
    [
        (None, None, ["foo", "foo-dev"]),  # select default_groups
        (None, ["dev"], ["foo", "foo-dev"]),  # same as default_groups
        (None, [], ["foo"]),  # select no groups
        (None, ["docs"], ["foo", "foo-docs"]),
        (None, ["dev", "docs"], ["foo", "foo-dev", "foo-docs"]),
        ([], None, ["foo", "foo-dev"]),
        (["feat1"], None, ["foo", "foo-dev", "foo-feat1"]),
        (["feat2"], None, ["foo", "foo-dev", "foo-feat2"]),
        (["feat1", "feat2"], None, ["foo", "foo-dev", "foo-feat1", "foo-feat2"]),
        (["feat1", "feat2"], ["docs"], ["foo", "foo-docs", "foo-feat1", "foo-feat2"]),
    ],
)
def test_extras_and_groups(
    extras: list[str] | None,
    dependency_groups: list[str] | None,
    expected: list[str],
) -> None:
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="some_tool",
        extras=[cast("NormalizedName", "feat1"), cast("NormalizedName", "feat2")],
        dependency_groups=["dev", "docs"],
        default_groups=["dev"],
        packages=[
            Package(
                name=cast("NormalizedName", "foo"),
                directory=PackageDirectory(path="./foo"),
            ),
            Package(
                name=cast("NormalizedName", "foo-dev"),
                directory=PackageDirectory(path="./foo-dev"),
                marker=Marker("'dev' in dependency_groups"),
            ),
            Package(
                name=cast("NormalizedName", "foo-docs"),
                directory=PackageDirectory(path="./foo-docs"),
                marker=Marker("'docs' in dependency_groups"),
            ),
            Package(
                name=cast("NormalizedName", "foo-feat1"),
                directory=PackageDirectory(path="./foo-feat1"),
                marker=Marker("'feat1' in extras"),
            ),
            Package(
                name=cast("NormalizedName", "foo-feat2"),
                directory=PackageDirectory(path="./foo-feat2"),
                marker=Marker("'feat2' in extras"),
            ),
        ],
    )
    pylock.validate()
    selected_names = [
        package.name
        for package, _ in pylock.select(
            extras=extras,
            dependency_groups=dependency_groups,
        )
    ]
    assert selected_names == expected
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1113567
packaging-26.2/tests/test_requirements.py0000644000000000000000000006556115172742311015633 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 pickle

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"


@pytest.mark.parametrize(
    "req_str",
    [
        "requests",
        "requests>=2.0",
        "requests>=2.0,<3.0",
        'requests>=2.0; python_version >= "3.8"',
        "requests[security,socks]>=2.0",
        "my-pkg @ https://example.com",
        'Django>=1.4.2,!=1.5.0,!=1.5.1; python_version < "3"',
    ],
)
def test_pickle_requirement_roundtrip(req_str: str) -> None:
    # Make sure equality and str() work between a pickle/unpickle round trip.
    r = Requirement(req_str)
    loaded = pickle.loads(pickle.dumps(r))
    assert loaded == r
    assert str(loaded) == str(r)


def test_pickle_requirement_setstate_rejects_invalid_state() -> None:
    # Cover the TypeError branches in __setstate__ for invalid input.
    r = Requirement.__new__(Requirement)
    with pytest.raises(TypeError, match="Cannot restore Requirement"):
        r.__setstate__(12345)
    with pytest.raises(TypeError, match="Cannot restore Requirement"):
        r.__setstate__((1, 2, 3))


def test_pickle_requirement_setstate_rejects_invalid_string() -> None:
    # Cover the string branch where Requirement() raises InvalidRequirement.
    r = Requirement.__new__(Requirement)
    with pytest.raises(TypeError, match="Cannot restore Requirement"):
        r.__setstate__("this is not a valid requirement")


# Pickle bytes generated with packaging==26.1, Python 3.13.1, pickle protocol 2.
# Format: plain __dict__ (no __getstate__). Contains nested SpecifierSet and
# Marker objects also pickled in their old format.
_PACKAGING_26_1_PICKLE_REQUESTS_GE_2_0_WITH_MARKER = (
    b"\x80\x02cpackaging.requirements\nRequirement\nq\x00)\x81q\x01}q\x02("
    b"X\x04\x00\x00\x00nameq\x03X\x08\x00\x00\x00requestsq\x04X\x03\x00"
    b"\x00\x00urlq\x05NX\x06\x00\x00\x00extrasq\x06c__builtin__\nset\nq\x07"
    b"]q\x08\x85q\tRq\nX\t\x00\x00\x00specifierq\x0bcpackaging.specifiers\n"
    b"SpecifierSet\nq\x0c)\x81q\rcpackaging.specifiers\nSpecifier\nq\x0e)\x81"
    b"q\x0fX\x02\x00\x00\x00>=q\x10X\x03\x00\x00\x002.0q\x11\x86q\x12N\x86"
    b"q\x13b\x85q\x14N\x86q\x15bX\x06\x00\x00\x00markerq\x16cpackaging."
    b"markers\nMarker\nq\x17)\x81q\x18N}q\x19X\x08\x00\x00\x00_markersq\x1a"
    b"]q\x1bcpackaging._parser\nVariable\nq\x1c)\x81q\x1dN}q\x1eX\x05\x00"
    b"\x00\x00valueq\x1fX\x0e\x00\x00\x00python_versionq s\x86q!b"
    b'cpackaging._parser\nOp\nq")\x81q#N}q$h\x1fX\x02\x00\x00\x00>=q%s'
    b"\x86q&bcpackaging._parser\nValue\nq')\x81q(N}q)h\x1fX\x03\x00\x00"
    b"\x003.8q*s\x86q+b\x87q,as\x86q-bub."
)


# Pickle bytes generated with packaging==26.0, Python 3.13.1, pickle protocol 2.
# Format: plain __dict__ (no __getstate__).
_PACKAGING_26_0_PICKLE_REQUESTS_GE_2_0 = (
    b"\x80\x02cpackaging.requirements\nRequirement\nq\x00)\x81q\x01}q\x02("
    b"X\x04\x00\x00\x00nameq\x03X\x08\x00\x00\x00requestsq\x04X\x03\x00"
    b"\x00\x00urlq\x05NX\x06\x00\x00\x00extrasq\x06c__builtin__\nset\nq\x07"
    b"]q\x08\x85q\tRq\nX\t\x00\x00\x00specifierq\x0bcpackaging.specifiers\n"
    b"SpecifierSet\nq\x0c)\x81q\rN}q\x0e(X\x0c\x00\x00\x00_prereleasesq\x0f"
    b"NX\x06\x00\x00\x00_specsq\x10c__builtin__\nfrozenset\nq\x11]q\x12cpackag"
    b"ing.specifiers\nSpecifier\nq\x13)\x81q\x14N}q\x15(h\x0fNX\x05\x00\x00"
    b"\x00_specq\x16X\x02\x00\x00\x00>=q\x17X\x03\x00\x00\x002.0q\x18\x86q"
    b"\x19X\r\x00\x00\x00_spec_versionq\x1ah\x18cpackaging.version\nVersion\n"
    b"q\x1b)\x81q\x1cN}q\x1d(X\x04\x00\x00\x00_devq\x1eNX\x06\x00\x00\x00_epo"
    b"chq\x1fK\x00X\n\x00\x00\x00_key_cacheq NX\x06\x00\x00\x00_localq!NX\x05"
    b'\x00\x00\x00_postq"NX\x04\x00\x00\x00_preq#NX\x08\x00\x00\x00_releaseq$'
    b"K\x02K\x00\x86q%u\x86q&b\x86q'u\x86q(b"
    b"a\x85q)Rq*u\x86q+bX\x06\x00\x00"
    b"\x00markerq,Nub."
)


# Pickle bytes generated with packaging==25.0, Python 3.13.1, pickle protocol 2.
# Format: plain __dict__ (no __getstate__).
_PACKAGING_25_0_PICKLE_REQUESTS_GE_2_0 = (
    b"\x80\x02cpackaging.requirements\nRequirement\nq\x00)\x81q\x01}q\x02("
    b"X\x04\x00\x00\x00nameq\x03X\x08\x00\x00\x00requestsq\x04X\x03\x00"
    b"\x00\x00urlq\x05NX\x06\x00\x00\x00extrasq\x06c__builtin__\nset\nq\x07"
    b"]q\x08\x85q\tRq\nX\t\x00\x00\x00specifierq\x0bcpackaging.specifiers\n"
    b"SpecifierSet\nq\x0c)\x81q\r}q\x0e(X\x06\x00\x00\x00_specsq\x0fc__bui"
    b"ltin__\nfrozenset\nq\x10]q\x11cpackaging.specifiers\nSpecifier\nq\x12)\x81"
    b"q\x13}q\x14(X\x05\x00\x00\x00_specq\x15X\x02\x00\x00\x00>=q\x16X\x03\x00"
    b"\x00\x002.0q\x17\x86q\x18X\x0c\x00\x00\x00_prereleasesq\x19Nuba\x85q\x1a"
    b"Rq\x1bh\x19NubX\x06\x00\x00\x00markerq\x1cNub."
)


def test_pickle_requirement_old_format_loads() -> None:
    # Verify that Requirement pickles created with packaging <= 26.1 (plain
    # __dict__, no __getstate__) can be loaded and produce correct objects.
    r = pickle.loads(_PACKAGING_26_1_PICKLE_REQUESTS_GE_2_0_WITH_MARKER)
    assert isinstance(r, Requirement)
    assert r.name == "requests"
    assert r.url is None
    assert r.extras == set()
    assert str(r.specifier) == ">=2.0"
    assert r.marker is not None
    assert str(r.marker) == 'python_version >= "3.8"'
    assert r == Requirement('requests>=2.0; python_version >= "3.8"')


def test_pickle_requirement_26_0_format_loads() -> None:
    # Verify that Requirement pickles created with packaging 26.0 (plain __dict__)
    # can be loaded and produce correct objects.
    r = pickle.loads(_PACKAGING_26_0_PICKLE_REQUESTS_GE_2_0)
    assert isinstance(r, Requirement)
    assert r.name == "requests"
    assert r.url is None
    assert r.extras == set()
    assert str(r.specifier) == ">=2.0"
    assert r.marker is None
    assert r == Requirement("requests>=2.0")


def test_pickle_requirement_25_0_format_loads() -> None:
    # Verify that Requirement pickles created with packaging 25.0 (plain __dict__)
    # can be loaded and produce correct objects.
    r = pickle.loads(_PACKAGING_25_0_PICKLE_REQUESTS_GE_2_0)
    assert isinstance(r, Requirement)
    assert r.name == "requests"
    assert r.url is None
    assert r.extras == set()
    assert str(r.specifier) == ">=2.0"
    assert r.marker is None
    assert r == Requirement("requests>=2.0")
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1113567
packaging-26.2/tests/test_specifiers.py0000644000000000000000000036375215172742311015247 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 pickle
import re
import sys
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", "==2.0.0.*"),
                ("2", "==0!2.*"),
                ("0!2", "==2.*"),
                ("2.0", "==2.*"),
                ("2.0.0", "==2.*"),
                ("2.0.0.0", "==2.0.*"),
                ("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.*"),
                ("3", "!=2.0.0.*"),
                ("2.1.0.0", "!=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"),
                # Test local versions with pre/dev/post segments and >
                # (verifies _public_version keeps pre/dev/post in the guard)
                ("1.0+local", ">1.0.dev1"),
                ("4.1.0a2.dev1235+local", ">4.1.0a2.dev1234"),
                ("1.0a2+local", ">1.0a1"),
                ("1.0b2+local", ">1.0b1"),
                ("1.0rc2+local", ">1.0rc1"),
                ("1.0.post2+local", ">1.0.post1"),
                ("1.0.dev2+local", ">1.0.dev1"),
                ("1.0a1.dev2+local", ">1.0a1.dev1"),
                ("1.0.post1.dev2+local", ">1.0.post1.dev1"),
            ]
        ]
        + [
            (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.*"),
                ("3", "==2.0.0.*"),
                ("2.1.0.0", "==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", "!=2.0.0.*"),
                ("2.0", "!=2.*"),
                ("2.0.0", "!=2.*"),
                ("2.0.0.0", "!=2.0.*"),
                # 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"),
                ("4.1.0a2.dev1234+local", ">4.1.0a2.dev1234"),
                # Test local versions with pre/dev/post segments and >
                # (local variant of the exact spec version must not match)
                ("1.0a1+local", ">1.0a1"),
                ("1.0b1+local", ">1.0b1"),
                ("1.0rc1+local", ">1.0rc1"),
                ("1.0.post1+local", ">1.0.post1"),
                ("1.0.dev1+local", ">1.0.dev1"),
                ("1.0a1.dev1+local", ">1.0a1.dev1"),
                ("1.0.post1.dev1+local", ">1.0.post1.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(
        ("spec_str", "version", "expected"),
        [
            # Zero padding: unnormalized spec vs string/Version
            # Strings preserve their original form, so "1.01" != "1.1"
            ("===1.1", "1.01", False),
            ("===1.01", "1.1", False),
            ("===1.01", "1.01", True),
            ("===1.1", "1.1", True),
            # Version objects are normalized, so Version("1.01") -> "1.1"
            ("===1.1", Version("1.01"), True),
            ("===1.1", Version("1.1"), True),
            ("===1.01", Version("1.01"), False),
            ("===1.01", Version("1.1"), False),
            # Prerelease separator normalization (issue #766)
            # "1.a1" is valid PEP 440, normalizes to "1a1"
            ("===1.a1", "1.a1", True),
            ("===1a1", "1.a1", False),
            ("===1.a1", "1a1", False),
            ("===1a1", "1a1", True),
            ("===1.a1", Version("1.a1"), False),
            ("===1a1", Version("1.a1"), True),
            # Epoch normalization: "0!1.0" normalizes to "1.0"
            ("===0!1.0", "0!1.0", True),
            ("===0!1.0", "1.0", False),
            ("===1.0", "0!1.0", False),
            ("===0!1.0", Version("1.0"), False),
            ("===1.0", Version("0!1.0"), True),
            # Leading zeros in release segments
            ("===01.0", "01.0", True),
            ("===01.0", "1.0", False),
            ("===1.0", "01.0", False),
            ("===01.0", Version("1.0"), False),
            ("===1.0", Version("01.0"), True),
            # Post-release normalization: "post" vs "-" separator
            ("===1.0.post1", "1.0.post1", True),
            ("===1.0-1", "1.0-1", True),
            ("===1.0-1", "1.0.post1", False),
            ("===1.0.post1", "1.0-1", False),
            ("===1.0-1", Version("1.0.post1"), False),
            ("===1.0.post1", Version("1.0-1"), True),
            # Dev normalization
            ("===1.0.dev01", "1.0.dev01", True),
            ("===1.0.dev01", "1.0.dev1", False),
            ("===1.0.dev1", "1.0.dev01", False),
            ("===1.0.dev01", Version("1.0.dev1"), False),
            ("===1.0.dev1", Version("1.0.dev01"), True),
        ],
    )
    def test_arbitrary_equality_normalization(
        self, spec_str: str, version: str | Version, expected: bool
    ) -> None:
        spec = Specifier(spec_str, prereleases=True)
        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),
            # >V.devN: post-releases of V.devN itself are excluded
            # (V.devN can't have post-releases in PEP 440, so nothing
            # to exclude; these just confirm ordering still works)
            (">1.0.dev1", "1.0.dev0", None, None, False),
            (">1.0.dev1", "1.0.dev2", None, None, True),
            # >V.devN: post-releases of the base release are NOT
            # post-releases of V.devN, so they are accepted
            (">1.0.dev1", "1.0.post0", None, None, True),
            (">1.0.dev1", "1.0.post1", None, None, True),
            (">1.0.dev0", "1.0.post0", None, None, True),
            # >V.preN: post-releases of the base release are NOT
            # post-releases of V.preN, so they are accepted
            (">1.0a1", "1.0.post0", None, None, True),
            (">1.0b1", "1.0.post0", None, None, True),
            (">1.0rc1", "1.0.post0", None, None, True),
            # >V.preN: post-releases of the pre-release itself
            # ARE excluded
            (">1.0a1", "1.0a1.post0", None, None, False),
            (">1.0b2", "1.0b2.post0", None, None, False),
            (">1.0rc1", "1.0rc1.post0", None, None, False),
            # >V.preN: post of a different pre is not a post-release
            # of V.preN either
            (">1.0a1", "1.0a2.post0", None, None, True),
            (">1.0b1", "1.0b2.post0", None, None, True),
            # >V.devN: non-post-release versions above V.devN
            (">1.0.dev1", "1.0", None, None, True),
            (">1.0.dev1", "1.0a1", None, None, True),
            (">1.0.dev1", "1.1", None, None, True),
            # >V (final): post-releases of V are still excluded
            (">1.0", "1.0.post0", None, None, False),
            (">1.0", "1.0.post1", None, None, False),
            # >V (final): post-releases of a different base are fine
            (">1.0", "2.0.post0", None, None, True),
            (">1.0", "0.9.post0", None, None, False),
            # >V.devN: locals and different bases
            (">1.0.dev1", "1.1.post0", None, None, True),
            (">1.0.dev1", "0.9.post0", None, None, False),
            #  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)

        if prereleases is None:
            result = list(spec.filter(input))
        else:
            result = list(spec.filter(input, prereleases=prereleases))

        assert result == expected

    @pytest.mark.parametrize(
        ("specifier", "input", "expected"),
        [
            # Strings preserve original form
            ("===1.01", ["1.01", "1.1", "1.0.1"], ["1.01"]),
            ("===1.1", ["1.01", "1.1"], ["1.1"]),
            # Version objects use normalized form
            (
                "===1.1",
                [Version("1.01"), Version("1.1")],
                [Version("1.01"), Version("1.1")],
            ),
            ("===1.01", [Version("1.01"), Version("1.1")], []),
            # Mixed strings and Version objects
            ("===1.1", ["1.01", "1.1", Version("1.01")], ["1.1", Version("1.01")]),
            ("===1.01", ["1.01", "1.1", Version("1.01")], ["1.01"]),
            # Prerelease separator
            ("===1.a1", ["1.a1", "1a1"], ["1.a1"]),
            ("===1a1", ["1.a1", "1a1", Version("1.a1")], ["1a1", Version("1.a1")]),
        ],
    )
    def test_specifier_filter_arbitrary_equality_normalization(
        self, specifier: str, input: list[str | Version], expected: list[str | Version]
    ) -> None:
        spec = Specifier(specifier, prereleases=True)
        assert list(spec.filter(input)) == expected

    @pytest.mark.parametrize(
        ("prereleases", "expected_indexes"),
        [
            (None, [1]),
            (True, [1]),
            (False, []),
        ],
    )
    def test_specifier_filter_with_key(
        self, prereleases: bool | None, expected_indexes: list[int]
    ) -> None:
        items = [
            {"version": "1.0"},
            {"version": "2.1a1"},
        ]
        spec = Specifier(">=2.0")
        if prereleases is None:
            result = list(spec.filter(items, key=lambda item: item["version"]))
        else:
            result = list(
                spec.filter(
                    items, key=lambda item: item["version"], prereleases=prereleases
                )
            )

        expected = [items[index] for index in expected_indexes]
        assert result == 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)
        assert list(spec.filter(versions)) == expected

    @pytest.mark.parametrize(
        ("versions", "expected"),
        [
            # Mixed prerelease, arbitrary, final - return arbitrary and final in order
            (
                ["1.0a1", "foobar", "1.0", "2.0a1", "bazqux", "2.0"],
                ["foobar", "1.0", "bazqux", "2.0"],
            ),
            # Mixed arbitrary, final - return all in order
            (
                ["foobar", "1.0", "bazqux", "2.0", "hello"],
                ["foobar", "1.0", "bazqux", "2.0", "hello"],
            ),
            # Mixed prerelease, arbitrary (no final) - return all in order
            (
                ["1.0a1", "foobar", "2.0a1", "bazqux", "3.0a1"],
                ["1.0a1", "foobar", "2.0a1", "bazqux", "3.0a1"],
            ),
        ],
    )
    def test_empty_specifier_ordering_with_arbitrary(
        self, versions: list[str], expected: list[str]
    ) -> None:
        spec = SpecifierSet("")
        result = list(spec.filter(versions))
        assert result == 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"]),
            # Test === with multiple specifiers matching non-parseable versions
            (
                "===foobar,===foobar",
                None,
                None,
                ["foobar", "foo", "bar"],
                ["foobar"],
            ),
            # Test ==.* in multi-specifier set
            ("==1.*,>=1.0", None, None, ["0.9", "1.0", "1.5", "2.0"], ["1.0", "1.5"]),
        ],
    )
    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)

        if prereleases is None:
            result = list(spec.filter(input))
        else:
            result = list(spec.filter(input, prereleases=prereleases))

        assert result == expected

    @pytest.mark.parametrize(
        ("prereleases", "expected_indexes"),
        [
            (None, [1]),
            (True, [1]),
            (False, []),
        ],
    )
    def test_specifierset_filter_with_key(
        self, prereleases: bool | None, expected_indexes: list[int]
    ) -> None:
        items = [
            {"version": "1.0"},
            {"version": "2.1a1"},
        ]
        spec = SpecifierSet(">=2")
        if prereleases is None:
            result = list(spec.filter(items, key=lambda item: item["version"]))
        else:
            result = list(
                spec.filter(
                    items, key=lambda item: item["version"], prereleases=prereleases
                )
            )

        expected = [items[index] for index in expected_indexes]
        assert result == expected

    @pytest.mark.parametrize(
        ("prereleases", "expected_indexes"),
        [
            (None, [1]),
            (True, [0, 1]),
            (False, [1]),
        ],
    )
    def test_empty_specifierset_filter_with_key(
        self, prereleases: bool | None, expected_indexes: list[int]
    ) -> None:
        items = [
            {"version": "2.0a1"},
            {"version": "2.1"},
        ]

        spec = SpecifierSet("", prereleases=prereleases)
        result = list(spec.filter(items, key=lambda item: item["version"]))

        expected = [items[index] for index in expected_indexes]
        assert result == 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)
        if prereleases is None:
            result = list(spec.filter(input))
        else:
            result = list(spec.filter(input, prereleases=prereleases))

        assert result == 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),
            # >V.devN combined with other specifiers: post-releases of
            # the base release are accepted (they are not post-releases
            # of V.devN).
            (">1.0.dev1,==1.0.post0", None, "1.0.post0", True),
            (">1.0.dev1,==1.0.post1", None, "1.0.post1", True),
            (">1.0a1,==1.0.post0", None, "1.0.post0", True),
            (">1.0.dev1,<=2.0", None, "1.0.post0", True),
            (">1.0.dev1,<=2.0", None, "1.0", True),
            # >V.preN: post of the pre-release itself is still excluded
            (">1.0a1,<=2.0", True, "1.0a1.post0", False),
            # With an upper bound that includes post-releases
            (">1.0.dev1,<=1.0.post1", None, "1.0.post0", True),
            (">1.0.dev1,<=1.0.post1", None, "1.0.post1", True),
            (">1.0.dev1,<=1.0.post1", None, "1.0", True),
            # != can remove some versions but post-releases still match
            (">1.0.dev1,!=1.0,<=2.0", None, "1.0.post0", True),
            (">1.0.dev1,!=1.0,!=1.0.post0,<=2.0", None, "1.0.post1", True),
            # =1.0,<1.0.post1", None, "1.0", True),
            (">=1.0,<1.0.post1", None, "1.0.post0", True),
            # 1.0.dev0 < 1.0, so it fails >=1.0 regardless of <
            (">=1.0,<1.0.post1", True, "1.0.dev0", False),
            # With a lower bound that includes pre-releases
            (">=1.0.dev0,<1.0.post1", True, "1.0.dev0", True),
            (">=1.0.dev0,<1.0.post1", True, "1.0.a1", True),
            (">=1.0.dev0,<1.0.post1", True, "1.0.post0.dev0", True),
            # != can remove non-pre-releases but pre-releases still match
            (">=1.0.dev0,<1.0.post1,!=1.0,!=1.0.post0", True, "1.0.dev0", True),
            (">=1.0.dev0,<1.0.post1,!=1.0,!=1.0.post0", True, "1.0.post0.dev0", True),
            # Post-release survivors still match
            (">=1.0.dev0,<1.0.post2,!=1.0,!=1.0.post0", True, "1.0.post1", True),
            (">=1.0.dev0,<1.0.post2,!=1.0", True, "1.0.post0", True),
        ],
    )
    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.skipif(
        not hasattr(sys, "get_int_max_str_digits"),
        reason="requires int max str digits limit",
    )
    @pytest.mark.parametrize(
        "specifier",
        [
            ">=" + "1" * 5000,
            ">=1.0a" + "1" * 5000,
        ],
    )
    def test_contains_oversized_version_raises_valueerror(self, specifier: str) -> None:
        old = sys.get_int_max_str_digits()
        sys.set_int_max_str_digits(4300)
        try:
            spec = SpecifierSet(specifier)
            with pytest.raises(ValueError, match="Exceeds the limit"):
                spec.contains("1.0")
        finally:
            sys.set_int_max_str_digits(old)

    @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(
        ("spec_str", "version", "expected"),
        [
            # Zero padding: string preserves original, Version normalizes
            ("===1.1", "1.01", False),
            ("===1.01", "1.1", False),
            ("===1.01", "1.01", True),
            ("===1.1", "1.1", True),
            ("===1.1", Version("1.01"), True),
            ("===1.01", Version("1.01"), False),
            # Prerelease separator normalization
            ("===1.a1", "1.a1", True),
            ("===1a1", "1.a1", False),
            ("===1.a1", "1a1", False),
            ("===1a1", "1a1", True),
            ("===1.a1", Version("1.a1"), False),
            ("===1a1", Version("1.a1"), True),
            # Combined with other operators
            (">=1.0,===1.01", "1.01", True),
            (">=1.0,===1.1", "1.1", True),
            (">=1.0,===1.1", "1.01", False),
            (">=1.0,===1.1", Version("1.01"), True),
            (">=1.0,===1.01", Version("1.01"), False),
        ],
    )
    def test_contains_arbitrary_equality_normalization(
        self, spec_str: str, version: str | Version, expected: bool
    ) -> None:
        spec = SpecifierSet(spec_str, prereleases=True)
        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_duplicate_normalization(self) -> None:
        # Specifiers that are equal but have different string representations
        # should be deduplicated for equality, hashing, and string output.
        a = SpecifierSet(">1.0.0,>1.0")
        b = SpecifierSet(">1.0")
        assert a == b
        assert hash(a) == hash(b)
        assert str(a) == str(b)

    def test_specifiers_combine_deduplicates(self) -> None:
        result = SpecifierSet(">=1.0") & SpecifierSet(">=1.0,<5.0")
        assert str(result) == "<5.0,>=1.0"

    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


def _version_family(base: str) -> list[str]:
    """All PEP 440 suffixes and combinations around a base version."""
    return [
        f"{base}.dev0",
        f"{base}.dev1",
        f"{base}.dev0+local",
        f"{base}a0",
        f"{base}a0.post0.dev0",
        f"{base}a0.post0",
        f"{base}a1.dev1",
        f"{base}a1.dev1+local",
        f"{base}a1",
        f"{base}a1+local",
        f"{base}b1",
        f"{base}b2.post1.dev1",
        f"{base}b2.post1",
        f"{base}rc1.dev1",
        f"{base}rc1",
        f"{base}rc2",
        f"{base}a2.dev0",
        base,
        f"{base}.0",
        f"{base}.post0.dev0",
        f"{base}.post0",
        f"{base}.post1.dev0",
        f"{base}.post1",
        f"{base}.post1+local",
        f"{base}.post2",
        f"{base}+local",
        f"{base}+local1",
        f"{base}+local2",
        f"{base}+1",
        f"{base}+1.local",
        f"{base}.1.dev1",
        f"{base}.1a1",
        f"{base}.1",
        f"{base}.1+local",
        f"{base}.1.post1",
    ]


_SAMPLE_BASES: list[str] = [
    "0",
    "0.0",
    "1.0",
    "1.1",
    "1.2",
    "2.0",
    "2.1",
    "3.0",
    "1.0.1",
    "1.4.2",
    "2.0.0",
    "3.10.2",
    "3.8",
    "3.9",
    "3.10",
    "3.11",
    "3.12",
    "3.13",
    "3.14",
    "10.0",
    "100.0",
    "1!0.0",
    "1!1.0",
    "1!2.0",
]


def _build_sample_versions(
    bases: list[str], family_fn: Callable[[str], list[str]]
) -> list[str]:
    """version_family x bases, deduplicated.  Returns strings (not Version
    objects) so === can also match unnormalized and non-PEP-440 samples."""
    version_strs: list[str] = []
    for base in bases:
        version_strs.extend(family_fn(base))
    seen: set[str] = set()
    unique: list[str] = []
    for v in version_strs:
        if v not in seen:
            seen.add(v)
            unique.append(v)
    return unique


_SAMPLE_VERSIONS: list[str] = _build_sample_versions(_SAMPLE_BASES, _version_family)

# Extra strings for === (arbitrary equality): unnormalized forms and
# non-PEP-440 strings that no Version object can represent.
_SAMPLE_VERSIONS += [
    "foobar",
    "a",
    "b",
    "not-a-version",
    "1.01",
    "1.0-1",
    "v1.0",
]


class TestIsUnsatisfiable:
    """Tests for SpecifierSet.is_unsatisfiable().

    Testing approach:
    - UNSATISFIABLE: detected as unsatisfiable, filter returns nothing.
    - SATISFIABLE: not falsely reported as unsatisfiable.
    """

    UNSATISFIABLE: typing.ClassVar[list[str]] = [
        # Crossed bounds
        ">=2.0,<1.0",
        ">=2.0,<2.0",
        ">2.0,<=2.0",
        ">2.0,<2.0",
        # Equality conflicts
        "==1.0,!=1.0",
        "==1.0,>1.0",
        "==1.0,<1.0",
        "==1.0,>=2.0",
        "==3.0,<2.0",
        # Wildcard conflicts
        "==1.*,>=2.0",
        "==2.*,<2.0.dev0",
        "==3.*,<3.0.dev0",
        "==1.0.*,!=1.0.*",
        "==1.0,!=1.*",
        # Compatible release conflicts
        "~=2.0,<2.0",
        "~=2.0,>=3.0",
        "~=2.5,<2.5",
        "~=1.0,>=2.0",
        "~=1.4.2,<1.4.2",
        # Point range excluded
        ">=1.0,<=1.0,!=1.0",
        # Epoch conflicts
        "==1!1.0,==1.0",
        ">=1!1.0,<1.0",
        ">=1!0.0,<1.0",
        # Zero/dev edge cases
        "<0",
        "<0.0",
        "<0.0.dev0",
        ">=1.0,<0.0.dev0",
        # =1.0a1,<1.0",
        ">=1.0.dev0,<1.0",
        ">=1.0rc1,<1.0",
        # =1.0.post1,<1.0.post1",
        ">=1.0.post1.dev0,<1.0.post1",
        # >V excludes posts of V; 1.0,<1.0.post0",
        ">1.0,<1.0.post1",
        # >V.postN + 1.0.post0,<1.0.post1",
        # dev crossing
        ">=1.0.dev5,<1.0.dev3",
        # == with dev/pre/post + > same version
        "==1.0.dev0,>1.0.dev0",
        "==1.0a1,>1.0a1",
        "==1.0.post1,>1.0.post1",
        # >V.preN excludes posts of V.preN; nothing between
        ">1.0a1,<1.0a1.post1",
        # ~= with dev/pre + conflicting range
        "~=1.0.dev0,>=2.0",
        "~=1.0a1,>=2.0",
        # Wildcard exhausts range
        ">=1.0,<2.0,!=1.*",
        "~=1.4.2,!=1.4.*",
        # Local version conflicts
        "==1.0+local,!=1.0+local",
        # === conflicts: multiple === with different strings
        "===a,===b",
        "===1.0,===2.0",
        # === with unparsable + standard spec
        "===foobar,==1.0",
        "===foobar,>=1.0",
        "===a,!=1.0",
        "===not-a-version,~=1.0",
        "===foobar,>=2.0,<3.0",
        # === with parsable version that fails standard specs
        "===1.0,>=2.0",
        "===1.0,!=1.0",
        "===1.0,>1.0",
        "===1.01,==1.0",
        # Non-overlapping wildcards (adjacent boundaries, upper exclusive)
        "==1.0.*,==1.1.*",
        "==1.*,==2.*",
        # Conflicting compatible releases
        "~=1.0,~=2.0",
        "~=1.4.2,~=1.5.0",
        # Local excluded by non-local != (locals ignored per spec)
        "==1.0+local1,!=1.0",
        # Wildcard exhaustion (single and multiple)
        ">=1.0,<1.1,!=1.0.*",
        "!=1.*,!=2.*,>=1.0,<3.0",
        "~=1.0,!=1.*",
        # >V excludes posts of pre-release V
        ">1.0a1,<1.0a1.post2",
        # Adjacent dev of zero: no version between devN and dev(N+1)
        ">0.dev0,<0.dev1",
        # Compatible release with pre/dev suffix vs V.postK.devN leaves no room
        ">1.0.post0.dev0,<1.0.post0",
        # Deep release crossing compatible release boundary
        "~=1.2.3.4.5,>=1.2.3.5",
        # Different base but release is above the =1.0",
        "<2.0",
        ">1.0",
        ">=1.0,<2.0",
        ">=1.0,<=1.0",
        ">=1.0,<100.0",
        # Compatible release
        "~=1.0",
        "~=1.0,<1.5",
        "~=1.4.2",
        # Wildcards
        "==1.0.*",
        "!=1.0.*",
        "==1.*,!=1.5",
        "==1.0.*,==1.*",
        "!=1.*,>=2.0",
        # Exclusions that don't exhaust range
        ">=1.0,<2.0,!=1.5,!=1.6",
        ">=1.0,<2.0,!=1.0,!=1.1,!=1.2,!=1.3,!=1.4",
        # Single operators
        "==1.0",
        "!=1.0",
        # Prerelease ranges
        ">=1.0.dev0,<1.0.dev1",
        ">=1.0a1,<1.0a2",
        # Pre-release ranges with room between
        ">1.0a1,<1.0a2",
        ">=1.0a1,<1.0b1",
        ">=1.0b1,<1.0rc1",
        # Post-release ranges
        ">1.0.post0,<1.0.post2",
        ">1.0.post0,<1.0.post3",
        # Dev range within a release
        ">=1.0a1.dev0,<1.0a1",
        # Epoch
        ">=1!1.0,<1!2.0",
        ">1!1.0,<1!3.0",
        # Wildcards that don't exhaust range
        ">=1.0,<3.0,!=2.*",
        # Real-world
        ">=3.8,!=3.9.*,!=3.10.0,!=3.10.1,~=3.10.2,<3.14",
        # Boundary checks
        "<1.0.dev1",
        ">1!1.0",
        "<1!2.0",
        ">1.0,<3.0",
        ">1.0,>2.0",
        "<2.0,<3.0",
        ">1.0.post0",
        ">1.0.post1,<2.0",
        # Local versions (spec with local + spec without local that strips local)
        "==1.0+local1,>=1.0",
        "!=1.0+local1,>=1.0",
        "==1.0+local1,!=1.0+local2",
        "==1.0+local1,==1.0",
        "==1.0+local1,<=1.0",
        "==1.0+local,>=1.0,<=1.0",
        "==1.0.post1+local,<=1.0.post1",
        # Various multi-spec
        ">1.0,!=0.5",
        ">=1.0,<2.0rc1",
        ">=0.5,!=1.0.*",
        "~=1.0,!=1.3",
        ">=1!0.0,<1!1.0",
        # === (arbitrary string equality)
        "===foobar",
        "===1.0",
        "===1.0a1",
        # === with unnormalized version string (PR #1124)
        "===1.01",
        # === mixed with standard operators
        "===1.0,==1.0",
        "===1.0,>=1.0",
        "===1.0,>=0.5",
        "===1.0,!=2.0",
        "===1.0.0,>=1.0",
        "===1.01,>=1.0",
        # === with unnormalized version that parses to a matching version
        "===1.01,==1.1",
        # === case-insensitive identity
        "===FOOBAR,===foobar",
        "===FooBar,===FOOBAR",
        # Final version sits below its own post-releases
        ">=1.0,<1.0.post0",
        ">=1.0,<1.0.post1",
        # =1.0.dev0,<1.0.post1,!=1.0,!=1.0.post0",
        # === with normalization variants
        "===v1.0,>=1.0",
        "===1.0-1,>=1.0",
        # Zero-padding equivalence
        "==1.0,==1.0.0",
        # Compatible release with post suffix
        "~=1.0.post1,>=1.0",
        # Range below post dev
        ">=1.0,<1.0.post0.dev1",
        # Post of alpha satisfies (1.0a1.post0 exists)
        ">=1.0a1,<1.0a2,!=1.0a1",
        # Alpha-to-beta range has room (1.0a2.dev0, etc.)
        ">1.0a1,<1.0b1",
        # Overlapping compatible releases
        "~=1.0,~=1.1",
        "~=1.0,~=1.0.1",
        # Partial wildcard exclusion doesn't exhaust range
        ">=1.0,<2.0,!=1.0.*,!=1.1.*",
        # ~= with pre/dev lower bound still accepts the final release
        "~=1.0.dev0,<1.0.post0",
        "~=1.0a1,<1.0.post0",
    ]

    @pytest.mark.parametrize("spec_str", UNSATISFIABLE)
    def test_unsatisfiable(self, spec_str: str) -> None:
        """Unsatisfiable specs must be detected, and filter must return empty."""
        ss = SpecifierSet(spec_str)
        assert ss.is_unsatisfiable(), f"Expected unsatisfiable: {spec_str!r}"
        result = list(ss.filter(_SAMPLE_VERSIONS, prereleases=True))
        assert result == [], (
            f"is_unsatisfiable() but filter matched: "
            f"{[str(v) for v in result]} for {spec_str!r}"
        )

    @pytest.mark.parametrize("spec_str", SATISFIABLE)
    def test_satisfiable(self, spec_str: str) -> None:
        """Satisfiable specs must not be falsely reported, and filter must match."""
        ss = SpecifierSet(spec_str)
        assert not ss.is_unsatisfiable(), f"Expected satisfiable: {spec_str!r}"
        result = bool(next(iter(ss.filter(_SAMPLE_VERSIONS, prereleases=True)), None))
        assert result, f"Expected filter to match at least one version for {spec_str!r}"

    def test_result_is_cached(self) -> None:
        ss = SpecifierSet(">=2.0,<1.0")
        assert ss.is_unsatisfiable()
        assert ss._is_unsatisfiable is True
        assert ss.is_unsatisfiable()  # second call uses cache

    def test_cache_reset_on_prereleases_change(self) -> None:
        ss = SpecifierSet(">=1.0,<2.0")
        assert not ss.is_unsatisfiable()
        ss.prereleases = True
        assert ss._is_unsatisfiable is None

    UNSATISFIABLE_NO_PRE: typing.ClassVar[list[str]] = [
        # Only pre-releases in range
        ">=1.0.dev0,<1.0",
        ">=1.0a1,<1.0",
        ">=1.0rc1,<1.0",
        # Single pre-release pin
        "==1.0.dev0",
        "==1.0a1",
        "==1.0a1.post0",
        "==1.0.post0.dev0",
        "==0.dev0",
        # Ranges within one pre-release family
        ">=1.0a1,<1.0a2",
        ">=1.0b1,<1.0rc1",
        ">=1.0.dev0,<1.0.dev5",
        # Strict > on pre-release lower bound (BoundaryVersion path)
        ">1.0a1,<1.0a3",
        # != removes all non-pre-releases from range
        ">=1.0rc1,<=1.0,!=1.0",
        ">=1.0.dev0,<=1.0,!=1.0",
        ">=1.0.dev0,<=1.0.post0,!=1.0,!=1.0.post0",
        # Epoch pre-release
        "==1!1.0.dev0",
        ">=1!1.0a1,<1!1.0",
        # === with parseable pre-release string
        "===1.0a1",
        "===1.0.dev0",
        # Already unsatisfiable regardless of prereleases
        ">=2.0,<1.0",
    ]

    SATISFIABLE_NO_PRE: typing.ClassVar[list[str]] = [
        "",
        ">=1.0,<2.0",
        ">=1.0.dev0,<2.0",
        "==1.0",
        "==1.0.post0",
        ">=1.0.dev0,<1.0.post1",
        # Unbounded lower (nearest_non_prerelease(None) path)
        "<2.0",
        # Exact local pin: nearest == upper and upper inclusive
        "==1.0+local",
        # === with unparsable string (prereleases filter does not apply)
        "===foobar",
        # Compatible release from pre-release includes final release
        "~=1.0a1",
        "~=1.0.dev0",
        # != removes some but not all
        ">=1.0rc1,<=1.0.post0,!=1.0",
        # Inclusive upper at non-pre-release boundary
        ">=1.0rc1,<=1.0",
        ">=1.0.dev0,<=1.0",
    ]

    @pytest.mark.parametrize("spec_str", UNSATISFIABLE_NO_PRE)
    def test_unsatisfiable_prereleases_false(self, spec_str: str) -> None:
        """With prereleases=False, detected as unsatisfiable and
        filter returns nothing."""
        ss = SpecifierSet(spec_str, prereleases=False)
        assert ss.is_unsatisfiable(), f"Expected unsatisfiable: {spec_str!r}"
        result = list(ss.filter(_SAMPLE_VERSIONS))
        assert result == [], (
            f"is_unsatisfiable() but filter matched: "
            f"{[str(v) for v in result]} for {spec_str!r}"
        )

    @pytest.mark.parametrize("spec_str", SATISFIABLE_NO_PRE)
    def test_satisfiable_prereleases_false(self, spec_str: str) -> None:
        """With prereleases=False, not falsely reported and filter matches."""
        ss = SpecifierSet(spec_str, prereleases=False)
        assert not ss.is_unsatisfiable(), f"Expected satisfiable: {spec_str!r}"
        result = bool(next(iter(ss.filter(_SAMPLE_VERSIONS)), None))
        assert result, f"Expected filter to match at least one version for {spec_str!r}"

    def test_and_preserves_unsatisfiable(self) -> None:
        combined = SpecifierSet(">=2.0") & SpecifierSet("<1.0")
        assert combined.is_unsatisfiable()

    def test_and_satisfiable(self) -> None:
        combined = SpecifierSet(">=1.0") & SpecifierSet("<2.0")
        assert not combined.is_unsatisfiable()

    def test_and_reuses_interval_cache(self) -> None:
        """Specifier interval cache is reused when specs are shared via &."""
        s1 = SpecifierSet(">=1.0")
        s2 = SpecifierSet("<2.0")
        # Compute intervals on the original sets first.
        assert not s1.is_unsatisfiable()
        assert not s2.is_unsatisfiable()
        # __and__ reuses the same Specifier objects, so _to_ranges()
        # hits the cache on those Specifier instances.
        combined = s1 & s2
        assert not combined.is_unsatisfiable()

    def test_range_bounds_hashable_and_equal(self) -> None:
        """Range bounds are hashable and support equality."""
        a = Specifier(">1.0")._to_ranges()
        b = Specifier(">1.0")._to_ranges()
        for (al, au), (bl, bu) in zip(a, b):
            hash(al)
            hash(au)
            assert al == bl
            assert au == bu

    def test_range_bounds_repr(self) -> None:
        [(lower, upper)] = Specifier(">=1.0")._to_ranges()
        assert repr(lower) == "<_LowerBound [>"
        assert repr(upper) == "<_UpperBound None)>"

        [(lower2, upper2)] = Specifier(">1.0")._to_ranges()
        assert (
            repr(lower2)
            == "<_LowerBound (_BoundaryVersion(, AFTER_POSTS)>"
        )
        assert repr(upper2) == "<_UpperBound None)>"


@pytest.mark.parametrize(
    ("specifier", "spec_prereleases"),
    [
        (">=1.0", None),
        ("==2.1.*", None),
        ("!=2.2.*", None),
        ("~=2.0", None),
        (">=1.0.dev1", None),
        ("<1.0.post1", None),
        (">2.0.post1", None),
        ("<=5", None),
        (">=7.9a1", None),
        ("<1.0.dev1", None),
        ("===foobar", None),
        # With prereleases override
        (">=1.0", True),
        (">=1.0", False),
    ],
)
def test_pickle_specifier_roundtrip(
    specifier: str, spec_prereleases: bool | None
) -> None:
    # Make sure equality and str() work between a pickle/unpickle round trip.
    s = Specifier(specifier, prereleases=spec_prereleases)
    # Warm up caches before pickling to ensure they are excluded from state.
    _ = s.prereleases
    _ = s._to_ranges()
    loaded = pickle.loads(pickle.dumps(s))
    assert loaded == s
    assert str(loaded) == str(s)
    assert loaded.prereleases == s.prereleases


@pytest.mark.parametrize(
    ("specifiers", "ss_prereleases"),
    [
        (">=1.0,<2.0", None),
        ("~=1.0,!=1.1", None),
        (">=1.0.dev1,<2.0", None),
        ("", None),  # Empty
        (">=1.0,<2.0,!=1.5", None),
        # With prereleases override
        (">=1.0,<2.0", True),
        (">=1.0,<2.0", False),
    ],
)
def test_pickle_specifierset_roundtrip(
    specifiers: str, ss_prereleases: bool | None
) -> None:
    # Make sure equality and str() work between a pickle/unpickle round trip.
    ss = SpecifierSet(specifiers, prereleases=ss_prereleases)
    # Warm up caches before pickling to ensure they are excluded from state.
    _ = ss.prereleases
    _ = ss.is_unsatisfiable()
    list(ss.filter(["1.5"]))
    loaded = pickle.loads(pickle.dumps(ss))
    assert loaded == ss
    assert str(loaded) == str(ss)
    assert loaded.prereleases == ss.prereleases


def test_pickle_setstate_rejects_invalid_state() -> None:
    # Cover the TypeError branches in __setstate__ for invalid input.
    s = Specifier.__new__(Specifier)
    with pytest.raises(TypeError, match="Cannot restore Specifier"):
        s.__setstate__((1, 2, 3))  # Wrong tuple length
    with pytest.raises(TypeError, match="Cannot restore Specifier"):
        s.__setstate__(12345)  # Not a tuple or dict

    ss = SpecifierSet.__new__(SpecifierSet)
    with pytest.raises(TypeError, match="Cannot restore SpecifierSet"):
        ss.__setstate__((1, 2, 3))  # Wrong tuple length
    with pytest.raises(TypeError, match="Cannot restore SpecifierSet"):
        ss.__setstate__(12345)  # Not a tuple or dict


def test_pickle_specifier_setstate_rejects_malformed_legacy_state() -> None:
    # Verify validation catches malformed legacy slot-dict and dict formats.
    s = Specifier.__new__(Specifier)
    # Missing _spec key (legacy slot-dict format).
    with pytest.raises(TypeError, match="Cannot restore Specifier"):
        s.__setstate__((None, {"_prereleases": None}))
    # Missing _spec key (legacy dict format).
    with pytest.raises(TypeError, match="Cannot restore Specifier"):
        s.__setstate__({"_prereleases": None})
    # _spec is not a 2-tuple of strings.
    with pytest.raises(TypeError, match="Cannot restore Specifier"):
        s.__setstate__((("bad",), None))
    with pytest.raises(TypeError, match="Cannot restore Specifier"):
        s.__setstate__((None, {"_spec": 123}))
    # _prereleases is not bool|None.
    with pytest.raises(TypeError, match="Cannot restore Specifier"):
        s.__setstate__((("==", "1.0"), "yes"))


def test_pickle_specifierset_setstate_rejects_malformed_legacy_state() -> None:
    # Verify validation catches malformed legacy slot-dict and dict formats.
    ss = SpecifierSet.__new__(SpecifierSet)
    # _specs contains non-Specifier items (legacy slot-dict format).
    with pytest.raises(TypeError, match="Cannot restore SpecifierSet"):
        ss.__setstate__((None, {"_specs": {1, 2}, "_prereleases": None}))
    # _specs contains non-Specifier items (legacy dict format).
    with pytest.raises(TypeError, match="Cannot restore SpecifierSet"):
        ss.__setstate__({"_specs": {1, 2}, "_prereleases": None})


def test_pickle_specifierset_setstate_on_initialized_instance() -> None:
    # Cover the branch where hasattr(self, "_specs") is True in __setstate__.
    # This happens when __setstate__ is called on an already-initialized instance.
    ss = SpecifierSet(">=1.0")
    ss.__setstate__(((Specifier(">=2.0"),), None))
    assert ss == SpecifierSet(">=2.0")


def test_pickle_specifier_setstate_clears_cache() -> None:
    # Verify that __setstate__ resets all three cached slots to None,
    # regardless of what was cached before the call.
    s = Specifier("==1.*")
    # Warm up every cache slot.
    _ = s.prereleases  # populates _spec_version
    _ = s._get_wildcard_split("1.*")  # populates _wildcard_split
    _ = s._to_ranges()  # populates _ranges
    assert s._spec_version is not None
    assert s._wildcard_split is not None
    assert s._ranges is not None

    s.__setstate__((("==", "1.*"), None))

    assert s._spec_version is None
    assert s._wildcard_split is None
    assert s._ranges is None


def test_pickle_specifierset_setstate_clears_cache() -> None:
    # Verify that __setstate__ resets all cached slots to None,
    # regardless of what was cached before the call.
    ss = SpecifierSet(">=1.0,<2.0")
    # Warm up every cache slot.
    ss.is_unsatisfiable()  # populates _is_unsatisfiable
    list(ss.filter(["1.5"]))  # populates _resolved_ops
    assert ss._is_unsatisfiable is not None
    assert ss._resolved_ops is not None

    ss.__setstate__(((Specifier(">=3.0"), Specifier("<4.0")), None))

    assert ss._is_unsatisfiable is None
    assert ss._resolved_ops is None


# Pickle bytes generated with packaging==25.0, Python 3.13.13, pickle protocol 2.
# Format: plain __dict__ (no __slots__). _spec is stored as a (operator, version) tuple
# and _prereleases as a separate key.
_PACKAGING_25_0_PICKLE_GE_3_10 = (
    b"\x80\x02cpackaging.specifiers\nSpecifier\nq\x00)\x81q\x01}q\x02"
    b"(X\x05\x00\x00\x00_specq\x03X\x02\x00\x00\x00>=q\x04X\x04\x00\x00"
    b"\x003.10q\x05\x86q\x06X\x0c\x00\x00\x00_prereleasesq\x07Nub."
)

_PACKAGING_25_0_PICKLE_SS_GE_3_10_LT_4_0 = (
    b"\x80\x02cpackaging.specifiers\nSpecifierSet\nq\x00)\x81q\x01}q\x02"
    b"(X\x06\x00\x00\x00_specsq\x03c__builtin__\nfrozenset\nq\x04]q\x05"
    b"(cpackaging.specifiers\nSpecifier\nq\x06)\x81q\x07}q\x08(X\x05\x00"
    b"\x00\x00_specq\tX\x02\x00\x00\x00>=q\nX\x04\x00\x00\x003.10q\x0b"
    b"\x86q\x0cX\x0c\x00\x00\x00_prereleasesq\rNubh\x06)\x81q\x0e}q\x0f"
    b"(h\tX\x01\x00\x00\x00 None:
    # Verify that Specifier pickles created with packaging <= 25.x (plain __dict__)
    # can be loaded and produce correct Specifier objects.
    s = pickle.loads(_PACKAGING_25_0_PICKLE_GE_3_10)
    assert isinstance(s, Specifier)
    assert str(s) == ">=3.10"
    assert s == Specifier(">=3.10")
    assert s.operator == ">="
    assert s.version == "3.10"
    assert s.prereleases == Specifier(">=3.10").prereleases


def test_pickle_specifierset_25_0_format_loads() -> None:
    # Verify that SpecifierSet pickles created with packaging <= 25.x (plain __dict__,
    # _specs stored as a frozenset) can be loaded and produce correct objects.
    ss = pickle.loads(_PACKAGING_25_0_PICKLE_SS_GE_3_10_LT_4_0)
    assert isinstance(ss, SpecifierSet)
    assert ss == SpecifierSet(">=3.10,<4.0")
    assert "3.10" in ss
    assert "3.12" in ss
    assert "4.0" not in ss
    assert ss.prereleases is None


# Pickle bytes generated with packaging==26.0, Python 3.13.13, pickle protocol 2.
# Format: __slots__ (no __dict__), state is (None, {slot: value}). Includes
# _spec_version slot (a cached Version object, may be present or None).
_PACKAGING_26_0_PICKLE_GE_3_10 = (
    b"\x80\x02cpackaging.specifiers\nSpecifier\nq\x00)\x81q\x01N}q\x02"
    b"(X\x0c\x00\x00\x00_prereleasesq\x03NX\x05\x00\x00\x00_specq\x04"
    b"X\x02\x00\x00\x00>=q\x05X\x04\x00\x00\x003.10q\x06\x86q\x07X\r"
    b"\x00\x00\x00_spec_versionq\x08Nu\x86q\tb."
)

_PACKAGING_26_0_PICKLE_SS_GE_3_10_LT_4_0 = (
    b"\x80\x02cpackaging.specifiers\nSpecifierSet\nq\x00)\x81q\x01N}q\x02"
    b"(X\x0c\x00\x00\x00_prereleasesq\x03NX\x06\x00\x00\x00_specsq\x04"
    b"c__builtin__\nfrozenset\nq\x05]q\x06(cpackaging.specifiers\nSpecifier"
    b"\nq\x07)\x81q\x08N}q\t(h\x03NX\x05\x00\x00\x00_specq\nX\x02\x00"
    b"\x00\x00>=q\x0bX\x04\x00\x00\x003.10q\x0c\x86q\rX\r\x00\x00\x00"
    b"_spec_versionq\x0eh\x0ccpackaging.version\nVersion\nq\x0f)\x81q\x10"
    b"N}q\x11(X\x04\x00\x00\x00_devq\x12NX\x06\x00\x00\x00_epochq\x13K"
    b"\x00X\n\x00\x00\x00_key_cacheq\x14NX\x06\x00\x00\x00_localq\x15N"
    b"X\x05\x00\x00\x00_postq\x16NX\x04\x00\x00\x00_preq\x17NX\x08\x00"
    b"\x00\x00_releaseq\x18K\x03K\n\x86q\x19u\x86q\x1ab\x86q\x1bu\x86"
    b"q\x1cbh\x07)\x81q\x1dN}q\x1e(h\x03Nh\nX\x01\x00\x00\x00 None:
    # Verify that Specifier pickles created with packaging 26.0 (__slots__,
    # state is (None, {slot_dict})) can be loaded and produce correct objects.
    s = pickle.loads(_PACKAGING_26_0_PICKLE_GE_3_10)
    assert isinstance(s, Specifier)
    assert str(s) == ">=3.10"
    assert s == Specifier(">=3.10")
    assert s.operator == ">="
    assert s.version == "3.10"
    assert s.prereleases == Specifier(">=3.10").prereleases


def test_pickle_specifierset_26_0_slots_format_loads() -> None:
    # Verify that SpecifierSet pickles created with packaging 26.0 (__slots__,
    # state is (None, {slot_dict}), _specs stored as frozenset) can be loaded.
    ss = pickle.loads(_PACKAGING_26_0_PICKLE_SS_GE_3_10_LT_4_0)
    assert isinstance(ss, SpecifierSet)
    assert ss == SpecifierSet(">=3.10,<4.0")
    assert "3.10" in ss
    assert "3.12" in ss
    assert "4.0" not in ss
    assert ss.prereleases is None


# Pickle bytes generated with packaging==26.1, Python 3.13.13, pickle protocol 2.
# Format: __slots__ (no __dict__), state is (None, {slot: value}). Compared to 26.0,
# the slot dict now includes _ranges and _wildcard_split cache fields, and SpecifierSet
# adds _canonicalized, _has_arbitrary, _is_unsatisfiable, and _resolved_ops.
_PACKAGING_26_1_PICKLE_GE_3_10 = (
    b"\x80\x02cpackaging.specifiers\nSpecifier\nq\x00)\x81q\x01N}q\x02"
    b"(X\x0c\x00\x00\x00_prereleasesq\x03NX\x07\x00\x00\x00_rangesq\x04"
    b"NX\x05\x00\x00\x00_specq\x05X\x02\x00\x00\x00>=q\x06X\x04\x00\x00"
    b"\x003.10q\x07\x86q\x08X\r\x00\x00\x00_spec_versionq\tNX\x0f\x00"
    b"\x00\x00_wildcard_splitq\nNu\x86q\x0bb."
)

_PACKAGING_26_1_PICKLE_SS_GE_3_10_LT_4_0 = (
    b"\x80\x02cpackaging.specifiers\nSpecifierSet\nq\x00)\x81q\x01N}q\x02"
    b"(X\x0e\x00\x00\x00_canonicalizedq\x03\x89X\x0e\x00\x00\x00_has_arb"
    b"itraryq\x04\x89X\x11\x00\x00\x00_is_unsatisfiableq\x05NX\x0c\x00"
    b"\x00\x00_prereleasesq\x06NX\r\x00\x00\x00_resolved_opsq\x07NX\x06"
    b"\x00\x00\x00_specsq\x08cpackaging.specifiers\nSpecifier\nq\t)\x81q"
    b"\nN}q\x0b(h\x06NX\x07\x00\x00\x00_rangesq\x0cNX\x05\x00\x00\x00"
    b"_specq\rX\x02\x00\x00\x00>=q\x0eX\x04\x00\x00\x003.10q\x0f\x86q"
    b"\x10X\r\x00\x00\x00_spec_versionq\x11NX\x0f\x00\x00\x00_wildcard_"
    b"splitq\x12Nu\x86q\x13bh\t)\x81q\x14N}q\x15(h\x06Nh\x0cNh\rX\x01"
    b"\x00\x00\x00 None:
    # Verify that Specifier pickles created with packaging 26.1 (__slots__,
    # state includes _ranges and _wildcard_split) can be loaded correctly.
    s = pickle.loads(_PACKAGING_26_1_PICKLE_GE_3_10)
    assert isinstance(s, Specifier)
    assert str(s) == ">=3.10"
    assert s == Specifier(">=3.10")
    assert s.operator == ">="
    assert s.version == "3.10"
    assert s.prereleases == Specifier(">=3.10").prereleases


def test_pickle_specifierset_26_1_slots_format_loads() -> None:
    # Verify that SpecifierSet pickles created with packaging 26.1 (__slots__,
    # state includes _canonicalized, _has_arbitrary, _is_unsatisfiable,
    # _resolved_ops, and _specs as a tuple) can be loaded correctly.
    ss = pickle.loads(_PACKAGING_26_1_PICKLE_SS_GE_3_10_LT_4_0)
    assert isinstance(ss, SpecifierSet)
    assert ss == SpecifierSet(">=3.10,<4.0")
    assert "3.10" in ss
    assert "3.12" in ss
    assert "4.0" not in ss
    assert ss.prereleases is None


# Pickle bytes generated with packaging==26.2.dev0 (the 26.2 clean-tuple format),
# Python 3.13.13, pickle protocol 2.
# Format: Specifier state is ((operator, version), prereleases). SpecifierSet state
# is (tuple[Specifier, ...], prereleases). No slot dicts or __dict__ wrappers.
_PACKAGING_26_2_PICKLE_GE_3_10 = (
    b"\x80\x02cpackaging.specifiers\nSpecifier\nq\x00)\x81q\x01X\x02\x00"
    b"\x00\x00>=q\x02X\x04\x00\x00\x003.10q\x03\x86q\x04N\x86q\x05b."
)

_PACKAGING_26_2_PICKLE_SS_GE_3_10_LT_4_0 = (
    b"\x80\x02cpackaging.specifiers\nSpecifierSet\nq\x00)\x81q\x01cpackag"
    b"ing.specifiers\nSpecifier\nq\x02)\x81q\x03X\x02\x00\x00\x00>=q\x04"
    b"X\x04\x00\x00\x003.10q\x05\x86q\x06N\x86q\x07bh\x02)\x81q\x08X\x01"
    b"\x00\x00\x00 None:
    # Verify that Specifier pickles created with packaging 26.2+ (compact 2-tuple
    # state: ((operator, version), prereleases)) load correctly.
    s = pickle.loads(_PACKAGING_26_2_PICKLE_GE_3_10)
    assert isinstance(s, Specifier)
    assert str(s) == ">=3.10"
    assert s == Specifier(">=3.10")
    assert s.operator == ">="
    assert s.version == "3.10"
    assert s.prereleases == Specifier(">=3.10").prereleases


def test_pickle_specifierset_26_2_tuple_format_loads() -> None:
    # Verify that SpecifierSet pickles created with packaging 26.2+ (compact 2-tuple
    # state: (tuple[Specifier, ...], prereleases)) load correctly.
    ss = pickle.loads(_PACKAGING_26_2_PICKLE_SS_GE_3_10_LT_4_0)
    assert isinstance(ss, SpecifierSet)
    assert ss == SpecifierSet(">=3.10,<4.0")
    assert "3.10" in ss
    assert "3.12" in ss
    assert "4.0" not in ss
    assert ss.prereleases is None
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1123567
packaging-26.2/tests/test_tags.py0000644000000000000000000023545415172742311014046 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 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


class AndroidVer(typing.NamedTuple):
    release: str
    api_level: int
    manufacturer: str
    model: str
    device: str
    is_emulator: bool


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

    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

    def test_unsorted_interpreter_parses_by_default(self) -> None:
        # Unsorted tags should parse fine without validate_order
        result = tags.parse_tag("py3.py2-none-any")
        assert tags.Tag("py3", "none", "any") in result
        assert tags.Tag("py2", "none", "any") in result

    def test_unsorted_interpreter_raises_with_validate(self) -> None:
        with pytest.raises(ValueError, match="not in sorted order"):
            tags.parse_tag("py3.py2-none-any", validate_order=True)

    def test_unsorted_platform_parses_by_default(self) -> None:
        result = tags.parse_tag(
            "cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64"
        )
        assert len(result) == 2

    def test_unsorted_platform_raises_with_validate(self) -> None:
        with pytest.raises(ValueError, match="not in sorted order"):
            tags.parse_tag(
                "cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64",
                validate_order=True,
            )

    def test_sorted_multi_interpreter_valid(self) -> None:
        # py2 < py3 alphabetically — should not raise even with validation
        result = tags.parse_tag("py2.py3-none-any", validate_order=True)
        assert tags.Tag("py2", "none", "any") in result
        assert tags.Tag("py3", "none", "any") in result


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", "abi3t", "plat1"),
            tags.Tag("cp313", "abi3t", "plat2"),
            tags.Tag("cp313", "none", "plat1"),
            tags.Tag("cp313", "none", "plat2"),
            tags.Tag("cp312", "abi3t", "plat1"),
            tags.Tag("cp312", "abi3t", "plat2"),
            tags.Tag("cp311", "abi3t", "plat1"),
            tags.Tag("cp311", "abi3t", "plat2"),
            tags.Tag("cp310", "abi3t", "plat1"),
            tags.Tag("cp310", "abi3t", "plat2"),
            tags.Tag("cp39", "abi3t", "plat1"),
            tags.Tag("cp39", "abi3t", "plat2"),
            tags.Tag("cp38", "abi3t", "plat1"),
            tags.Tag("cp38", "abi3t", "plat2"),
            tags.Tag("cp37", "abi3t", "plat1"),
            tags.Tag("cp37", "abi3t", "plat2"),
            tags.Tag("cp36", "abi3t", "plat1"),
            tags.Tag("cp36", "abi3t", "plat2"),
            tags.Tag("cp35", "abi3t", "plat1"),
            tags.Tag("cp35", "abi3t", "plat2"),
            tags.Tag("cp34", "abi3t", "plat1"),
            tags.Tag("cp34", "abi3t", "plat2"),
            tags.Tag("cp33", "abi3t", "plat1"),
            tags.Tag("cp33", "abi3t", "plat2"),
            tags.Tag("cp32", "abi3t", "plat1"),
            tags.Tag("cp32", "abi3t", "plat2"),
        ]

        result = list(tags.cpython_tags((3, 15), ["cp315t"], ["platform"]))
        assert result == [
            tags.Tag("cp315", "cp315t", "platform"),
            tags.Tag("cp315", "abi3t", "platform"),
            tags.Tag("cp315", "none", "platform"),
            tags.Tag("cp314", "abi3t", "platform"),
            tags.Tag("cp313", "abi3t", "platform"),
            tags.Tag("cp312", "abi3t", "platform"),
            tags.Tag("cp311", "abi3t", "platform"),
            tags.Tag("cp310", "abi3t", "platform"),
            tags.Tag("cp39", "abi3t", "platform"),
            tags.Tag("cp38", "abi3t", "platform"),
            tags.Tag("cp37", "abi3t", "platform"),
            tags.Tag("cp36", "abi3t", "platform"),
            tags.Tag("cp35", "abi3t", "platform"),
            tags.Tag("cp34", "abi3t", "platform"),
            tags.Tag("cp33", "abi3t", "platform"),
            tags.Tag("cp32", "abi3t", "platform"),
        ]

        result = list(tags.cpython_tags((3, 16), ["cp316t"], ["platform"]))
        assert result == [
            tags.Tag("cp316", "cp316t", "platform"),
            tags.Tag("cp316", "abi3t", "platform"),
            tags.Tag("cp316", "none", "platform"),
            tags.Tag("cp315", "abi3t", "platform"),
            tags.Tag("cp314", "abi3t", "platform"),
            tags.Tag("cp313", "abi3t", "platform"),
            tags.Tag("cp312", "abi3t", "platform"),
            tags.Tag("cp311", "abi3t", "platform"),
            tags.Tag("cp310", "abi3t", "platform"),
            tags.Tag("cp39", "abi3t", "platform"),
            tags.Tag("cp38", "abi3t", "platform"),
            tags.Tag("cp37", "abi3t", "platform"),
            tags.Tag("cp36", "abi3t", "platform"),
            tags.Tag("cp35", "abi3t", "platform"),
            tags.Tag("cp34", "abi3t", "platform"),
            tags.Tag("cp33", "abi3t", "platform"),
            tags.Tag("cp32", "abi3t", "platform"),
        ]

        result = list(tags.cpython_tags((3, 16), ["cp316"], ["platform"]))
        assert result == [
            tags.Tag("cp316", "cp316", "platform"),
            tags.Tag("cp316", "abi3", "platform"),
            tags.Tag("cp316", "none", "platform"),
            tags.Tag("cp315", "abi3", "platform"),
            tags.Tag("cp314", "abi3", "platform"),
            tags.Tag("cp313", "abi3", "platform"),
            tags.Tag("cp312", "abi3", "platform"),
            tags.Tag("cp311", "abi3", "platform"),
            tags.Tag("cp310", "abi3", "platform"),
            tags.Tag("cp39", "abi3", "platform"),
            tags.Tag("cp38", "abi3", "platform"),
            tags.Tag("cp37", "abi3", "platform"),
            tags.Tag("cp36", "abi3", "platform"),
            tags.Tag("cp35", "abi3", "platform"),
            tags.Tag("cp34", "abi3", "platform"),
            tags.Tag("cp33", "abi3", "platform"),
            tags.Tag("cp32", "abi3", "platform"),
        ]

    def test_no_abi3t_in_non_threaded_interpreter(self) -> None:
        result = list(tags.cpython_tags((3, 16), ["cp316"], ["platform"]))
        assert all(t.abi in ("cp316", "none", "abi3") for t in result)

    def test_no_abi3_in_threaded_interpreter(self) -> None:
        result = list(tags.cpython_tags((3, 16), ["cp316t"], ["platform"]))
        assert all(t.abi in ("cp316t", "none", "abi3t") for t in result)

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

    def test_emscripten(
        self,
        mock_interpreter_name: Callable[[str], bool],
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        expected_interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
        if mock_interpreter_name("CPython"):
            monkeypatch.setattr(
                tags, "_cpython_abis", lambda _1, _2: [expected_interpreter]
            )
        config = {
            "Py_GIL_DISABLED": 0,
        }

        monkeypatch.setattr(sysconfig, "get_config_var", config.get)
        monkeypatch.setattr(platform, "system", lambda: "Emscripten")
        monkeypatch.setattr(
            sysconfig, "get_platform", lambda: "emscripten-5.0.3-wasm32"
        )
        assert list(tags.platform_tags()) == ["emscripten_5_0_3_wasm32"]
        result = list(tags.sys_tags())
        assert result[0] == tags.Tag(
            expected_interpreter, expected_interpreter, "emscripten_5_0_3_wasm32"
        )

    def test_pyemscripten(
        self,
        mock_interpreter_name: Callable[[str], bool],
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        expected_interpreter = "cp" + tags._version_nodot(sys.version_info[:2])
        config = {
            "PYEMSCRIPTEN_PLATFORM_VERSION": "2026_0",
        }

        monkeypatch.setattr(sysconfig, "get_config_var", config.get)
        if mock_interpreter_name("CPython"):
            monkeypatch.setattr(
                tags, "_cpython_abis", lambda _1, _2: [expected_interpreter]
            )
        monkeypatch.setattr(platform, "system", lambda: "Emscripten")
        monkeypatch.setattr(
            sysconfig, "get_platform", lambda: "emscripten-5.0.3-wasm32"
        )
        assert list(tags.platform_tags()) == [
            "pyemscripten_2026_0_wasm32",
            "emscripten_5_0_3_wasm32",
        ]
        result = list(tags.sys_tags())
        assert result[0] == tags.Tag(
            expected_interpreter, expected_interpreter, "pyemscripten_2026_0_wasm32"
        )


class TestBitness:
    @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)
        assert expected == tags._compute_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


@pytest.mark.parametrize(
    ("interpreter", "abi", "platform"),
    [
        ("py3", "none", "any"),
        ("cp39", "cp39", "linux_x86_64"),
        ("cp312", "cp312", "win_amd64"),
        ("pp310", "pypy310_pp73", "manylinux_2_17_x86_64"),
    ],
)
def test_pickle_tag_roundtrip(interpreter: str, abi: str, platform: str) -> None:
    # Make sure equality, str(), and hash() work between a pickle/unpickle round trip.
    t = tags.Tag(interpreter, abi, platform)
    loaded = pickle.loads(pickle.dumps(t))
    assert loaded == t
    assert str(loaded) == str(t)
    assert hash(loaded) == hash(t)


def test_pickle_tag_setstate_rejects_invalid_state() -> None:
    # Cover the TypeError branches in __setstate__ for invalid input.
    t = tags.Tag.__new__(tags.Tag)
    with pytest.raises(TypeError, match="Cannot restore Tag"):
        t.__setstate__(12345)
    with pytest.raises(TypeError, match="Cannot restore Tag"):
        t.__setstate__((1, 2, 3))  # Wrong types, not all strings
    with pytest.raises(TypeError, match="Cannot restore Tag"):
        t.__setstate__((None, {"_interpreter": "cp39", "_abi": "cp39"}))
    with pytest.raises(TypeError, match="Cannot restore Tag"):
        t.__setstate__(
            (None, {"_interpreter": 123, "_abi": "cp39", "_platform": "linux_x86_64"})
        )
    with pytest.raises(TypeError, match="Cannot restore Tag"):
        t.__setstate__((1, 2))  # len==2 but second element not a dict
    with pytest.raises(TypeError, match="Cannot restore Tag"):
        t.__setstate__((1, 2, 3, 4))  # tuple length not 2 or 3


# Pickle bytes generated with packaging==26.1, Python 3.13.1, pickle protocol 2.
# Format: __slots__ (no __getstate__), state is (None, {slot: value}). The
# _hash slot contains a pre-computed integer that must be discarded on load.
_PACKAGING_26_1_PICKLE_TAG_CP39 = (
    b"\x80\x02cpackaging.tags\nTag\nq\x00)\x81q\x01N}q\x02(X\x04\x00\x00"
    b"\x00_abiq\x03X\x04\x00\x00\x00cp39q\x04X\x05\x00\x00\x00_hashq\x05"
    b"\x8a\x08)\xb1\xe8\x9d\x90\xf8tFX\x0c\x00\x00\x00_interpreterq\x06X"
    b"\x04\x00\x00\x00cp39q\x07X\t\x00\x00\x00_platformq\x08X\x0c\x00\x00"
    b"\x00linux_x86_64q\tu\x86q\nb."
)


# Pickle bytes generated with packaging==26.0, Python 3.13.1, pickle protocol 2.
# Format: __slots__ (no __getstate__), state is (None, {slot: value}).
_PACKAGING_26_0_PICKLE_TAG_CP39 = (
    b"\x80\x02cpackaging.tags\nTag\nq\x00)\x81q\x01N}q\x02(X\x04\x00\x00"
    b"\x00_abiq\x03X\x04\x00\x00\x00cp39q\x04X\x05\x00\x00\x00_hashq\x05"
    b"\x8a\x08\xc1\xdb\xa0\xe5]7z\x87X\x0c\x00\x00\x00_interpreterq\x06X"
    b"\x04\x00\x00\x00cp39q\x07X\t\x00\x00\x00_platformq\x08X\x0c\x00\x00"
    b"\x00linux_x86_64q\tu\x86q\nb."
)


# Pickle bytes generated with packaging==25.0, Python 3.13.1, pickle protocol 2.
# Format: plain __dict__ (no __slots__).
_PACKAGING_25_0_PICKLE_TAG_CP39 = (
    b"\x80\x02cpackaging.tags\nTag\nq\x00)\x81q\x01N}q\x02(X\x04\x00\x00\x00"
    b"_abiq\x03X\x04\x00\x00\x00cp39q\x04X\x05\x00\x00\x00_hashq\x05\x8a\x08"
    b"\xea\xa5X\x92\xa5\xc9\x11\x0cX\x0c\x00\x00\x00_interpreterq\x06X\x04"
    b"\x00\x00\x00cp39q\x07X\t\x00\x00\x00_platformq\x08X\x0c\x00\x00\x00"
    b"linux_x86_64q\tu\x86q\nb."
)


def test_pickle_tag_old_format_loads() -> None:
    # Verify that Tag pickles created with packaging <= 26.1 (__slots__,
    # no __getstate__) can be loaded and produce correct Tag objects.
    t = pickle.loads(_PACKAGING_26_1_PICKLE_TAG_CP39)
    assert isinstance(t, tags.Tag)
    assert str(t) == "cp39-cp39-linux_x86_64"
    assert t == tags.Tag("cp39", "cp39", "linux_x86_64")
    assert t.interpreter == "cp39"
    assert t.abi == "cp39"
    assert t.platform == "linux_x86_64"
    assert t._hash == hash(("cp39", "cp39", "linux_x86_64"))


def test_pickle_tag_26_0_format_loads() -> None:
    # Verify that Tag pickles created with packaging 26.0 (__slots__,
    # no __getstate__) can be loaded and produce correct Tag objects.
    t = pickle.loads(_PACKAGING_26_0_PICKLE_TAG_CP39)
    assert isinstance(t, tags.Tag)
    assert str(t) == "cp39-cp39-linux_x86_64"
    assert t == tags.Tag("cp39", "cp39", "linux_x86_64")
    assert t._hash == hash(("cp39", "cp39", "linux_x86_64"))


def test_pickle_tag_25_0_format_loads() -> None:
    # Verify that Tag pickles created with packaging 25.0 (plain __dict__)
    # can be loaded and produce correct Tag objects.
    t = pickle.loads(_PACKAGING_25_0_PICKLE_TAG_CP39)
    assert isinstance(t, tags.Tag)
    assert str(t) == "cp39-cp39-linux_x86_64"
    assert t == tags.Tag("cp39", "cp39", "linux_x86_64")
    assert t._hash == hash(("cp39", "cp39", "linux_x86_64"))


@pytest.mark.parametrize(
    ("supported", "things", "expected"),
    [
        (["t1", "t2"], ["t1", "t2"], ["t1", "t2"]),
        (["t1", "t2"], ["t3", "t4"], []),
        (["t1", "t2"], ["t2", "t1"], ["t1", "t2"]),
        (["t1", "t2", "t1"], ["t2", "t1"], ["t1", "t2"]),
        (["t1", "t3"], ["t2", "t1"], ["t1"]),
        (["t1", "t3"], ["t2.t3", "t1"], ["t1", "t2.t3"]),
        (["t1"], ["t2", "t1"], ["t1"]),
    ],
)
def test_create_compatible_tags_selector(
    supported: list[str], things: list[str], expected: list[str]
) -> None:
    def t_to_tag(t: str) -> tags.Tag:
        return tags.Tag("py3", "none", t)

    def t_to_tags(t: str) -> frozenset[tags.Tag]:
        return tags.parse_tag(f"py3-none-{t}")

    selector = tags.create_compatible_tags_selector([t_to_tag(t) for t in supported])
    assert list(selector([(t, t_to_tags(t)) for t in things])) == expected
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1777059017.1123567
packaging-26.2/tests/test_utils.py0000644000000000000000000001506215172742311014237 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")},
        ),
        (
            "pyvirtualcam-0.13.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl",
            "pyvirtualcam",
            Version("0.13.0"),
            (),
            {
                Tag("cp310", "cp310", "manylinux2014_x86_64"),
                Tag("cp310", "cp310", "manylinux_2_17_x86_64"),
            },
        ),
        (
            "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",
    [
        "pyvirtualcam-0.13.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
        "foo-1.0-py3.py2-none-any.whl",
    ],
)
def test_parse_wheel_unsorted_tags_valid_by_default(filename: str) -> None:
    # Unsorted compressed tags should parse fine without validate_order
    parse_wheel_filename(filename)


@pytest.mark.parametrize(
    "filename",
    [
        "pyvirtualcam-0.13.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
        "foo-1.0-py3.py2-none-any.whl",
    ],
)
def test_parse_wheel_unsorted_tags_invalid_with_validate(filename: str) -> None:
    with pytest.raises(InvalidWheelFilename):
        parse_wheel_filename(filename, validate_order=True)


@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=1777059017.1123567
packaging-26.2/tests/test_version.py0000644000000000000000000014000215172742311014555 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 pickle
import sys
import typing

import pretend
import pytest

from packaging._structures import Infinity, NegativeInfinity
from packaging.version import (
    InvalidVersion,
    Version,
    _BaseVersion,
    _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.dev0",
    "1.0.dev456",
    "1.0.dev456+local",
    "1.0a0",
    "1.0a0.post0.dev0",
    "1.0a0.post0",
    "1.0a1.dev1",
    "1.0a1.dev1+local",
    "1.0a1",
    "1.0a1+local",
    "1.0b0",
    "1.0b1.dev456",
    "1.0b2",
    "1.0b2.post345.dev456",
    "1.0b2.post345",
    "1.0b2-346",
    "1.0rc0",
    "1.0rc1.dev1",
    "1.0c1",
    "1.0rc2",
    "1.0",
    "1.0.post0.dev0",
    "1.0.post0",
    "1.0.post456.dev34",
    "1.0.post456",
    "1.0.post456+local",
    "1.0.1.dev1",
    "1.0.1a1",
    "1.0.1",
    "1.0.1+local",
    "1.0.1.post1",
    "1.1.dev1",
    "1.2+a",
    "1.2+abc",
    "1.2+abcdef",
    "1.2+def",
    "1.2+0",
    "1.2+1",
    "1.2+1.abc",
    "1.2+1.1",
    "1.2+1.1.0",
    "1.2+2",
    "1.2+123",
    "1.2+123456",
    "1.2.r32+123456",
    "1.2.rev33+123456",
    # Explicit epoch of 1
    "1!1.0.dev0",
    "1!1.0.dev456",
    "1!1.0.dev456+local",
    "1!1.0a0",
    "1!1.0a0.post0.dev0",
    "1!1.0a0.post0",
    "1!1.0a1.dev1",
    "1!1.0a1.dev1+local",
    "1!1.0a1",
    "1!1.0a1+local",
    "1!1.0b0",
    "1!1.0b1.dev456",
    "1!1.0b2",
    "1!1.0b2.post345.dev456",
    "1!1.0b2.post345",
    "1!1.0b2-346",
    "1!1.0rc0",
    "1!1.0rc1.dev1",
    "1!1.0c1",
    "1!1.0rc2",
    "1!1.0",
    "1!1.0.post0.dev0",
    "1!1.0.post0",
    "1!1.0.post456.dev34",
    "1!1.0.post456",
    "1!1.0.post456+local",
    "1!1.0.1.dev1",
    "1!1.0.1a1",
    "1!1.0.1",
    "1!1.0.1+local",
    "1!1.0.1.post1",
    "1!1.1.dev1",
    "1!1.2+a",
    "1!1.2+abc",
    "1!1.2+abcdef",
    "1!1.2+def",
    "1!1.2+0",
    "1!1.2+1",
    "1!1.2+1.abc",
    "1!1.2+1.1",
    "1!1.2+1.1.0",
    "1!1.2+2",
    "1!1.2+123",
    "1!1.2+123456",
    "1!1.2.r32+123456",
    "1!1.2.rev33+123456",
]


# Simple _BaseVersion subclass for testing comparison with non-Version types
class SimpleVersion(_BaseVersion):
    """A simple _BaseVersion subclass for testing cross-type comparisons."""

    def __init__(self, key: typing.Any) -> None:  # noqa: ANN401
        # If key is a string, parse it as a version to create a compatible key
        if isinstance(key, str):
            parsed = Version(key)
            self._key_tuple = parsed._key
        else:
            self._key_tuple = key

    @property
    def _key(self) -> typing.Any:  # noqa: ANN401
        return self._key_tuple

    @_key.setter
    def _key(self, value: typing.Any) -> None:  # noqa: ANN401
        self._key_tuple = value


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",
            # Spaces in versions are also invalid
            "1. 0",
            "1 .0",
            "1. 0a1",
            "1 .0a1",
            "1.0 a1",
            "1.0a 1",
            # Versions do need to be standard numbers
            "٠١٢.٣٤٥.٦٧٨٩",
            # Invalid versions that trigger the fast path (digits/dots only)
            ".",
            "..",
            "1..0",
            "1.0.",
            ".1.0",
            "1..2.3",
            # Local version which includes a non-ASCII letter that matches
            # regex '[a-z]' when re.IGNORECASE is in force and re.ASCII is not
            "1.0+\u0130",
        ],
    )
    def test_invalid_versions(self, version: str) -> None:
        with pytest.raises(InvalidVersion):
            Version(version)

    @pytest.mark.skipif(
        not hasattr(sys, "get_int_max_str_digits"),
        reason="requires int max str digits limit",
    )
    @pytest.mark.parametrize(
        "version",
        [
            # Simple path (digits only)
            "1" * 5000,
            # Regex path (has pre-release)
            "1.0a" + "1" * 5000,
        ],
    )
    def test_oversized_version_raises_valueerror(self, version: str) -> None:
        old = sys.get_int_max_str_digits()
        sys.set_int_max_str_digits(4300)
        try:
            with pytest.raises(ValueError, match="Exceeds the limit"):
                Version(version)
        finally:
            sys.set_int_max_str_digits(old)

    @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"),
            # Non-ASCII whitespace
            ("\N{NARROW NO-BREAK SPACE}1.0\t\N{PARAGRAPH SEPARATOR}\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))

    def test_version_hash_with_warm_key_cache(self) -> None:
        v = Version("1.0")
        # Populate _key_cache via comparison before hashing
        assert v > Version("0.9")
        assert hash(v) == hash(Version("1.0"))

    @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

    @pytest.mark.parametrize(
        "op", ["__lt__", "__le__", "__eq__", "__ge__", "__gt__", "__ne__"]
    )
    def test_base_version_notimplemented_with_non_base_version(self, op: str) -> None:
        """Test _BaseVersion returns NotImplemented with non-_BaseVersion."""
        v = SimpleVersion("1.0")
        assert getattr(v, op)(1) is NotImplemented

    def test_base_version_hash(self) -> None:
        """Test that _BaseVersion hash works"""
        v = SimpleVersion("1.0")
        assert isinstance(hash(v), int)

    def test_base_version_ne_with_base_version(self) -> None:
        """Test _BaseVersion.__ne__ with another _BaseVersion."""
        v1 = SimpleVersion("1.0")
        v2 = SimpleVersion("2.0")
        assert v1 != v2

    def test_version_compare_with_base_version_subclass(self) -> None:
        """Test Version comparison with another _BaseVersion subclass"""
        v1 = Version("1.0")
        v2 = SimpleVersion("1.0")

        # All comparisons should work with compatible keys
        assert v1 == v2
        assert v1 <= v2
        assert v1 >= v2
        assert v1 == v2
        assert not (v1 < v2)
        assert not (v1 > v2)

        # Test with different versions to exercise != path
        v3 = Version("1.0")
        v4 = SimpleVersion("2.0")
        assert v3 != v4

    def test_version_ne_with_uncached_keys(self) -> None:
        """Test Version.__ne__ populates cache when comparing with another Version"""
        v1 = Version("1.0")
        v2 = Version("2.0")

        # Test with both caches None
        result = v1 != v2
        assert result is True

        # Test with v1 cached, v3 uncached
        v3 = Version("1.5")
        result = v1 != v3
        assert result is True

        # Test with v3 cached, v4 uncached (the reverse case)
        v4 = Version("1.2")
        result = v4 != v3
        assert result is True

    def test_version_le_with_uncached_keys(self) -> None:
        """Test Version.__le__ populates cache when comparing with another Version"""
        v1 = Version("1.0")
        v2 = Version("2.0")

        # Test <= with both caches None
        result = v1 <= v2
        assert result is True

        # Test with v1 cached (from above), v3 uncached
        v3 = Version("1.5")
        result = v1 <= v3
        assert result is True

    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"
        assert str(replace(v, pre=("Alpha", 2))) == "1.2.3a2"

    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"
        assert str(replace(v, pre=("bEta", 2))) == "1.2.3b2"

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

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


@pytest.mark.parametrize(
    ("args", "string"),
    [
        ({"release": (1, 2, 3)}, "1.2.3"),
        ({"release": (1, 2, 3), "epoch": 2}, "2!1.2.3"),
        ({"release": (1, 2, 3), "pre": ("b", 1)}, "1.2.3b1"),
        ({"release": (1, 2, 3), "pre": ("B", 1)}, "1.2.3b1"),
        ({"release": (1, 2, 3), "pre": ("beta", 1)}, "1.2.3b1"),
        ({"release": (1, 2, 3), "post": 2}, "1.2.3post2"),
        ({"release": (1, 2, 3), "dev": 3}, "1.2.3.dev3"),
        ({"release": (1, 2, 3), "local": "abc"}, "1.2.3+abc"),
        (
            {
                "release": (1, 2, 3),
                "epoch": None,
                "pre": None,
                "post": None,
                "dev": None,
                "local": None,
            },
            "1.2.3",
        ),
        (
            {
                "release": (2, 3, 4),
                "epoch": 1,
                "pre": ("a", 5),
                "post": 6,
                "dev": 7,
                "local": "zzz",
            },
            "1!2.3.4a5.post6.dev7+zzz",
        ),
    ],
)
def test_from_parts(args: dict[str, typing.Any], string: str) -> None:
    v = Version.from_parts(**args)
    assert v == Version(string)


@pytest.mark.parametrize(
    "version",
    [
        "1.2.3",
        "0.1.0",
        "2.0a1",
        "1.0b2",
        "3.0rc1",
        "1.0.post1",
        "1.0.dev3",
        "1!2.3.4a5.post6.dev7+zzz",
    ],
)
def test_pickle_roundtrip(version: str) -> None:
    # Make sure equality and str() work between a pickle/unpickle round trip.
    v = Version(version)
    loaded = pickle.loads(pickle.dumps(v))
    assert loaded == v
    assert str(loaded) == str(v)


# Pickle bytes generated with packaging==25.0, Python 3.13.1, pickle protocol 2.
# These contain references to packaging._structures.InfinityType and
# NegativeInfinityType in the _key cache, which were removed in packaging 26.1.
_PACKAGING_25_0_PICKLE_V1_2_3 = (
    b"\x80\x02cpackaging.version\nVersion\nq\x00)\x81q\x01}q\x02"
    b"(X\x08\x00\x00\x00_versionq\x03cpackaging.version\n_Version\n"
    b"q\x04(K\x00K\x01K\x02K\x03\x87q\x05NNNNtq\x06\x81q\x07X\x04"
    b"\x00\x00\x00_keyq\x08(K\x00K\x01K\x02K\x03\x87q\tcpackaging._structures\n"
    b"InfinityType\nq\n)\x81q\x0bcpackaging._structures\nNegativeInfinityType\n"
    b"q\x0c)\x81q\rh\x0bh\rtq\x0eub."
)

_PACKAGING_25_0_PICKLE_V2_0A1 = (
    b"\x80\x02cpackaging.version\nVersion\nq\x00)\x81q\x01}q\x02"
    b"(X\x08\x00\x00\x00_versionq\x03cpackaging.version\n_Version\n"
    b"q\x04(K\x00K\x02K\x00\x86q\x05NX\x01\x00\x00\x00aq\x06K\x01"
    b"\x86q\x07NNtq\x08\x81q\tX\x04\x00\x00\x00_keyq\n(K\x00K\x02"
    b"\x85q\x0bh\x07cpackaging._structures\nNegativeInfinityType\n"
    b"q\x0c)\x81q\rcpackaging._structures\nInfinityType\nq\x0e)\x81"
    b"q\x0fh\rtq\x10ub."
)


def test_pickle_old_format_loads() -> None:
    # Verify that pickles created with packaging <= 25.x can be loaded
    # and produce correct Version objects.
    v = pickle.loads(_PACKAGING_25_0_PICKLE_V1_2_3)
    assert isinstance(v, Version)
    assert str(v) == "1.2.3"
    assert v == Version("1.2.3")
    assert v < Version("2.0")
    assert v > Version("1.2.2")

    v2 = pickle.loads(_PACKAGING_25_0_PICKLE_V2_0A1)
    assert isinstance(v2, Version)
    assert str(v2) == "2.0a1"
    assert v2 == Version("2.0a1")
    assert v2 < Version("2.0")


def test_pickle_old_format_re_pickled_is_clean() -> None:
    # Verify that loading an old pickle and re-pickling it produces
    # a clean payload that no longer references packaging._structures.
    v = pickle.loads(_PACKAGING_25_0_PICKLE_V1_2_3)
    new_data = pickle.dumps(v)
    assert b"_structures" not in new_data
    # And the re-pickled version still works.
    v2 = pickle.loads(new_data)
    assert v2 == Version("1.2.3")
    assert str(v2) == "1.2.3"


# Pickle bytes generated with packaging==26.0, Python 3.13.1, pickle protocol 2.
# 26.0 used __slots__ (no __dict__), so the pickle state is (None, {slot: value}).
# The _key_cache slot still contains packaging._structures.InfinityType references.
_PACKAGING_26_0_PICKLE_V1_2_3 = (
    b"\x80\x02cpackaging.version\nVersion\nq\x00)\x81q\x01N}q\x02"
    b"(X\x04\x00\x00\x00_devq\x03NX\x06\x00\x00\x00_epochq\x04K\x00"
    b"X\n\x00\x00\x00_key_cacheq\x05(K\x00K\x01K\x02K\x03\x87q\x06"
    b"cpackaging._structures\nInfinityType\nq\x07)\x81q\x08cpackaging._structures\n"
    b"NegativeInfinityType\nq\t)\x81q\nh\x08h\ntq\x0bX\x06\x00\x00\x00"
    b"_localq\x0cNX\x05\x00\x00\x00_postq\rNX\x04\x00\x00\x00_preq\x0e"
    b"NX\x08\x00\x00\x00_releaseq\x0fh\x06u\x86q\x10b."
)


def test_pickle_26_0_slots_format_loads() -> None:
    # Verify that pickles created with packaging 26.0 (__slots__, no __reduce__)
    # can be loaded and produce correct Version objects.
    v = pickle.loads(_PACKAGING_26_0_PICKLE_V1_2_3)
    assert isinstance(v, Version)
    assert str(v) == "1.2.3"
    assert v == Version("1.2.3")
    assert v < Version("2.0")
    assert v > Version("1.2.2")


# Pickle bytes generated with packaging 26.2+ (6-tuple __getstate__ format),
# Python 3.13.1, pickle protocol 2.
_PACKAGING_26_2_TUPLE_PICKLE_V1E2_3_4A5_POST6_DEV7_ZZZ = (
    b"\x80\x02cpackaging.version\nVersion\nq\x00)\x81q\x01(K\x01K\x02K\x03"
    b"K\x04\x87q\x02X\x01\x00\x00\x00aq\x03K\x05\x86q\x04X\x04\x00\x00"
    b"\x00postq\x05K\x06\x86q\x06X\x03\x00\x00\x00devq\x07K\x07\x86q\x08"
    b"X\x03\x00\x00\x00zzzq\t\x85q\ntq\x0bb."
)


def test_pickle_26_2_tuple_getstate_loads() -> None:
    # Verify that pickles created with packaging 26.2+ (6-tuple __getstate__)
    # can be loaded and produce correct Version objects.
    v = pickle.loads(_PACKAGING_26_2_TUPLE_PICKLE_V1E2_3_4A5_POST6_DEV7_ZZZ)
    assert isinstance(v, Version)
    assert str(v) == "1!2.3.4a5.post6.dev7+zzz"
    assert v == Version("1!2.3.4a5.post6.dev7+zzz")
    assert v.epoch == 1
    assert v.release == (2, 3, 4)
    assert v.pre == ("a", 5)
    assert v.post == 6
    assert v.dev == 7
    assert v.local == "zzz"


def test_pickle_setstate_rejects_invalid_state() -> None:
    # Cover the TypeError branches in __setstate__ for invalid input.
    v = Version.__new__(Version)
    # dict without "_version" key
    with pytest.raises(TypeError, match="Cannot restore Version"):
        v.__setstate__({"bad_key": 123})
    # tuple with non-dict second element
    with pytest.raises(TypeError, match="Cannot restore Version"):
        v.__setstate__((None, "not_a_dict"))
    # tuple with unexpected length (not 2 or 6)
    with pytest.raises(TypeError, match="Cannot restore Version"):
        v.__setstate__((1, 2, 3))
    # completely wrong type
    with pytest.raises(TypeError, match="Cannot restore Version"):
        v.__setstate__(12345)


def test_structures_shim_repr() -> None:
    # Cover the __repr__ methods on the backward-compatibility shim classes.
    assert repr(Infinity) == "Infinity"
    assert repr(NegativeInfinity) == "-Infinity"
packaging-26.2/PKG-INFO0000644000000000000000000000672700000000000011367 0ustar00Metadata-Version: 2.4
Name: packaging
Version: 26.2
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: Programming Language :: Python :: Free Threading :: 4 - Resilient
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
- Licenses
- Requirements
- Metadata
- Tags
- Lockfiles (pylock)
- Direct URL helpers
- Dependency groups
- Errors
- Utilities

Installation
------------

Use ``pip`` to install these utilities::

    pip install packaging

The ``packaging`` library uses calendar-based versioning (``YY.N``).

Discussion
----------

If you run into bugs, you can file them in our `issue tracker`_.

You can also join discussions on `GitHub Discussions`_ to ask questions or get involved.

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


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

Everyone interacting in the packaging project's codebases, issue trackers, 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/