././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4497523 packaging-26.3/CHANGELOG.rst0000644000000000000000000010420515234171317012345 0ustar00Changelog --------- 26.3 - 2026-08-03 ~~~~~~~~~~~~~~~~~ Features: * Add a public :class:`~packaging.ranges.VersionRange` API and :meth:`SpecifierSet.to_range() `, representing the versions a specifier set accepts as an interval set that supports intersection, union, difference, complement, set relations, membership tests, and filtering. :meth:`~packaging.ranges.VersionRange.to_specifier_set` converts a range back to a :class:`~packaging.specifiers.SpecifierSet` where a PEP 440 form exists. (:pull:`1267`, :pull:`1270`, :pull:`1298`) * PEP 808: accept ``Metadata-Version: 2.6``. (:pull:`1194`) * Add a ``limit`` argument to ``parse_tag()`` for compressed tag sets. (:issue:`1220`) * Add a ``prefer_sdist_predicate`` argument to ``Pylock.select()`` to prefer source distributions over wheels for selected packages. (:pull:`1334`) * Add :func:`~packaging.tags.pure_python_tags` to generate the pure-Python tags for a Python version without touching the running platform. (:pull:`1346`) * Add :meth:`SpecifierSet.is_subset() `, :meth:`~packaging.specifiers.SpecifierSet.is_superset`, and :meth:`~packaging.specifiers.SpecifierSet.is_disjoint`, which compare the versions two specifier sets accept. (:pull:`1313`) Behavior adaptations: * Drop support for Python 3.8; packaging now requires Python 3.9 or later. (:pull:`1157`) * Prefer native ``linux_*`` platform tags over ``manylinux`` and ``musllinux`` tags on Linux. (:issue:`160`) Fixes for versions and specifiers: * Raise ``InvalidVersion`` instead of ``TypeError`` when ``Version`` is given a non-string. (:pull:`1319`) * Raise ``InvalidVersion`` for non-string pre-release letters passed to ``Version.from_parts``. (:pull:`1241`) * Fix an ``AttributeError`` when hashing internally trimmed versions. (:pull:`1242`) * Fix ``SpecifierSet.is_unsatisfiable`` for post-release boundary intersections. (:pull:`1257`) Fixes for requirements and markers: * Make ``Requirement.__hash__`` consistent with ``__eq__`` for trailing-zero-equivalent specifiers (e.g. ``foo==1.0.0`` and ``foo==1.0.0.0``), so equal requirements hash equal and deduplicate in sets and dicts. (:pull:`1232`) * Normalize requested extra names before comparing or hashing requirements. (:issue:`644`) * Preserve a ``Requirement``'s specifier ``prereleases`` override across a pickle round trip. (:issue:`1204`) * Raise ``InvalidRequirement`` instead of ``InvalidSpecifier`` when a requirement contains an invalid specifier. (:pull:`1332`) * Clarify the error for post-release prefix wildcards like ``==1.0.post1.*``. (:pull:`1299`) * Preserve quoting semantics when serializing marker values, so round-tripped markers parse back to the same marker. (:pull:`1213`) * Keep the parentheses of a nested group when serializing markers. (:pull:`1316`) * Normalize ``extra`` and ``dependency_groups`` values in nested markers at parse time. (:pull:`1246`, :pull:`1310`) * Raise ``UndefinedComparison`` when a set-valued variable like ``extras`` is used outside the membership form. (:pull:`1265`) * Raise ``UndefinedEnvironmentName`` (a ``KeyError`` subclass) for missing environment keys during marker evaluation. (:pull:`1276`) * Wrap malformed string literal errors in ``InvalidMarker`` / ``InvalidRequirement`` instead of leaking a low-level error. (:pull:`1249`) * Reject requirements and markers with a trailing line break. (:pull:`1345`) Fixes for metadata and licenses: * Collect all ``from_email`` validation errors into one ``ExceptionGroup`` instead of raising the first. (:pull:`1268`) * Accept the UTF-8 charset case-insensitively in email payloads. (:pull:`1330`) * Reject malformed ``Description-Content-Type`` values. (:pull:`1329`) * Don't rewrite user values that contain ``{field}`` placeholders in error messages. (:pull:`1327`) * Route multipart email payloads to ``unparsed`` instead of asserting. (:pull:`1247`) * Make ``InvalidMetadata`` and ``CyclicDependencyGroup`` picklable. (:pull:`1328`) * Fold every line boundary ``str.splitlines`` recognizes when writing a header with :class:`~packaging.metadata.RFC822Message`. (:pull:`1356`) * Raise ``InvalidLicenseExpression`` for misplaced ``WITH`` clauses and empty ``LicenseRef-`` names. (:pull:`1266`) * Raise ``InvalidLicenseExpression`` instead of ``KeyError`` for a ``LicenseRef-`` with a ``+`` suffix. (:pull:`1219`) Fixes for tags and filenames: * Raise ``InvalidTag`` from ``parse_tag()`` for tags with the wrong number of components. (:pull:`1238`) * Reject empty tag components in ``parse_wheel_filename()`` and ``parse_tag()``. (:pull:`1234`) * Reject an empty project name in the wheel and sdist filename parsers. (:pull:`1305`) * Reject wheel filenames with a trailing newline. (:pull:`1341`) * Reject wheel tags whose interpreter component is not an identifier. (:issue:`577`) * ``is_normalized_name`` now rejects names with collapsed double hyphens like ``a--b``. (:pull:`1230`) * Fix duplicate explicit ``abi3t`` tags. (:pull:`1245`) * Forward the ``warn`` argument to ``generic_tags()`` in ``sys_tags()``. (:pull:`1264`) * Raise ``SystemError`` for an empty or malformed CPython ``EXT_SUFFIX``. (:pull:`1271`, :pull:`1301`) * Fix a typo in the macOS ``fat3`` architecture name (was ``fat32``). (:pull:`1199`) Fixes for pylock, direct URLs, and dependency groups: * Percent-decode ``pylock`` artifact file names derived from a ``url`` so that local versions (e.g. a wheel with ``2.12.1+cu130`` encoded as ``2.12.1%2Bcu130``) yield a valid file name. (:pull:`1314`) * Use an explicitly empty ``tags`` sequence in ``Pylock.select()`` instead of falling back to ``sys_tags()``. (:pull:`1349`) * Fix ``Pylock.select()`` on Python builds that report a non-PEP 440 ``python_full_version`` (e.g. ``3.15.0+``). (:pull:`1179`) * Reject TOML booleans where integers are expected in ``pylock`` files. (:pull:`1244`) * Add ``PylockSelectError`` to ``packaging.pylock.__all__``. (:pull:`1202`) * Fix ``DirectUrl`` credential stripping for passwords containing ``@``. (:pull:`1218`) * Parse the URL scheme case-insensitively when checking for file URLs in ``direct_url``. (:pull:`1240`) * Require absolute file URLs for local directories in ``direct_url``. (:pull:`1297`) * Collect ``InvalidRequirement`` errors while resolving dependency groups instead of leaking them. (:pull:`1302`) * Don't cache malformed dependency group parses. (:pull:`1248`) Performance: * Implement ``Specifier`` and ``SpecifierSet`` filtering with the new range engine. (:pull:`1120`, :pull:`1259`) * Cache the default marker environment. (:pull:`1250`) * Cache the ``_manylinux`` module lookup process-wide. (:pull:`1254`) * Add ``__slots__`` to ``Requirement`` and the token classes. (:pull:`1320`, :pull:`1258`) * Keep range caches across canonicalization, precompile the wheel project-name pattern, simplify ``parse_tag()``, and skip ``platform.mac_ver()`` when the version and arch are given. (:pull:`1253`, :pull:`1256`, :pull:`1236`, :pull:`1255`) Documentation: * Describe the validation scope of ``packaging.pylock``. (:pull:`1339`) * Explain which ``packaging.metadata`` fields are validated. (:pull:`1342`) * Document ``RFC822Policy`` in the low-level ``packaging.metadata`` interface. (:pull:`1222`) * Enable nitpicky mode and render missing classes and fields in the API reference. (:pull:`1196`, :pull:`1225`, :pull:`1277`) * Add missing ``versionadded`` / ``versionchanged`` directives and many small docstring fixes across the API reference. (:pull:`1205`, :pull:`1207`, :pull:`1208`, :pull:`1209`, :pull:`1211`, :pull:`1216`, :pull:`1217`, :pull:`1223`, :pull:`1272`, :pull:`1273`, :pull:`1274`, :pull:`1291`, :pull:`1300`, :pull:`1303`, :pull:`1317`, :pull:`1344`) Internal: * Add Python 3.15 to the test matrix. (:pull:`1190`) * Add a musl/Alpine test job and make the test suite pass on musl. (:pull:`1226`, :pull:`1227`) * Expand the downstream test matrix by ten projects. (:pull:`1261`) * Update to mypy 2. (:pull:`1191`) * Use nox's uv integration. (:pull:`1057`) 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 metadata 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:`1169`) * Add example of ``is_unsatisfiable`` in (:pull:`1166`) Internal: * Enable the auditor persona on zizmor in (:pull:`1158`) * Test new pickle guarantees 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 735: 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=1785787087.4497523 packaging-26.3/LICENSE0000644000000000000000000000030515234171317011325 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=1785787087.4497523 packaging-26.3/LICENSE.APACHE0000644000000000000000000002367615234171317012265 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=1785787087.4497523 packaging-26.3/LICENSE.BSD0000644000000000000000000000250015234171317011733 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=1785787087.4497523 packaging-26.3/README.rst0000644000000000000000000000431715234171317012016 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=1785787087.4507523 packaging-26.3/docs/Makefile0000644000000000000000000001271015234171317012713 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=1785787087.4512296 packaging-26.3/docs/changelog.rst0000644000000000000000000000003615234171317013732 0ustar00.. include:: ../CHANGELOG.rst ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4512296 packaging-26.3/docs/conf.py0000644000000000000000000001157715234171317012564 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" # Rewrite bare ``Path`` in rendered annotations to the stdlib target so # intersphinx resolves it (annotations are strings under # ``from __future__ import annotations``). autodoc_type_aliases = { "Path": "pathlib.Path", } # -- 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), } # -- Options for nitpicky mode ------------------------------------------------ # https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-nitpick_ignore # Built with ``-n`` so unresolved cross-references fail the build. These # targets have no documentation page on purpose, so they are allowed to # stay unresolved: private internal types, and TypeVars / type aliases the # Python domain cannot resolve as classes. nitpick_ignore = [ ("py:class", "packaging.version._BaseVersion"), ("py:class", "_Validator"), ("py:class", "_MetadataVersion"), ("py:class", "_VersionReplace"), ("py:class", "T"), ("py:class", "_T"), ("py:class", "packaging.specifiers.T"), ("py:class", "UnparsedVersion"), ("py:class", "UnparsedVersionVar"), ] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4512296 packaging-26.3/docs/dependency_groups.rst0000644000000000000000000000434215234171317015524 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. .. versionadded:: 26.1 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=1785787087.4512296 packaging-26.3/docs/development/getting-started.rst0000644000000000000000000000573015234171317017440 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.9: success nox > * tests-3.10: success nox > * tests-3.11: success nox > * tests-3.12: success nox > * tests-3.13: success nox > * tests-3.14: success nox > * tests-3.15: success nox > * tests-3.13t: success nox > * tests-3.14t: success nox > * tests-3.15t: success nox > * tests-pypy3.9: skipped nox > * tests-pypy3.10: skipped nox > * tests-pypy3.11: 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=1785787087.4514275 packaging-26.3/docs/development/index.rst0000644000000000000000000000103715234171317015436 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=1785787087.4514275 packaging-26.3/docs/development/release-process.rst0000644000000000000000000000312415234171317017422 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=1785787087.4514275 packaging-26.3/docs/development/reviewing-patches.rst0000644000000000000000000000176615234171317017764 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=1785787087.4514275 packaging-26.3/docs/development/submitting-patches.rst0000644000000000000000000000477115234171317020151 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=1785787087.4514275 packaging-26.3/docs/direct_url.rst0000644000000000000000000000421415234171317014141 0ustar00Direct URLs =========== .. currentmodule:: packaging.direct_url Parse and validate `direct_url.json files `_. .. versionadded:: 26.1 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__ .. autoclass:: ArchiveInfo :members: :undoc-members: :exclude-members: __init__, __new__ .. autoclass:: DirInfo :members: :undoc-members: :exclude-members: __init__, __new__ .. autoclass:: VcsInfo :members: :undoc-members: :exclude-members: __init__, __new__ The following exception may be raised by this module: .. autoexception:: DirectUrlValidationError :exclude-members: __init__, __new__ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4514275 packaging-26.3/docs/errors.rst0000644000000000000000000000241215234171317013317 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 :external:exc:`ExceptionGroup`. It is recommended to use the stdlib module on Python 3.11+, but this does reexport that as well. .. versionadded:: 26.1 Recommended Usage ----------------- .. code-block:: python import sys 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 :external:exc:`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=1785787087.4514275 packaging-26.3/docs/index.rst0000644000000000000000000000125315234171317013114 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 ranges 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=1785787087.4514275 packaging-26.3/docs/licenses.rst0000644000000000000000000000053215234171317013611 0ustar00Licenses ========= .. currentmodule:: packaging.licenses Helper for canonicalizing SPDX `License-Expression metadata `__ as `defined in PEP 639 `__. .. versionadded:: 24.2 Reference --------- .. automodule:: packaging.licenses :members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4514275 packaging-26.3/docs/markers.rst0000644000000000000000000000504615234171317013455 0ustar00Markers ======= .. currentmodule:: packaging.markers One extra requirement of dealing with dependencies is the ability to specify if it is required depending on the operating system or Python version in use. The :ref:`specification of dependency specifiers ` defines the scheme which has been implemented by this module. Usage ----- .. doctest:: >>> from packaging.markers import Marker, UndefinedEnvironmentName >>> marker = Marker("python_version>'2'") >>> marker "2"')> >>> # We can evaluate the marker to see if it is satisfied >>> marker.evaluate() True >>> # We can also override the environment >>> env = {'python_version': '1.5'} >>> marker.evaluate(environment=env) False >>> # Multiple markers can be ANDed >>> and_marker = Marker("os_name=='a' and os_name=='b'") >>> and_marker >>> # Multiple markers can be ORed >>> or_marker = Marker("os_name=='a' or os_name=='b'") >>> or_marker >>> # Markers can be also used with extras, to pull in dependencies if >>> # a certain extra is being installed >>> extra = Marker('extra == "bar"') >>> # You can do simple comparisons between marker objects: >>> Marker("python_version > '3.6'") == Marker("python_version > '3.6'") True >>> # You can also perform simple comparisons between sets of markers: >>> markers1 = {Marker("python_version > '3.6'"), Marker('os_name == "unix"')} >>> markers2 = {Marker('os_name == "unix"'), Marker("python_version > '3.6'")} >>> markers1 == markers2 True 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=1785787087.4514275 packaging-26.3/docs/metadata.rst0000644000000000000000000000351415234171317013567 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.6\nName: packaging\nVersion: 24.0" >>> raw, unparsed = parse_email(metadata) >>> raw["metadata_version"] '2.6' >>> 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 .. autoclass:: packaging.metadata.RFC822Message .. autoclass:: packaging.metadata.RFC822Policy 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=1785787087.4514275 packaging-26.3/docs/pylock.rst0000644000000000000000000000722415234171317013312 0ustar00Lock Files ========== .. currentmodule:: packaging.pylock Parse and validate `pylock.toml files `_. .. versionadded:: 26.0 Usage ----- .. code-block:: python import tomllib from pathlib import Path from packaging.pylock import Package, PackageWheel, Pylock, is_valid_pylock_path 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}") Validation ---------- :meth:`Pylock.from_dict` and :meth:`Pylock.validate` check the structure of the lock file against the specification. Required fields must be present, fields must have the expected types, package and extra names must be normalized, and versions, specifiers and markers must parse. Each package must have exactly one source: distribution files (``sdist`` or ``wheels``), or one of ``vcs``, ``directory`` or ``archive``. Wheel and sdist filenames must be parseable (see :func:`~packaging.utils.parse_wheel_filename` and :func:`~packaging.utils.parse_sdist_filename`) and match the package name and version. Validation stops at the structure. URL and path fields, including ``packages.index``, are stored as-is. They are not checked to be valid URLs or paths, and relative paths are not resolved against the location of the lock file. A wheel or sdist entry with no ``name`` takes its filename from the last component of its ``path`` or ``url``; nothing else is read from these fields. ``hashes`` tables must be non-empty and their values must be strings, but algorithm names and digest formats are not checked. Nothing is downloaded, so checking hashes and sizes against the actual artifacts is up to the caller. 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=1785787087.4514275 packaging-26.3/docs/ranges.rst0000644000000000000000000002641415234171317013272 0ustar00Version Ranges ============== .. currentmodule:: packaging.ranges A :class:`VersionRange` is the set of :class:`~packaging.version.Version` values accepted by a :class:`~packaging.specifiers.SpecifierSet`, viewed as intervals on the PEP 440 ordering. It supports intersection, union, complement, and difference, so tooling that combines many requirements, such as a resolver, can work on the intervals directly. .. versionadded:: 26.3 Usage ----- .. doctest:: >>> from packaging.ranges import VersionRange >>> from packaging.specifiers import SpecifierSet >>> from packaging.version import Version >>> # Build a range from a specifier set >>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> r >>> Version("1.5") in r True >>> Version("2.0") in r False >>> # Combine ranges with set algebra >>> a = SpecifierSet(">=1.0").to_range() >>> b = SpecifierSet("<2.0").to_range() >>> a & b == r True >>> # The union covers either side, leaving any gap between them >>> u = SpecifierSet("<1.0").to_range() | SpecifierSet(">=2.0").to_range() >>> Version("0.5") in u True >>> Version("1.5") in u False >>> # The complement is every other version >>> Version("0.5") in ~r True >>> # Filter an iterable of versions >>> list(r.filter(["0.9", "1.5", "2.0"])) ['1.5'] >>> # An unsatisfiable set produces the empty range >>> SpecifierSet(">=2.0,<1.0").to_range().is_empty True >>> # Convert back to a SpecifierSet when possible >>> str(r.to_specifier_set()) '<2.0,>=1.0' Pre-releases ------------ A specifier that names a pre-release, such as ``>=2.0b1``, opts in pre-releases only for the versions it asks for. That opt-in region is carried as ranges are combined, so a union with a plain range keeps the pre-releases it named without admitting every pre-release below them: .. doctest:: >>> a = SpecifierSet(">=1.0").to_range() >>> b = SpecifierSet(">=2.0b1").to_range() >>> list((a | b).filter(["1.5b1", "2.0b1", "2.5"])) ['2.0b1', '2.5'] ``2.0b1`` is admitted because ``>=2.0b1`` asked for it; ``1.5b1`` is not, since the opt-in never came from ``>=1.0``. The opt-in is also clipped to the range's own bounds, so combining ranges never force-admits a pre-release outside every operand's request. ``>=2.0b1,<3`` opts pre-releases in only below ``3``, so unioning it with an unrelated higher range does not admit a pre-release up in that range: .. doctest:: >>> capped = SpecifierSet(">=2.0b1,<3").to_range() >>> other = SpecifierSet(">=3.5,<4").to_range() >>> list((capped | other).filter(["3.6b1", "3.7"])) ['3.7'] Neither operand admits ``3.6b1``: ``>=3.5,<4`` names no pre-release and ``>=2.0b1,<3`` opts in only below ``3``. Set difference -------------- ``a - b`` is set difference: the versions in ``a`` but not ``b``. It agrees with ``a & ~b`` on the version set and the opt-in region, so subtracting a pre-release-naming range does not leak its pre-releases into the result: .. doctest:: >>> base = SpecifierSet(">=1.0").to_range() >>> excluded = SpecifierSet(">=2.0b1").to_range() >>> list((base - excluded).filter(["1.9", "2.0a1"])) ['1.9'] >>> (base - excluded) == (base & ~excluded) True Comparing ranges ---------------- Equality on a :class:`VersionRange` is structural: it compares the bounds, the ``===`` admit/reject literals, the arbitrary-string flag, the configured pre-release policy, and the opt-in region, not only the version set. Equal ranges therefore behave identically under :meth:`VersionRange.contains` and :meth:`VersionRange.filter`. The guarantee is one-directional: ``==1.0`` and ``>=1.0,<1.0.post0.dev0`` compare unequal (the second carries an opt-in region), yet no pre-release exists in that window, so they filter identically. For set relations use :meth:`VersionRange.is_subset`, :meth:`VersionRange.is_superset`, and :meth:`VersionRange.is_disjoint` rather than comparing intersections by hand. Intersection can change the opt-in region without changing the version set, so the textbook subset test ``a & b == a`` can report a false negative. Each method compares the version sets directly, so it is not affected by that opt-in difference: .. doctest:: >>> from packaging.specifiers import SpecifierSet >>> a = SpecifierSet(">=1.0").to_range() >>> b = SpecifierSet(">=1.0a1").to_range() >>> # Every version >=1.0 is also >=1.0a1, so a is a subset of b. But b >>> # opts pre-releases in, so ``a & b`` and ``a`` differ in the opt-in region: >>> a & b == a False >>> a.is_subset(b) True >>> b.is_superset(a) True >>> a.is_disjoint(b) False >>> # The opt-in difference is observable: a & b force-admits pre-releases >>> # in b's region that plain a filters out >>> list(a.filter(["2.0a1", "2.5"])) ['2.5'] >>> list((a & b).filter(["2.0a1", "2.5"])) ['2.0a1', '2.5'] Like :meth:`VersionRange.intersection`, :meth:`VersionRange.union`, and :meth:`VersionRange.difference`, these predicates require both operands to share the same configured pre-release policy and raise :exc:`ValueError` otherwise. Because the operations refuse to mix policies, a range's version set is well-defined only under its own configured policy, and set relations stay sound only while that policy is held fixed. Reinterpreting a range, or a :class:`~packaging.specifiers.SpecifierSet` recovered from one, under a different ``prereleases`` value is therefore unsound: under ``prereleases=False`` the ranges of ``<=1.0,!=1.0`` and ``<1.0`` accept the same releases (they differ only in ``1.0``'s pre-releases, which the policy excludes), but that equivalence is gone once the policy changes. Different specifiers that denote the same range, opt-in region included, canonicalize to one form, so they compare equal. ``>1.0a1`` excludes ``1.0a1``'s post-releases per PEP 440, so its smallest member is ``1.0a2.dev0``, exactly the set of ``>=1.0a2.dev0``: .. doctest:: >>> r1 = SpecifierSet(">1.0a1").to_range() >>> r2 = SpecifierSet(">=1.0a2.dev0").to_range() >>> r1 == r2 True >>> third = SpecifierSet("<2.0").to_range() >>> (r1 & third) == (r2 & third) True The opt-in region is also part of equality. ``<1.0.post0.dev0`` and ``<=1.0`` cover the same versions, but the first autodetects an opt-in region from its ``.dev`` bound, so it admits pre-releases by default, while the second does not; they are not substitutable and compare unequal: .. doctest:: >>> SpecifierSet("<1.0.post0.dev0").to_range() == SpecifierSet("<=1.0").to_range() False Recovering a specifier set -------------------------- :meth:`VersionRange.to_specifier_set` converts a range back to a :class:`~packaging.specifiers.SpecifierSet`. Specifier syntax cannot express every range, so it returns the simplest set whose own :meth:`~packaging.specifiers.SpecifierSet.to_range` reproduces the range, or ``None`` when no single set does: .. doctest:: >>> str(SpecifierSet(">=1.0,<2.0").to_range().to_specifier_set()) '<2.0,>=1.0' >>> # A disjoint union usually has no single-set spelling >>> a = SpecifierSet("<1").to_range() >>> b = SpecifierSet(">=2").to_range() >>> (a | b).to_specifier_set() is None True >>> # unless the gap between the pieces is expressible as exclusions >>> u = SpecifierSet("==1.*").to_range() | SpecifierSet("==3.*").to_range() >>> str(u.to_specifier_set()) '!=0.*,!=2.*,<4' >>> # The strict singleton has no spelling: ==1.5 would also match 1.5+local >>> VersionRange.singleton("1.5").to_specifier_set() is None True >>> # Neither does the full range built by algebra: it opts no pre-release >>> # in, while its only spelling, >=0.dev0, opts them all in >>> r = SpecifierSet(">=2").to_range() >>> (r | ~r).to_specifier_set() is None True >>> # full() itself admits arbitrary strings, which the empty set spells >>> str(VersionRange.full().to_specifier_set()) '' The recovery also caps how many ``!=`` exclusions it will write out, returning ``None`` past the cap; without it, some ranges would convert to pathologically large sets that are slow to build and to use: .. doctest:: >>> far = SpecifierSet("==1.*").to_range() | SpecifierSet("==1000000.*").to_range() >>> far.to_specifier_set() is None True Limits of the model ------------------- The pre-release opt-in is not itself a set. PEP 440 opts a whole specifier set in when any one specifier names a pre-release, so ``&`` is requirement conjunction (a comma-merge of the two specifier sets), not plain intersection, on the opt-in. No model can keep that parity with :class:`~packaging.specifiers.SpecifierSet`, exclusion soundness (an exclusion grants no opt-in), and an involutive complement at the same time. This model keeps parity and soundness, so complement drops the opt-in and a few Boolean identities do not hold once an operand carries one. A double complement therefore erases the opt-in rather than restoring it. ``~~r`` keeps ``r``'s versions but not its eager pre-releases: .. doctest:: >>> b = SpecifierSet(">=2.0b1").to_range() >>> list(b.filter(["2.0b1", "2.5"])) ['2.0b1', '2.5'] >>> list((~~b).filter(["2.0b1", "2.5"])) ['2.5'] >>> ~~b == b False The erasure is still well behaved: ``~~~r == ~r``, both De Morgan laws hold, and ``r & ~r`` is empty. .. doctest:: >>> ~~~b == ~b True >>> (b & ~b).is_empty True Because complement drops the opt-in while union keeps it, ``b | full()`` carries ``b``'s opt-in, which the full range (with no eager pre-release) does not, so it does not collapse to :meth:`VersionRange.full`. For the same reason union no longer distributes over intersection, and the absorption laws do not hold, when an operand carries an opt-in: .. doctest:: >>> a = SpecifierSet(">=1.0").to_range() >>> b | VersionRange.full() == VersionRange.full() False >>> a & (a | b) == a False Intersection still distributes over union, ``a - b`` agrees with ``a & ~b`` on the version set and the opt-in region, and every law holds on the version set as usual. The opt-in region makes the identities above differ only when a specifier named a pre-release. The arbitrary-string flag has corners of its own. ``SpecifierSet("")`` matches even strings that are not PEP 440 versions, so its range, :meth:`VersionRange.full`, admits them too; pass ``admit_arbitrary=False`` for the versions-only full range. Only those ranges and ``===`` literals admit such strings: combining ranges never grants an admission the operands did not have, so ``~r`` stays version-only for any version-only ``r``. The flag rides along where that is harmless, keeping ``~~full() == full()`` and union idempotent, but an intersection or difference that shrinks the bounds does not remember it: .. doctest:: >>> f = VersionRange.full() >>> "wat" in f True >>> "wat" in VersionRange.full(admit_arbitrary=False) False >>> ~~f == f True >>> (~f | ~f) == ~f True >>> (f & ~f) == VersionRange.empty() True >>> (f & ~f) == ~f False >>> d = f - SpecifierSet(">=1.0").to_range() >>> "wat" in (d | SpecifierSet(">=0.5").to_range()) False >>> d == f & ~SpecifierSet(">=1.0").to_range() True Reference --------- .. automodule:: packaging.ranges :members: :special-members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4514275 packaging-26.3/docs/requirements.rst0000644000000000000000000001107415234171317014532 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 >>> Requirement("my_pkg[foo_bar] == 1.0") == Requirement("my-pkg[foo-bar] == 1.0.0") True >>> str(Requirement("my_pkg[foo_bar] == 1.0")) 'my_pkg[foo_bar]==1.0' >>> # 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_string) This class abstracts handling the details of a requirement for a project. Each requirement will be parsed according to the specification. .. versionadded:: 16.1 .. versionchanged:: 22.0 Added equality (``__eq__``) and hashing (``__hash__``) so requirements can be compared and stored in sets / dicts. .. versionchanged:: 23.2 Equality and hashing began canonicalizing requirement names, so requirements whose names differ only by normalization (e.g. ``Requirement("Foo")`` vs ``Requirement("foo")``) now compare and hash equal. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. .. versionchanged:: 26.3 The dedicated pickle support introduced in 26.2 did not preserve the specifier's explicit :attr:`~packaging.specifiers.SpecifierSet.prereleases` override; it is now included again. Equality and hashing normalize extras and equivalent specifiers. The string representation still preserves the parsed name and extras spelling. :param str requirement_string: The string representation of a requirement. :raises InvalidRequirement: If the given ``requirement_string`` 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. .. versionadded:: 16.1 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4514275 packaging-26.3/docs/security.rst0000644000000000000000000000125515234171317013656 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=1785787087.4514275 packaging-26.3/docs/specifiers.rst0000644000000000000000000000663715234171317014154 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 >>> # We can convert a specifier set into a set-algebra VersionRange >>> SpecifierSet(">=1.0,<2.0").to_range() >>> # Or ask set-relation questions directly >>> SpecifierSet(">=3.12,<3.13").is_subset(SpecifierSet(">=3.12")) True >>> SpecifierSet(">=3.12").is_superset(SpecifierSet(">=3.12,<3.13")) True >>> SpecifierSet("<3.12").is_disjoint(SpecifierSet(">=3.12")) True The :meth:`~packaging.specifiers.SpecifierSet.to_range` method returns a :class:`~packaging.ranges.VersionRange`, a set-algebra view of the accepted versions that supports intersection, union, complement, and difference. See :doc:`ranges` for details. The relation helpers take another :class:`~packaging.specifiers.SpecifierSet` and compare the versions the two sets accept, not the specifier objects themselves. Both sets must have been given the same ``prereleases`` argument, not just the same derived :attr:`~packaging.specifiers.SpecifierSet.prereleases` value, or the comparison raises :exc:`ValueError`. Sets containing ``===`` specifiers are rejected; call :meth:`~packaging.specifiers.SpecifierSet.to_range` on both sides for those. Reference --------- .. automodule:: packaging.specifiers :members: :special-members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4517524 packaging-26.3/docs/tags.rst0000644000000000000000000000542115234171317012744 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 .. autoexception:: TooManyTagsError .. autoexception:: UnsortedTagsError .. autoexception:: InvalidTag 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. .. autodata:: PythonVersion .. autodata:: AppleVersion .. autofunction:: interpreter_name .. autofunction:: interpreter_version .. autofunction:: mac_platforms .. autofunction:: ios_platforms .. autofunction:: android_platforms .. autofunction:: platform_tags .. autofunction:: compatible_tags .. autofunction:: pure_python_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=1785787087.4517524 packaging-26.3/docs/utils.rst0000644000000000000000000000023415234171317013143 0ustar00Utilities ========= A set of small, helper utilities for dealing with Python packages. Reference --------- .. automodule:: packaging.utils :members: ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4517524 packaging-26.3/docs/version.rst0000644000000000000000000000217415234171317013475 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=1785787087.4517524 packaging-26.3/pyproject.toml0000644000000000000000000001103715234171317013240 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.9" 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.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 :: 3.15", "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", ] 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.9" files = ["src", "tests", "noxfile.py"] native_parser = true [[tool.mypy.overrides]] module = ["_manylinux", "pretend"] 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 "CPY001", # no copyright messages in files (for now) "D", # doc formatting "EM", # flake8-errmsg "ERA", # commented out code "FBT", # boolean positional args (existing API) "FIX", # has todos "ISC004", # unparenthesized implicit string concatenation in collection "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_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=1785787087.4524963 packaging-26.3/src/packaging/__init__.py0000644000000000000000000000075615234171317015156 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.3" __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=1785787087.4525542 packaging-26.3/src/packaging/_elffile.py0000644000000000000000000000624415234171317015162 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 AArch64 = 183 class ELFFile: """ Representation of an ELF executable. """ def __init__(self, f: IO[bytes]) -> None: self._f = f try: ident = self._read("16B") except struct.error as e: raise ELFInvalid("unable to parse identification") from e magic = bytes(ident[:4]) if magic != b"\x7fELF": raise ELFInvalid(f"invalid magic: {magic!r}") self.capacity = ident[4] # Format for program header (bitness). self.encoding = ident[5] # Data structure encoding (endianness). try: # e_fmt: Format for the ELF header. # p_fmt: Format for a program header. # p_idx: Indexes to find p_type, p_offset, and p_filesz. e_fmt, self._p_fmt, self._p_idx = { (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit 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 a program header entry. self._e_phnum, # Number of program headers. ) = self._read(e_fmt) except struct.error as e: raise ELFInvalid("unable to parse machine and section information") from e def _read(self, fmt: str) -> tuple[int, ...]: return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) @property def interpreter(self) -> str | None: """ The path recorded in the ``PT_INTERP`` section header. """ for index in range(self._e_phnum): self._f.seek(self._e_phoff + self._e_phentsize * index) try: data = self._read(self._p_fmt) except struct.error: continue if data[self._p_idx[0]] != 3: # Not PT_INTERP. continue self._f.seek(data[self._p_idx[1]]) return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") return None ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4525542 packaging-26.3/src/packaging/_manylinux.py0000644000000000000000000002342015234171317015573 0ustar00from __future__ import annotations import collections import contextlib import functools import os import re import sys import warnings from typing import TYPE_CHECKING, NamedTuple from ._elffile import EIClass, EIData, ELFFile, EMachine if TYPE_CHECKING: import types from collections.abc import Generator, Iterator, Sequence EF_ARM_ABIMASK = 0xFF000000 EF_ARM_ABI_VER5 = 0x05000000 EF_ARM_ABI_FLOAT_HARD = 0x00000400 _ALLOWED_ARCHS = { "x86_64", "aarch64", "ppc64", "ppc64le", "s390x", "loongarch64", "riscv64", } @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 # A c_char_p restype comes back as bytes, so decode to text. version_str: str | bytes = gnu_get_libc_version() if isinstance(version_str, bytes): version_str = version_str.decode("ascii") return version_str def _glibc_version_string() -> str | None: """Returns glibc version string, or None if not using glibc.""" return _glibc_version_string_confstr() or _glibc_version_string_ctypes() def _parse_glibc_version(version_str: str) -> _GLibCVersion: """Parse glibc version. We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked versions of glibc (e.g. Linaro's version of glibc uses version strings like "2.20-2014.11"). See gh-3588. """ m = re.match(r"(?P[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 @functools.lru_cache(maxsize=1) def _get_manylinux_module() -> types.ModuleType | None: """Return the ``_manylinux`` C extension module, or None if unavailable. The result is cached for the lifetime of the process, since the presence of the module does not change while running. """ try: return __import__("_manylinux") except ImportError: return None def _is_compatible(arch: str, version: _GLibCVersion) -> bool: sys_glibc = _get_glibc_version() if sys_glibc < version: return False # Check for presence of _manylinux module. manylinux_mod = _get_manylinux_module() if manylinux_mod is None: return True if hasattr(manylinux_mod, "manylinux_compatible"): result = manylinux_mod.manylinux_compatible(version[0], version[1], arch) if result is not None: return bool(result) return True if version == _GLibCVersion(2, 5) and hasattr( manylinux_mod, "manylinux1_compatible" ): return bool(manylinux_mod.manylinux1_compatible) if version == _GLibCVersion(2, 12) and hasattr( manylinux_mod, "manylinux2010_compatible" ): return bool(manylinux_mod.manylinux2010_compatible) if version == _GLibCVersion(2, 17) and hasattr( manylinux_mod, "manylinux2014_compatible" ): return bool(manylinux_mod.manylinux2014_compatible) return True _LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { # CentOS 7 w/ glibc 2.17 (PEP 599) _GLibCVersion(2, 17): "manylinux2014", # CentOS 6 w/ glibc 2.12 (PEP 571) _GLibCVersion(2, 12): "manylinux2010", # CentOS 5 w/ glibc 2.5 (PEP 513) _GLibCVersion(2, 5): "manylinux1", } def platform_tags(archs: Sequence[str]) -> Iterator[str]: """Generate manylinux tags compatible to the current platform. :param archs: Sequence of compatible architectures. The first one shall be the closest to the actual architecture and be the part of platform tag after the ``linux_`` prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a prerequisite for the current platform to be manylinux-compatible. :returns: An iterator of compatible manylinux tags. """ if not _have_compatible_abi(sys.executable, archs): return # Oldest glibc to be supported regardless of architecture is (2, 17). too_old_glibc2 = _GLibCVersion(2, 16) if set(archs) & {"x86_64", "i686"}: # On x86/i686 also oldest glibc to be supported is (2, 5). too_old_glibc2 = _GLibCVersion(2, 4) current_glibc = _GLibCVersion(*_get_glibc_version()) glibc_max_list = [current_glibc] # We can assume compatibility across glibc major versions. # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 # # Build a list of maximum glibc versions so that we can # output the canonical list of all glibc from current_glibc # down to too_old_glibc2, including all intermediary versions. for glibc_major in range(current_glibc.major - 1, 1, -1): glibc_minor = _LAST_GLIBC_MINOR[glibc_major] glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) for arch in archs: for glibc_max in glibc_max_list: if glibc_max.major == too_old_glibc2.major: min_minor = too_old_glibc2.minor else: # For other glibc major versions oldest supported is (x, 0). min_minor = -1 for glibc_minor in range(glibc_max.minor, min_minor, -1): glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) if _is_compatible(arch, glibc_version): yield "manylinux_{}_{}_{}".format(*glibc_version, arch) # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version): yield f"{legacy_tag}_{arch}" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4525542 packaging-26.3/src/packaging/_musllinux.py0000644000000000000000000000532615234171317015614 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 TYPE_CHECKING, NamedTuple from ._elffile import ELFFile if TYPE_CHECKING: from collections.abc import Iterator, Sequence class _MuslVersion(NamedTuple): major: int minor: int def _parse_musl_version(output: str) -> _MuslVersion | None: lines = [n for n in (n.strip() for n in output.splitlines()) if n] if len(lines) < 2 or lines[0][:4] != "musl": return None m = re.match(r"Version (\d+)\.(\d+)", lines[1]) if not m: return None return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) @functools.lru_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=1785787087.4525542 packaging-26.3/src/packaging/_parser.py0000644000000000000000000003053715234171317015052 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 collections.abc import Sequence from typing import Literal, NamedTuple, Union from ._tokenizer import DEFAULT_RULES, ParserSyntaxError, Tokenizer class Node: __slots__ = ("value",) def __init__(self, value: str) -> None: self.value = value def __str__(self) -> str: return self.value def __repr__(self) -> str: return f"<{self.__class__.__name__}({self.value!r})>" def serialize(self) -> str: raise NotImplementedError def __getstate__(self) -> str: # Return just the value string for compactness and stability. return self.value def _restore_value(self, value: object) -> None: if not isinstance(value, str): raise TypeError( f"Cannot restore {self.__class__.__name__} value from {value!r}" ) self.value = value def __setstate__(self, state: object) -> None: if isinstance(state, str): # New format (26.2+): just the value string. self._restore_value(state) return if isinstance(state, tuple) and len(state) == 2: # Old format (packaging <= 26.0, __slots__): (None, {slot: value}). _, slot_dict = state if isinstance(slot_dict, dict) and "value" in slot_dict: self._restore_value(slot_dict["value"]) return if isinstance(state, dict) and "value" in state: # Old format (packaging <= 25.0, no __slots__): plain __dict__. self._restore_value(state["value"]) return raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}") class Variable(Node): __slots__ = () def serialize(self) -> str: return str(self) class Value(Node): __slots__ = () def serialize(self) -> str: value = str(self) if '"' not in value: return f'"{value}"' if "'" not in value: return f"'{value}'" raise ValueError( "Cannot serialize marker value containing both quote characters" ) class Op(Node): __slots__ = () def serialize(self) -> str: return str(self) MarkerLogical = Literal["and", "or"] MarkerVar = Union[Variable, Value] MarkerItem = tuple[MarkerVar, Op, MarkerVar] MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] MarkerList = list[Union["MarkerList", MarkerAtom, MarkerLogical]] class ParsedRequirement(NamedTuple): name: str url: str extras: list[str] specifier: str marker: MarkerList | None # -------------------------------------------------------------------------------------- # Recursive descent parser for dependency specifier # -------------------------------------------------------------------------------------- def parse_requirement(source: str) -> ParsedRequirement: return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: """ requirement = WS? IDENTIFIER WS? extras WS? requirement_details """ tokenizer.consume("WS") name_token = tokenizer.expect( "IDENTIFIER", expected="package name at the start of dependency specifier" ) name = name_token.text tokenizer.consume("WS") extras = _parse_extras(tokenizer) tokenizer.consume("WS") url, specifier, marker = _parse_requirement_details(tokenizer) tokenizer.expect("END", expected="end of dependency specifier") return ParsedRequirement(name, url, extras, specifier, marker) def _parse_requirement_details( tokenizer: Tokenizer, ) -> tuple[str, str, MarkerList | None]: """ requirement_details = AT URL (WS requirement_marker?)? | specifier WS? (requirement_marker)? """ specifier = "" url = "" marker = None if tokenizer.check("AT"): tokenizer.read() tokenizer.consume("WS") url_start = tokenizer.position url = tokenizer.expect("URL", expected="URL after @").text if tokenizer.check("END", peek=True): return (url, specifier, marker) tokenizer.expect("WS", expected="whitespace after URL") # The input might end after whitespace. if tokenizer.check("END", peek=True): return (url, specifier, marker) marker = _parse_requirement_marker( tokenizer, span_start=url_start, expected="semicolon (after URL and whitespace)", ) else: specifier_start = tokenizer.position specifier = _parse_specifier(tokenizer) tokenizer.consume("WS") if tokenizer.check("END", peek=True): return (url, specifier, marker) marker = _parse_requirement_marker( tokenizer, span_start=specifier_start, expected=( "comma (within version specifier), semicolon (after version specifier)" if specifier else "semicolon (after name with no version specifier)" ), ) return (url, specifier, marker) def _parse_requirement_marker( tokenizer: Tokenizer, *, span_start: int, expected: str ) -> MarkerList: """ requirement_marker = SEMICOLON marker WS? """ if not tokenizer.check("SEMICOLON"): tokenizer.raise_syntax_error( f"Expected {expected} or end", span_start=span_start, span_end=None, ) tokenizer.read() marker = _parse_marker(tokenizer) tokenizer.consume("WS") return marker def _parse_extras(tokenizer: Tokenizer) -> list[str]: """ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? """ if not tokenizer.check("LEFT_BRACKET", peek=True): return [] with tokenizer.enclosing_tokens( "LEFT_BRACKET", "RIGHT_BRACKET", around="extras", ): tokenizer.consume("WS") extras = _parse_extras_list(tokenizer) tokenizer.consume("WS") return extras def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: """ extras_list = identifier (wsp* ',' wsp* identifier)* """ extras: list[str] = [] if not tokenizer.check("IDENTIFIER"): return extras extras.append(tokenizer.read().text) while True: tokenizer.consume("WS") if tokenizer.check("IDENTIFIER", peek=True): tokenizer.raise_syntax_error("Expected comma between extra names") elif not tokenizer.check("COMMA"): break tokenizer.read() tokenizer.consume("WS") extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") extras.append(extra_token.text) return extras def _parse_specifier(tokenizer: Tokenizer) -> str: """ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS | WS? version_many WS? """ with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="version specifier", ): tokenizer.consume("WS") parsed_specifiers = _parse_version_many(tokenizer) tokenizer.consume("WS") return parsed_specifiers def _parse_version_many(tokenizer: Tokenizer) -> str: """ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? """ parsed_specifiers = "" while tokenizer.check("SPECIFIER"): span_start = tokenizer.position specifier = tokenizer.read().text parsed_specifiers += specifier if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): message = ".* suffix can only be used with `==` or `!=` operators" if specifier.startswith("!=") or ( specifier.startswith("==") and not specifier.startswith("===") ): message = ( ".* suffix cannot be used with pre-release, post-release, " "dev or local versions" ) tokenizer.raise_syntax_error( message, span_start=span_start, span_end=tokenizer.position + 1, ) if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): tokenizer.raise_syntax_error( "Local version label can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position, ) tokenizer.consume("WS") if not tokenizer.check("COMMA"): break parsed_specifiers += tokenizer.read().text tokenizer.consume("WS") return parsed_specifiers # -------------------------------------------------------------------------------------- # Recursive descent parser for marker expression # -------------------------------------------------------------------------------------- def parse_marker(source: str) -> MarkerList: return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: retval = _parse_marker(tokenizer) tokenizer.expect("END", expected="end of marker expression") return retval def _parse_marker(tokenizer: Tokenizer) -> MarkerList: """ marker = marker_atom (BOOLOP marker_atom)+ """ expression = [_parse_marker_atom(tokenizer)] while tokenizer.check("BOOLOP"): token = tokenizer.read() expr_right = _parse_marker_atom(tokenizer) expression.extend((token.text, expr_right)) return expression def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: """ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? | WS? marker_item WS? """ tokenizer.consume("WS") if tokenizer.check("LEFT_PARENTHESIS", peek=True): with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="marker expression", ): tokenizer.consume("WS") marker: MarkerAtom = _parse_marker(tokenizer) tokenizer.consume("WS") else: marker = _parse_marker_item(tokenizer) tokenizer.consume("WS") return marker def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: """ marker_item = WS? marker_var WS? marker_op WS? marker_var WS? """ tokenizer.consume("WS") marker_var_left = _parse_marker_var(tokenizer) tokenizer.consume("WS") marker_op = _parse_marker_op(tokenizer) tokenizer.consume("WS") marker_var_right = _parse_marker_var(tokenizer) tokenizer.consume("WS") return (marker_var_left, marker_op, marker_var_right) def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503 """ marker_var = VARIABLE | QUOTED_STRING """ if tokenizer.check("VARIABLE"): return process_env_var(tokenizer.read().text.replace(".", "_")) elif tokenizer.check("QUOTED_STRING"): token = tokenizer.read() try: return process_python_str(token.text) except (SyntaxError, ValueError) as exc: raise ParserSyntaxError( "Invalid quoted string", source=tokenizer.source, span=(token.position, token.position + len(token.text)), ) from exc else: tokenizer.raise_syntax_error( message="Expected a marker variable or quoted string" ) def process_env_var(env_var: str) -> Variable: if env_var in ("platform_python_implementation", "python_implementation"): return Variable("platform_python_implementation") else: return Variable(env_var) def process_python_str(python_str: str) -> Value: value = ast.literal_eval(python_str) return Value(str(value)) def _parse_marker_op(tokenizer: Tokenizer) -> Op: """ marker_op = IN | NOT IN | OP """ if tokenizer.check("IN"): tokenizer.read() return Op("in") elif tokenizer.check("NOT"): tokenizer.read() tokenizer.expect("WS", expected="whitespace after 'not'") tokenizer.expect("IN", expected="'in' after 'not'") return Op("not in") elif tokenizer.check("OP"): return Op(tokenizer.read().text) else: return tokenizer.raise_syntax_error( "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4525542 packaging-26.3/src/packaging/_ranges.py0000644000000000000000000007420215234171317015032 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. """Private version-range helpers used by :mod:`packaging.specifiers`.""" from __future__ import annotations import enum import functools from typing import ( TYPE_CHECKING, Any, Final, ) from .version import InvalidVersion, Version if TYPE_CHECKING: from collections.abc import Callable, Iterable, Iterator, Sequence from typing import Union # Total-order key for comparing two boundaries (boundary-vs-boundary only). # The post slot may be ``_BOUNDARY_INF`` for an AFTER_POSTS boundary. _BoundaryOrderSuffix = tuple[int, int, int, Union[int, float], int, int] _BoundaryOrderKey = tuple[int, tuple[int, ...], _BoundaryOrderSuffix, float] __all__ = [ "FULL_RANGE", "bounds_for_spec", "coerce_version", "filter_by_ranges", "intersect_ranges", "intersect_specifier_bounds", "least_version_above", "matches_bounds_only", "range_is_empty", "ranges_are_prerelease_only", "resolve_prereleases", "standard_ranges", "wildcard_ranges", ] #: The smallest possible PEP 440 version. No valid version is less than this. MIN_VERSION: Final[Version] = Version("0.dev0") #: The smallest non-pre-release version, i.e. the nearest non-pre-release at or #: above the ``-inf`` floor. MIN_RELEASE: Final[Version] = Version("0") #: Sorts above any real post number and any local label, so a boundary can be #: ordered above the version family it covers when two boundaries are compared. _BOUNDARY_INF: Final[float] = float("inf") class BoundaryKind(enum.Enum): """Where a boundary marker sits in the version ordering.""" AFTER_LOCALS = enum.auto() # after V+local, before V.post0 AFTER_POSTS = enum.auto() # after V.postN, before next release @functools.total_ordering class BoundaryVersion: """A point on the version line between two real PEP 440 versions. Relative to a base version V:: V < V+local < AFTER_LOCALS(V) < V.post0 < AFTER_POSTS(V) AFTER_LOCALS is the upper bound of ``<=V``, ``==V``, ``!=V`` (no local), and the lower bound of the upper-side range of ``!=V``. AFTER_POSTS is the lower bound of ``>V`` (V final or pre-release), excluding V's post-releases per PEP 440. """ __slots__ = ( "_cached_dev", "_cached_epoch", "_cached_post", "_cached_pre", "_cached_trimmed_release", "kind", "version", ) def __init__(self, version: Version, kind: BoundaryKind) -> None: self.version = version self.kind = kind self._cached_trimmed_release = trim_release(version.release) self._cached_epoch = version.epoch self._cached_pre = version.pre self._cached_post = version.post self._cached_dev = version.dev def _is_family(self, other: Version) -> bool: """Is ``other`` a version that this boundary sorts above?""" if other.epoch != self._cached_epoch: return False # Inline release-trim comparison: other.release matches the # trimmed release iff its leading slice is equal and any extra # components are zero. Avoids trim_release's tuple allocation. other_release = other.release trimmed_release = self._cached_trimmed_release trimmed_length = len(trimmed_release) if len(other_release) < trimmed_length: return False if other_release[:trimmed_length] != trimmed_release: return False for i in range(trimmed_length, len(other_release)): if other_release[i] != 0: return False if other.pre != self._cached_pre: return False if self.kind == BoundaryKind.AFTER_LOCALS: # Local family: same public version, any local label. return other.post == self._cached_post and other.dev == self._cached_dev # Post family: V itself + any post-release of V. return other.dev == self._cached_dev or other.post is not None def _order_key(self) -> _BoundaryOrderKey: """Sort key placing this boundary just above the versions it covers. It extends ``V``'s comparison key ``(epoch, release, suffix)`` with a trailing ``_BOUNDARY_INF`` local component, so the key sorts after ``V`` and every ``V+local`` (whose keys carry a real, finite local segment). ``suffix`` is the 6-int comparison suffix ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``. For an AFTER_POSTS boundary the suffix is replaced with one whose post number is ``_BOUNDARY_INF``, so the key also sorts after every ``V.postN``. An AFTER_LOCALS boundary uses ``V``'s suffix unchanged. """ version_key = self.version._key suffix: _BoundaryOrderSuffix = version_key[2] if self.kind == BoundaryKind.AFTER_POSTS: suffix = (suffix[0], suffix[1], 1, _BOUNDARY_INF, 1, 0) return version_key[0], version_key[1], suffix, _BOUNDARY_INF def __eq__(self, other: object) -> bool: # Key off the order key so equality matches the ``<`` / ``>`` order: # ``AFTER_POSTS(1.0)`` and ``AFTER_POSTS(1.0.post1)`` are the same point. if isinstance(other, BoundaryVersion): return self._order_key() == other._order_key() return NotImplemented def __lt__(self, other: BoundaryVersion | Version) -> bool: if isinstance(other, BoundaryVersion): return self._order_key() < other._order_key() # boundary < other_version iff V < other AND other not in family. # The cheap V >= other path short-circuits before the family check. if not (self.version < other): return False return not self._is_family(other) def __gt__(self, other: BoundaryVersion | Version) -> bool: # Defined directly to bypass functools.total_ordering's # NotImplemented round-trip on reflected ``Version < boundary``. if isinstance(other, BoundaryVersion): return self._order_key() > other._order_key() if self.version >= other: return True return self._is_family(other) def __hash__(self) -> int: # Keyed to ``__eq__`` (the order key), so equal boundaries hash equal. return hash(self._order_key()) def __repr__(self) -> str: return f"{self.__class__.__name__}({self.version!r}, {self.kind.name})" if TYPE_CHECKING: _VersionOrBoundary = Union[Version, BoundaryVersion, None] @functools.total_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__ = ("_above", "inclusive", "version") def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: self.version = version self.inclusive = inclusive # Pre-bind a predicate "is parsed at or above this lower # bound?" for the hot filter / contains loops. One direct # call per check, no operator-dispatch chain. if version is None: self._above: Callable[[Version], bool] | None = None elif isinstance(version, BoundaryVersion): # >V produces an AFTER_POSTS lower bound; the upper-side # range of !=V produces an AFTER_LOCALS lower bound. if version.kind == BoundaryKind.AFTER_POSTS: self._above = _make_above_after_posts(version.version) else: self._above = _make_above_after_locals(version.version) elif inclusive: self._above = version.__le__ else: self._above = version.__lt__ def __eq__(self, other: object) -> bool: if not isinstance(other, LowerBound): return NotImplemented return self.version == other.version and self.inclusive == other.inclusive def __lt__(self, other: LowerBound) -> bool: if not isinstance(other, LowerBound): return NotImplemented # -inf < anything (except -inf itself). if self.version is None: return other.version is not None if other.version is None: return False if self.version != other.version: return self.version < other.version # [v < (v: inclusive starts earlier. return self.inclusive and not other.inclusive def __hash__(self) -> int: return hash((self.version, self.inclusive)) def __repr__(self) -> str: bracket = "[" if self.inclusive else "(" return f"<{self.__class__.__name__} {bracket}{self.version!r}>" @functools.total_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__ = ("_below", "inclusive", "version") def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: self.version = version self.inclusive = inclusive # Pre-bind a predicate "is parsed at or below this upper # bound?". See LowerBound for the rationale. if version is None: self._below: Callable[[Version], bool] | None = None elif isinstance(version, BoundaryVersion): # Standard specifiers only ever produce AFTER_LOCALS upper # bounds (from <=V / ==V / !=V with no local). if version.kind == BoundaryKind.AFTER_LOCALS: self._below = _make_below_after_locals(version.version) else: # An AFTER_POSTS upper is not produced by any specifier, but # range algebra reaches it: complementing ``>V`` flips the # ``AFTER_POSTS(V)`` lower into this upper bound. self._below = version.__ge__ elif inclusive: self._below = version.__ge__ else: self._below = version.__gt__ def __eq__(self, other: object) -> bool: if not isinstance(other, UpperBound): return NotImplemented return self.version == other.version and self.inclusive == other.inclusive def __lt__(self, other: UpperBound) -> bool: if not isinstance(other, UpperBound): return NotImplemented # Nothing < +inf (except +inf itself). if self.version is None: return False if other.version is None: return True if self.version != other.version: return self.version < other.version # v) < v]: exclusive ends earlier. return not self.inclusive and other.inclusive def __hash__(self) -> int: return hash((self.version, self.inclusive)) def __repr__(self) -> str: bracket = "]" if self.inclusive else ")" return f"<{self.__class__.__name__} {self.version!r}{bracket}>" if TYPE_CHECKING: #: A single contiguous interval as a (lower, upper) bound pair. Interval = tuple[LowerBound, UpperBound] NEG_INF: Final[LowerBound] = LowerBound(None, False) POS_INF: Final[UpperBound] = UpperBound(None, False) FULL_RANGE: Final[tuple[Interval]] = ((NEG_INF, POS_INF),) def trim_release(release: tuple[int, ...]) -> tuple[int, ...]: """Strip trailing zeros from a release tuple for normalized comparison.""" end = len(release) while end > 1 and release[end - 1] == 0: end -= 1 return release if end == len(release) else release[:end] def _next_prefix_dev0(version: Version) -> Version: """Smallest version in the next prefix: 1.2 -> 1.3.dev0.""" release = (*version.release[:-1], version.release[-1] + 1) return Version.from_parts(epoch=version.epoch, release=release, dev=0) def _base_dev0(version: Version) -> Version: """The .dev0 of a version's base release: 1.2 -> 1.2.dev0.""" return Version.from_parts(epoch=version.epoch, release=version.release, dev=0) def coerce_version(version: Version | str) -> Version | None: if not isinstance(version, Version): try: version = Version(version) except InvalidVersion: return None return version def _make_above_after_posts(version: Version) -> Callable[[Version], bool]: """Predicate ``parsed > AFTER_POSTS(V)`` for a lower bound. Per PEP 440, ``>V`` excludes V's post-releases unless V is itself a post-release. AFTER_POSTS sits above V and every V.postN (with or without local), and just below the next release. """ version_ge = version.__ge__ version_epoch = version.epoch version_pre = version.pre version_release_trimmed = trim_release(version.release) trimmed_length = len(version_release_trimmed) def above(parsed: Version) -> bool: if version_ge(parsed): return False # parsed > V cmpkey-wise: above the boundary iff NOT in V's # post family. if parsed.epoch != version_epoch: return True parsed_release = parsed.release if len(parsed_release) < trimmed_length: return True if parsed_release[:trimmed_length] != version_release_trimmed: return True for i in range(trimmed_length, len(parsed_release)): if parsed_release[i] != 0: return True if parsed.pre != version_pre: return True # Same release and pre as V: parsed is in V's post family (V itself, # V+local, or V.postN), which the boundary sits above. A V.devN # (different dev, no post) sorts before V and was already caught by # ``version_ge`` above, so the answer here is always "not above". return False return above def _make_above_after_locals(version: Version) -> Callable[[Version], bool]: """Predicate ``parsed > AFTER_LOCALS(V)`` for a lower bound. Used by the upper-side range of ``!=V`` (when V has no local segment). AFTER_LOCALS sits above V and every ``V+local`` but just below ``V.post0``. """ version_ge = version.__ge__ version_epoch = version.epoch version_pre = version.pre version_post = version.post version_dev = version.dev version_release_trimmed = trim_release(version.release) trimmed_length = len(version_release_trimmed) def above(parsed: Version) -> bool: if version_ge(parsed): return False # parsed > V cmpkey-wise: above the boundary iff NOT in V's # local family (same public version, any local segment). if parsed.epoch != version_epoch: return True parsed_release = parsed.release if len(parsed_release) < trimmed_length: return True if parsed_release[:trimmed_length] != version_release_trimmed: return True for i in range(trimmed_length, len(parsed_release)): if parsed_release[i] != 0: return True if parsed.pre != version_pre: return True if parsed.post != version_post: return True return parsed.dev != version_dev return above def _make_below_after_locals(version: Version) -> Callable[[Version], bool]: """Predicate ``parsed <= AFTER_LOCALS(V)`` for an upper bound. Used by ``<=V``, ``==V``, ``!=V`` (no local). ``parsed`` is at or below the boundary when it is at or below V cmpkey-wise, or when it is in V's local family. """ version_ge = version.__ge__ version_epoch = version.epoch version_pre = version.pre version_post = version.post version_dev = version.dev version_release_trimmed = trim_release(version.release) trimmed_length = len(version_release_trimmed) def below(parsed: Version) -> bool: if version_ge(parsed): return True # parsed > V cmpkey-wise: below the boundary iff in V's local # family. if parsed.epoch != version_epoch: return False parsed_release = parsed.release if len(parsed_release) < trimmed_length: return False if parsed_release[:trimmed_length] != version_release_trimmed: return False for i in range(trimmed_length, len(parsed_release)): if parsed_release[i] != 0: return False if parsed.pre != version_pre: return False if parsed.post != version_post: return False return parsed.dev == version_dev return below def least_version_above(boundary: BoundaryVersion) -> Version | None: """Smallest real version strictly above *boundary*, or ``None`` if none exists.""" base = boundary.version if boundary.kind == BoundaryKind.AFTER_LOCALS: # AFTER_LOCALS(V) sits just below V.post0, so its least successor is # V.post0.dev0 (V.dev(N+1) if V has a dev, V.post(N+1).dev0 if a post). if base.dev is not None: return base.__replace__(dev=base.dev + 1, local=None) next_post = (base.post + 1) if base.post is not None else 0 return base.__replace__(post=next_post, dev=0, local=None) # AFTER_POSTS(V): a pre-release V steps to the next pre-release's .dev0; # a final-release AFTER_POSTS has no least successor. if base.pre is not None: kind, number = base.pre return base.__replace__(pre=(kind, number + 1), post=None, dev=0, local=None) return None def range_is_empty(lower: LowerBound, upper: UpperBound) -> bool: """True when the range defined by *lower* and *upper* contains no versions. A boundary lower sits just below the next real version, so an ordered pair is still empty when the upper excludes that least successor: ``(AFTER_POSTS(1.0a1), 1.0a2.dev0)`` holds no version. """ if upper.version is None: return False if lower.version is None: # Nothing sorts below MIN_VERSION, so an exclusive upper at or below it # leaves an empty floor interval such as ``(-inf, 0.dev0)``. return ( not upper.inclusive and isinstance(upper.version, Version) and upper.version <= MIN_VERSION ) if isinstance(lower.version, BoundaryVersion): successor = least_version_above(lower.version) if successor is not None: if upper.version == successor: return not upper.inclusive return upper.version < successor if lower.version == upper.version: return not (lower.inclusive and upper.inclusive) return lower.version > upper.version def intersect_ranges( left: Sequence[Interval], right: Sequence[Interval], ) -> list[Interval]: """Intersect two sorted, non-overlapping range lists (two-pointer merge).""" result: list[Interval] = [] left_index = right_index = 0 while left_index < len(left) and right_index < len(right): left_lower, left_upper = left[left_index] right_lower, right_upper = right[right_index] lower = max(left_lower, right_lower) upper = min(left_upper, right_upper) if not range_is_empty(lower, upper): result.append((lower, upper)) # Advance whichever side has the smaller upper bound. if left_upper < right_upper: left_index += 1 else: right_index += 1 return result def filter_by_ranges( ranges: Sequence[Interval], iterable: Iterable[Any], key: Callable[[Any], Version | str] | None, prereleases: bool | None, region: Sequence[Interval] = (), ) -> Iterator[Any]: """Filter *iterable* against precomputed version *ranges*. With ``prereleases=None``, the PEP 440 default applies: pre-releases are excluded unless no final matches, in which case buffered pre-releases come out at the end. A pre-release inside the opt-in ``region`` is the exception: it is force-admitted in place, as ``prereleases=True`` would yield it. A force-admitted pre-release is not a final, so it never suppresses the buffer. """ if prereleases is None: prerelease_buffer: list[Any] = [] found_final = False if len(ranges) == 1: # Hot path: most specifiers and small SpecifierSets reduce to # a single contiguous range. lower, upper = ranges[0] above = lower._above below = upper._below for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue if above is not None and not above(parsed): continue if below is not None and not below(parsed): continue if not parsed.is_prerelease: found_final = True yield item elif region and matches_bounds_only(region, parsed): yield item elif not found_final: prerelease_buffer.append(item) if not found_final: yield from prerelease_buffer return for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue for lower, upper in ranges: above = lower._above if above is not None and not above(parsed): break below = upper._below if below is None or below(parsed): if not parsed.is_prerelease: found_final = True yield item elif region and matches_bounds_only(region, parsed): yield item elif not found_final: prerelease_buffer.append(item) break if not found_final: yield from prerelease_buffer return exclude_prereleases = prereleases is False if len(ranges) == 1: # Hot path: most specifiers and small SpecifierSets reduce to # a single contiguous range. lower, upper = ranges[0] above = lower._above below = upper._below for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue if exclude_prereleases and parsed.is_prerelease: continue if above is not None and not above(parsed): continue if below is None or below(parsed): yield item return for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: continue if exclude_prereleases and parsed.is_prerelease: continue for lower, upper in ranges: above = lower._above if above is not None and not above(parsed): break below = upper._below if below is None or below(parsed): yield item break def _nearest_release_above_prerelease(version: Version) -> Version: """Smallest non-pre-release at or above a pre-release *version*.""" if version.pre is not None: # An a/b/rc pre-release drops to its final release, which outranks # every post-release of that pre-release (1.0a1.post0 -> 1.0). return version.__replace__(pre=None, post=None, dev=None, local=None) # A dev-only release keeps its post-release (1.0.post0.dev0 -> 1.0.post0, # whose final 1.0 sorts below it). return version.__replace__(dev=None, local=None) def _lowest_release_at_or_above(value: Version | BoundaryVersion | None) -> Version: """Smallest non-pre-release version at or above *value*. ``None`` is the ``-inf`` floor, whose nearest non-pre-release is :data:`MIN_RELEASE`. """ if value is None: return MIN_RELEASE if isinstance(value, BoundaryVersion): inner_version = value.version if inner_version.is_prerelease: return _nearest_release_above_prerelease(inner_version) # AFTER_LOCALS(1.0) -> nearest non-pre is 1.0.post0 # AFTER_LOCALS(1.0.post0) -> nearest non-pre is 1.0.post1 next_post = (inner_version.post + 1) if inner_version.post is not None else 0 return inner_version.__replace__(post=next_post, local=None) if not value.is_prerelease: return value return _nearest_release_above_prerelease(value) def ranges_are_prerelease_only(ranges: Sequence[Interval]) -> bool: """True when every range in *ranges* contains only pre-releases. Used to detect unsatisfiable specifier sets when ``prereleases=False``: if every range is pre-release-only, every contained version is excluded. """ for lower, upper in ranges: nearest = _lowest_release_at_or_above(lower.version) if upper.version is None or nearest < upper.version: return False if nearest == upper.version and upper.inclusive: return False return True def wildcard_ranges(op: str, base: Version) -> list[Interval]: """Ranges for ==V.* and !=V.*. ==1.2.* -> [1.2.dev0, 1.3.dev0); !=1.2.* -> complement. """ lower = _base_dev0(base) upper = _next_prefix_dev0(base) if op == "==": return [(LowerBound(lower, True), UpperBound(upper, False))] # != return [ (NEG_INF, UpperBound(lower, False)), (LowerBound(upper, True), POS_INF), ] def standard_ranges(op: str, version: Version, has_local: bool) -> list[Interval]: """Ranges for the standard PEP 440 operators (no wildcard, no ===). *has_local* indicates whether the spec string included a ``+local`` segment; relevant only for ``==`` / ``!=`` to decide whether the upper bound includes V's local family. """ if op == ">=": return [(LowerBound(version, True), POS_INF)] if op == "<=": return [ ( NEG_INF, UpperBound(BoundaryVersion(version, BoundaryKind.AFTER_LOCALS), True), ) ] if op == ">": if version.dev is not None: # >V.devN: dev versions have no post-releases, so the # next real version is V.dev(N+1). lower_bound = version.__replace__(dev=version.dev + 1, local=None) return [(LowerBound(lower_bound, True), POS_INF)] if version.post is not None: # >V.postN: next real version is V.post(N+1).dev0. lower_bound = version.__replace__(post=version.post + 1, dev=0, local=None) return [(LowerBound(lower_bound, True), POS_INF)] # >V (final or pre-release V): exclude V itself, V+local, and # every V.postN per PEP 440. return [ ( LowerBound(BoundaryVersion(version, BoundaryKind.AFTER_POSTS), False), POS_INF, ) ] if op == "<": # list[Interval]: """Ranges for one specifier's ``(op, version_str)``. Dispatches between the wildcard and standard builders. ``version`` is the parsed ``version_str`` (its base, without the trailing ``.*``, for wildcards). ``===`` is not handled here; its match is a literal string compared in :mod:`packaging.specifiers`. """ if version_str.endswith(".*"): return wildcard_ranges(op, version) return standard_ranges(op, version, "+" in version_str) def intersect_specifier_bounds( per_specifier_ranges: Iterable[Sequence[Interval]], ) -> Sequence[Interval]: """Intersect each specifier's ranges into a single sequence. Short-circuits once the running intersection is empty, since no later specifier can revive it. Callers must pass at least one specifier. """ result: Sequence[Interval] | None = None for sub in per_specifier_ranges: if result is None: result = sub else: result = intersect_ranges(result, sub) if not result: break if result is None: # pragma: no cover - callers guard non-empty input raise RuntimeError("intersect_specifier_bounds called with no specifiers") return result def matches_bounds_only(ranges: Sequence[Interval], version: Version) -> bool: """Whether ``version`` falls within any of ``ranges``. The pure bounds membership test, for a single already-parsed version with no pre-release policy applied. ``ranges`` are sorted and non-overlapping, so a version below one range's lower bound is below every later range too. """ for lower, upper in ranges: above = lower._above if above is not None and not above(version): return False below = upper._below if below is None or below(version): return True return False def resolve_prereleases( configured: bool | None, autodetected: bool | None ) -> bool | None: """Resolve a specifier's effective default pre-release policy. An explicit ``configured`` value wins; otherwise an autodetected ``True`` propagates and anything else falls back to the PEP 440 default (``None``). """ if configured is not None: return configured if autodetected: return True return None ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4525542 packaging-26.3/src/packaging/_structures.py0000644000000000000000000000212515234171317015771 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=1785787087.4525542 packaging-26.3/src/packaging/_tokenizer.py0000644000000000000000000001270515234171317015565 0ustar00from __future__ import annotations import contextlib import re from dataclasses import dataclass from typing import TYPE_CHECKING, NoReturn from .specifiers import Specifier if TYPE_CHECKING: from collections.abc import Generator, Mapping @dataclass class Token: __slots__ = ("name", "position", "text") name: str text: str position: int class ParserSyntaxError(Exception): """The provided source text could not be parsed correctly.""" def __init__( self, message: str, *, source: str, span: tuple[int, int], ) -> None: self.span = span self.message = message self.source = source super().__init__() def __str__(self) -> str: marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" return f"{self.message}\n {self.source}\n {marker}" DEFAULT_RULES: dict[str, re.Pattern[str]] = { "LEFT_PARENTHESIS": re.compile(r"\("), "RIGHT_PARENTHESIS": re.compile(r"\)"), "LEFT_BRACKET": re.compile(r"\["), "RIGHT_BRACKET": re.compile(r"\]"), "SEMICOLON": re.compile(r";"), "COMMA": re.compile(r","), "QUOTED_STRING": re.compile( r""" ( ('[^']*') | ("[^"]*") ) """, re.VERBOSE, ), "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"), "BOOLOP": re.compile(r"\b(or|and)\b"), "IN": re.compile(r"\bin\b"), "NOT": re.compile(r"\bnot\b"), "VARIABLE": re.compile( r""" \b( python_version |python_full_version |os[._]name |sys[._]platform |platform_(release|system) |platform[._](version|machine|python_implementation) |python_implementation |implementation_(name|version) |extras? |dependency_groups )\b """, re.VERBOSE, ), "SPECIFIER": re.compile( Specifier._specifier_regex_str, re.VERBOSE | re.IGNORECASE, ), "AT": re.compile(r"\@"), "URL": re.compile(r"[^ \t]+"), "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), "WS": re.compile(r"[ \t]+"), "END": re.compile(r"\Z"), } class Tokenizer: """Context-sensitive token parsing. Provides methods to examine the input stream to check whether the next token matches. """ __slots__ = ("next_token", "position", "rules", "source") def __init__( self, source: str, *, rules: Mapping[str, re.Pattern[str]], ) -> None: self.source = source self.rules = rules self.next_token: Token | None = None self.position = 0 def consume(self, name: str) -> None: """Move beyond provided token name, if at current position.""" if self.check(name): self.read() def check(self, name: str, *, peek: bool = False) -> bool: """Check whether the next token has the provided name. By default, if the check succeeds, the token *must* be read before another check. If `peek` is set to `True`, the token is not loaded and would need to be checked again. """ assert self.next_token is None, ( f"Cannot check for {name!r}, already have {self.next_token!r}" ) assert name in self.rules, f"Unknown token name: {name!r}" expression = self.rules[name] match = expression.match(self.source, self.position) if match is None: return False if not peek: self.next_token = Token(name, match[0], self.position) return True def expect(self, name: str, *, expected: str) -> Token: """Expect a certain token name next, failing with a syntax error otherwise. The token is read and returned. """ if not self.check(name): raise self.raise_syntax_error(f"Expected {expected}") return self.read() def read(self) -> Token: """Consume the next token and return it.""" token = self.next_token assert token is not None self.position += len(token.text) self.next_token = None return token def raise_syntax_error( self, message: str, *, span_start: int | None = None, span_end: int | None = None, ) -> NoReturn: """Raise ParserSyntaxError at the given position.""" span = ( self.position if span_start is None else span_start, self.position if span_end is None else span_end, ) raise ParserSyntaxError( message, source=self.source, span=span, ) @contextlib.contextmanager def enclosing_tokens( self, open_token: str, close_token: str, *, around: str ) -> Generator[None, None, None]: if self.check(open_token): open_position = self.position self.read() else: open_position = None yield if open_position is None: return if not self.check(close_token): self.raise_syntax_error( f"Expected matching {close_token} for {open_token}, after {around}", span_start=open_position, ) self.read() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4527524 packaging-26.3/src/packaging/dependency_groups.py0000644000000000000000000002573015234171317017133 0ustar00from __future__ import annotations import re from collections.abc import Mapping, Sequence from .errors import _ErrorCollector from .requirements import InvalidRequirement, Requirement __all__ = [ "CyclicDependencyGroup", "DependencyGroupInclude", "DependencyGroupResolver", "DuplicateGroupNames", "InvalidDependencyGroupObject", "resolve_dependency_groups", ] def __dir__() -> list[str]: return __all__ # ----------- # Error Types # ----------- class DuplicateGroupNames(ValueError): """ The same dependency groups were defined twice, with different non-normalized names. .. versionadded:: 26.1 """ class CyclicDependencyGroup(ValueError): """ The dependency group includes form a cycle. .. versionadded:: 26.1 """ def __init__(self, requested_group: str, group: str, include_group: str) -> None: self.requested_group = requested_group self.group = group self.include_group = include_group if include_group == group: reason = f"{group} includes itself" else: reason = f"{include_group} -> {group}, {group} -> {include_group}" super().__init__( "Cyclic dependency group include while resolving " f"{requested_group}: {reason}" ) # Support pickling; ``args`` does not match ``__init__``'s signature. def __reduce__(self) -> tuple[type[CyclicDependencyGroup], tuple[str, str, str]]: return (self.__class__, (self.requested_group, self.group, self.include_group)) # in the PEP 735 spec, the tables in dependency group lists were described as # "Dependency Object Specifiers", but the only defined type of object was a # "Dependency Group Include" -- hence the naming of this error as "Object" class InvalidDependencyGroupObject(ValueError): """ A member of a dependency group was identified as a dict, but was not in a valid format. .. versionadded:: 26.1 """ # ------------------------ # Object Model & Interface # ------------------------ class DependencyGroupInclude: """ A reference to another dependency group by name. .. versionadded:: 26.1 """ __slots__ = ("include_group",) def __init__(self, include_group: str) -> None: """ Initialize a DependencyGroupInclude. :param include_group: The name of the group referred to by this include. """ self.include_group = include_group def __repr__(self) -> str: return f"{self.__class__.__name__}({self.include_group!r})" class DependencyGroupResolver: """ A resolver for Dependency Group data. This class handles caching, name normalization, cycle detection, and other parsing requirements. There are only two public methods for exploring the data: ``lookup()`` and ``resolve()``. :param dependency_groups: A mapping, as provided via pyproject ``[dependency-groups]``. .. versionadded:: 26.1 """ def __init__( self, dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], ) -> None: errors = _ErrorCollector() self.dependency_groups = _normalize_group_names(dependency_groups, errors) # a map of group names to parsed data self._parsed_groups: dict[ str, tuple[Requirement | DependencyGroupInclude, ...] ] = {} # a map of group names to their ancestors, used for cycle detection self._include_graph_ancestors: dict[str, tuple[str, ...]] = {} # a cache of completed resolutions to Requirement lists self._resolve_cache: dict[str, tuple[Requirement, ...]] = {} errors.finalize("[dependency-groups] data was invalid") def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]: """ Lookup a group name, returning the parsed dependency data for that group. This will not resolve includes. :param group: the name of the group to lookup """ group = _normalize_name(group) with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._parse_group(group, errors) def resolve(self, group: str) -> tuple[Requirement, ...]: """ Resolve a dependency group to a list of requirements. :param group: the name of the group to resolve """ group = _normalize_name(group) with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._resolve(group, group, errors) def _resolve( self, group: str, requested_group: str, errors: _ErrorCollector ) -> tuple[Requirement, ...]: """ This is a helper for cached resolution to strings. It preserves the name of the group which the user initially requested in order to present a clearer error in the event that a cycle is detected. :param group: The normalized name of the group to resolve. :param requested_group: The group which was used in the original, user-facing request. """ if group in self._resolve_cache: return self._resolve_cache[group] parsed = self._parse_group(group, errors) resolved_group = [] for item in parsed: if isinstance(item, Requirement): resolved_group.append(item) elif isinstance(item, DependencyGroupInclude): include_group = _normalize_name(item.include_group) # if a group is cyclic, record the error # otherwise, follow the include_group reference # # this allows us to examine all includes in a group, even in the # presence of errors if include_group in self._include_graph_ancestors.get(group, ()): errors.error( CyclicDependencyGroup( requested_group, group, item.include_group ) ) else: self._include_graph_ancestors[include_group] = ( *self._include_graph_ancestors.get(group, ()), group, ) resolved_group.extend( self._resolve(include_group, requested_group, errors) ) else: # pragma: no cover raise NotImplementedError( f"Invalid dependency group item after parse: {item}" ) # in the event that errors were detected, present the group as empty and do not # cache the result # this ensures that repeated access to a cyclic group will raise multiple errors if errors.errors: return () self._resolve_cache[group] = tuple(resolved_group) return self._resolve_cache[group] def _parse_group( self, group: str, errors: _ErrorCollector ) -> tuple[Requirement | DependencyGroupInclude, ...]: # short circuit -- never do the work twice if group in self._parsed_groups: return self._parsed_groups[group] if group not in self.dependency_groups: errors.error(LookupError(f"Dependency group '{group}' not found")) return () raw_group = self.dependency_groups[group] if isinstance(raw_group, str): errors.error( TypeError( f"Dependency group {group!r} contained a string rather than a list." ) ) return () if not isinstance(raw_group, Sequence): errors.error( TypeError(f"Dependency group {group!r} is not a sequence type.") ) return () elements: list[Requirement | DependencyGroupInclude] = [] for item in raw_group: if isinstance(item, str): # packaging.requirements.Requirement parsing ensures that this is a # valid PEP 508 Dependency Specifier. Collect InvalidRequirement # if it throws that. with errors.collect(InvalidRequirement): elements.append(Requirement(item)) elif isinstance(item, Mapping): if tuple(item.keys()) != ("include-group",): errors.error( InvalidDependencyGroupObject( f"Invalid dependency group item: {item!r}" ) ) else: include_group = item["include-group"] if not isinstance(include_group, str): msg = ( "Dependency group include-group value is not a string: " f"{item!r}" ) errors.error(TypeError(msg)) else: elements.append( DependencyGroupInclude(include_group=include_group) ) else: errors.error(TypeError(f"Invalid dependency group item: {item!r}")) if errors.errors: return () self._parsed_groups[group] = tuple(elements) return self._parsed_groups[group] # -------------------- # Functional Interface # -------------------- def resolve_dependency_groups( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str ) -> tuple[str, ...]: """ Resolve a dependency group to a tuple of requirements, as strings. :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table from ``pyproject.toml`` :param groups: the name of the group(s) to resolve .. versionadded:: 26.1 """ resolver = DependencyGroupResolver(dependency_groups) return tuple(str(r) for group in groups for r in resolver.resolve(group)) # ---------------- # internal helpers # ---------------- _NORMALIZE_PATTERN = re.compile(r"[-_.]+") def _normalize_name(name: str) -> str: return _NORMALIZE_PATTERN.sub("-", name).lower() def _normalize_group_names( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], errors: _ErrorCollector, ) -> dict[str, Sequence[str | Mapping[str, str]]]: original_names: dict[str, list[str]] = {} normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {} for group_name, value in dependency_groups.items(): normed_group_name = _normalize_name(group_name) original_names.setdefault(normed_group_name, []).append(group_name) normalized_groups[normed_group_name] = value for normed_name, names in original_names.items(): if len(names) > 1: errors.error( DuplicateGroupNames( "Duplicate dependency group names: " f"{normed_name} ({', '.join(names)})" ) ) return normalized_groups ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4527524 packaging-26.3/src/packaging/direct_url.py0000644000000000000000000002657515234171317015562 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 from urllib.parse import SplitResult if sys.version_info >= (3, 11): from typing import Self else: from typing_extensions import Self __all__ = [ "ArchiveInfo", "DirInfo", "DirectUrl", "DirectUrlValidationError", "VcsInfo", ] def __dir__() -> list[str]: return __all__ _T = TypeVar("_T") class _FromMappingProtocol(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) def _json_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return {key: value for key, value in data if value is not None} def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type): raise DirectUrlValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _DirectUrlRequiredKeyError(key) return value def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str ) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise DirectUrlValidationError(e, context=key) from e _PEP610_USER_PASS_ENV_VARS_REGEX = re.compile( r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$" ) def _strip_auth_from_netloc(netloc: str, safe_user_passwords: Collection[str]) -> str: if "@" not in netloc: return netloc user_pass, netloc_no_user_pass = netloc.rsplit("@", 1) if user_pass in safe_user_passwords: return netloc if _PEP610_USER_PASS_ENV_VARS_REGEX.match(user_pass): return netloc return netloc_no_user_pass def _strip_url(url: str, safe_user_passwords: Collection[str]) -> str: """url with user:password part removed unless it is formed with environment variables as specified in PEP 610, or it is a safe user:password such as `git`. """ parsed_url = urllib.parse.urlsplit(url) netloc = _strip_auth_from_netloc(parsed_url.netloc, safe_user_passwords) return urllib.parse.urlunsplit( ( parsed_url.scheme, netloc, parsed_url.path, parsed_url.query, parsed_url.fragment, ) ) def _file_url_has_absolute_path(parsed_url: SplitResult) -> bool: return parsed_url.path.startswith("/") class DirectUrlValidationError(Exception): """Raised when when input data is not spec-compliant. .. versionadded:: 26.1 """ context: str | None = None message: str def __init__( self, cause: str | Exception, *, context: str | None = None, ) -> None: if isinstance(cause, DirectUrlValidationError): if cause.context: self.context = ( f"{context}.{cause.context}" if context else cause.context ) else: self.context = context # pragma: no cover self.message = cause.message else: self.context = context self.message = str(cause) def __str__(self) -> str: if self.context: return f"{self.message} in {self.context!r}" return self.message class _DirectUrlRequiredKeyError(DirectUrlValidationError): def __init__(self, key: str) -> None: super().__init__("Missing required value", context=key) @dataclasses.dataclass(frozen=True, init=False) class VcsInfo: """The version control information of a :class:`DirectUrl`.""" vcs: str commit_id: str requested_revision: str | None = None def __init__( self, *, vcs: str, commit_id: str, requested_revision: str | None = None, ) -> None: object.__setattr__(self, "vcs", vcs) object.__setattr__(self, "commit_id", commit_id) object.__setattr__(self, "requested_revision", requested_revision) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: # We can't validate vcs value because is not closed. return cls( vcs=_get_required(d, str, "vcs"), requested_revision=_get(d, str, "requested_revision"), commit_id=_get_required(d, str, "commit_id"), ) @dataclasses.dataclass(frozen=True, init=False) class ArchiveInfo: """The archive information of a :class:`DirectUrl`.""" hashes: Mapping[str, str] | None = None def __init__( self, *, hashes: Mapping[str, str] | None = None, ) -> None: object.__setattr__(self, "hashes", hashes) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: hashes = _get(d, Mapping, "hashes") # type: ignore[type-abstract] if hashes is not None and not all(isinstance(h, str) for h in hashes.values()): raise DirectUrlValidationError( "Hash values must be strings", context="hashes" ) legacy_hash = _get(d, str, "hash") if legacy_hash is not None: if "=" not in legacy_hash: raise DirectUrlValidationError( "Invalid hash format (expected '=')", context="hash", ) hash_algorithm, hash_value = legacy_hash.split("=", 1) if hashes is None: # if `hashes` are not present, we can derive it from the legacy `hash` hashes = {hash_algorithm: hash_value} else: # if `hashes` are present, the legacy `hash` must match one of them if hash_algorithm not in hashes: raise DirectUrlValidationError( f"Algorithm {hash_algorithm!r} used in hash field " f"is not present in hashes field", context="hashes", ) if hashes[hash_algorithm] != hash_value: raise DirectUrlValidationError( f"Algorithm {hash_algorithm!r} used in hash field " f"has different value in hashes field", context="hash", ) return cls(hashes=hashes) @dataclasses.dataclass(frozen=True, init=False) class DirInfo: """The local directory information of a :class:`DirectUrl`.""" editable: bool | None = None def __init__( self, *, editable: bool | None = None, ) -> None: object.__setattr__(self, "editable", editable) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: return cls( editable=_get(d, bool, "editable"), ) @dataclasses.dataclass(frozen=True, init=False) class DirectUrl: """A class representing a direct URL. .. versionadded:: 26.1 """ url: str archive_info: ArchiveInfo | None = None vcs_info: VcsInfo | None = None dir_info: DirInfo | None = None subdirectory: str | None = None # XXX Path or str? def __init__( self, *, url: str, archive_info: ArchiveInfo | None = None, vcs_info: VcsInfo | None = None, dir_info: DirInfo | None = None, subdirectory: str | None = None, ) -> None: object.__setattr__(self, "url", url) object.__setattr__(self, "archive_info", archive_info) object.__setattr__(self, "vcs_info", vcs_info) object.__setattr__(self, "dir_info", dir_info) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: direct_url = cls( url=_get_required(d, str, "url"), archive_info=_get_object(d, ArchiveInfo, "archive_info"), vcs_info=_get_object(d, VcsInfo, "vcs_info"), dir_info=_get_object(d, DirInfo, "dir_info"), subdirectory=_get(d, str, "subdirectory"), ) if ( bool(direct_url.vcs_info) + bool(direct_url.archive_info) + bool(direct_url.dir_info) ) != 1: raise DirectUrlValidationError( "Exactly one of vcs_info, archive_info, dir_info must be present" ) if direct_url.dir_info is not None: parsed_url = urllib.parse.urlsplit(direct_url.url) if parsed_url.scheme != "file": raise DirectUrlValidationError( "URL scheme must be file:// when dir_info is present", context="url", ) if not _file_url_has_absolute_path(parsed_url): raise DirectUrlValidationError( "File URL must be absolute when dir_info is present", context="url", ) # XXX subdirectory must be relative, can we, should we validate that here? return direct_url @classmethod def from_dict(cls, d: Mapping[str, Any], /) -> Self: """Create and validate a DirectUrl instance from a JSON dictionary.""" return cls._from_dict(d) def to_dict( self, *, generate_legacy_hash: bool = False, strip_user_password: bool = True, safe_user_passwords: Collection[str] = ("git",), ) -> Mapping[str, Any]: """Convert the DirectUrl instance to a JSON dictionary. :param generate_legacy_hash: If True, include a legacy `hash` field in `archive_info` for backward compatibility with tools that don't support the `hashes` field. :param strip_user_password: If True, strip user:password from the URL unless it is formed with environment variables as specified in PEP 610, or it is a safe user:password such as `git`. :param safe_user_passwords: A collection of user:password strings that should not be stripped from the URL even if `strip_user_password` is True. """ res = dataclasses.asdict(self, dict_factory=_json_dict_factory) if generate_legacy_hash and self.archive_info and self.archive_info.hashes: hash_algorithm, hash_value = next(iter(self.archive_info.hashes.items())) res["archive_info"]["hash"] = f"{hash_algorithm}={hash_value}" if strip_user_password: res["url"] = _strip_url(self.url, safe_user_passwords) return res def validate(self) -> None: """Validate the DirectUrl instance against the specification. Raises :class:`DirectUrlValidationError` if invalid. """ self.from_dict(self.to_dict()) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4527524 packaging-26.3/src/packaging/errors.py0000644000000000000000000000517015234171317014726 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=1785787087.4527524 packaging-26.3/src/packaging/licenses/__init__.py0000644000000000000000000001726315234171317016764 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: Unknown license: 'invalid' """ def canonicalize_license_expression( raw_license_expression: str, ) -> NormalizedLicenseExpression: """ This function takes a valid License-Expression, and returns the normalized form of it. The return type is typed as :class:`NormalizedLicenseExpression`. This allows type checkers to help require that a string has passed through this function before use. :param str raw_license_expression: The License-Expression to canonicalize. :raises InvalidLicenseExpression: If the License-Expression is invalid due to an invalid/unknown license identifier or invalid syntax. .. doctest:: >>> from packaging.licenses import canonicalize_license_expression >>> canonicalize_license_expression("mit") 'MIT' >>> canonicalize_license_expression("mit and (apache-2.0 or bsd-2-clause)") 'MIT AND (Apache-2.0 OR BSD-2-Clause)' >>> canonicalize_license_expression("(mit") Traceback (most recent call last): ... InvalidLicenseExpression: Invalid license expression: '(mit' >>> canonicalize_license_expression("Use-it-after-midnight") Traceback (most recent call last): ... InvalidLicenseExpression: Unknown license: 'Use-it-after-midnight' """ if not raw_license_expression: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) # Pad any parentheses so tokenization can be achieved by merely splitting on # whitespace. license_expression = raw_license_expression.replace("(", " ( ").replace(")", " ) ") licenseref_prefix = "LicenseRef-" license_refs = { ref.lower(): "LicenseRef-" + ref[len(licenseref_prefix) :] for ref in license_expression.split() if ref.lower().startswith(licenseref_prefix.lower()) } # Normalize to lower case so we can look up licenses/exceptions # and so boolean operators are Python-compatible. license_expression = license_expression.lower() tokens = license_expression.split() # Rather than implementing a parenthesis/boolean logic parser, create an # expression that Python can parse. Everything that is not involved with the # grammar itself is replaced with the placeholder `False` and the resultant # expression should become a valid Python expression. python_tokens = [] for token in tokens: if token not in {"or", "and", "with", "(", ")"}: python_tokens.append("False") elif token == "with": python_tokens.append("or") elif ( token == "(" and python_tokens and python_tokens[-1] not in {"or", "and", "("} ) or (token == ")" and python_tokens and python_tokens[-1] == "("): message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) else: python_tokens.append(token) python_expression = " ".join(python_tokens) try: compile(python_expression, "", "eval") except SyntaxError: message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) from None # Take a final pass to check for unknown licenses/exceptions. normalized_tokens = [] last_license_start = False for index, token in enumerate(tokens): if token in {"or", "and", "with", "(", ")"}: if token == "with" and ( not last_license_start or index + 1 == len(tokens) or tokens[index + 1] in {"or", "and", "with", "(", ")"} ): message = f"Invalid license expression: {raw_license_expression!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(token.upper()) last_license_start = False continue if normalized_tokens and normalized_tokens[-1] == "WITH": if token not in EXCEPTIONS: message = f"Unknown license exception: {token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(EXCEPTIONS[token]["id"]) last_license_start = False else: if token.endswith("+"): final_token = token[:-1] suffix = "+" else: final_token = token suffix = "" if final_token.startswith("licenseref-"): license_ref_id = final_token[len("licenseref-") :] if suffix or not license_ref_allowed.match(license_ref_id): message = f"Invalid licenseref: {token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(license_refs[final_token]) else: if final_token not in LICENSES: message = f"Unknown license: {final_token!r}" raise InvalidLicenseExpression(message) normalized_tokens.append(LICENSES[final_token]["id"] + suffix) last_license_start = True normalized_expression = " ".join(normalized_tokens) return cast( "NormalizedLicenseExpression", normalized_expression.replace("( ", "(").replace(" )", ")"), ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4533734 packaging-26.3/src/packaging/licenses/_spdx.py0000644000000000000000000014366215234171317016345 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=1785787087.4533734 packaging-26.3/src/packaging/markers.py0000644000000000000000000005011215234171317015052 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 functools import operator import os import platform import sys from collections.abc import Set as AbstractSet from typing import TYPE_CHECKING, Callable, Literal, 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 if TYPE_CHECKING: from collections.abc import Mapping __all__ = [ "Environment", "EvaluateContext", "InvalidMarker", "Marker", "UndefinedComparison", "UndefinedEnvironmentName", "default_environment", ] def __dir__() -> list[str]: return __all__ Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] EvaluateContext = Literal["metadata", "lock_file", "requirement"] """A ``typing.Literal`` enumerating valid marker evaluation contexts. Valid values for the ``context`` passed to :meth:`Marker.evaluate` are: * ``"metadata"`` (for core metadata; default) * ``"lock_file"`` (for lock files) * ``"requirement"`` (i.e. all other situations) .. versionadded:: 25.0 """ MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} MARKERS_REQUIRING_VERSION = { "implementation_version", "platform_release", "python_full_version", "python_version", } class InvalidMarker(ValueError): """Raised when attempting to create a :class:`Marker` from invalid input. This error indicates that the given marker string does not conform to the :ref:`specification of dependency specifiers `. """ 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(KeyError): """Raised when evaluating a marker that references a missing environment key. Subclasses :class:`KeyError` so that code catching the bare ``KeyError`` that a missing environment lookup historically produced keeps working. .. versionchanged:: 26.3 Now subclasses :class:`KeyError` (was :class:`ValueError`) and is raised by :meth:`Marker.evaluate` for missing environment keys, where a bare ``KeyError`` was raised before. """ class Environment(TypedDict): """ A dictionary that represents a Python environment as captured by :func:`default_environment`. All fields are required. """ implementation_name: str """The implementation's identifier, e.g. ``'cpython'``.""" implementation_version: str """ The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or ``'7.3.13'`` for PyPy3.10 v7.3.13. """ os_name: str """ The value of :py:data:`os.name`. The name of the operating system dependent module imported, e.g. ``'posix'``. """ platform_machine: str """ Returns the machine type, e.g. ``'i386'``. An empty string if the value cannot be determined. """ platform_release: str """ The system's release, e.g. ``'2.2.0'`` or ``'NT'``. An empty string if the value cannot be determined. """ platform_system: str """ The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. An empty string if the value cannot be determined. """ platform_version: str """ The system's release version, e.g. ``'#3 on degas'``. An empty string if the value cannot be determined. """ python_full_version: str """ The Python version as string ``'major.minor.patchlevel'``. Note that unlike the Python :py:data:`sys.version`, this value will always include the patchlevel (it defaults to 0). """ platform_python_implementation: str """ A string identifying the Python implementation, e.g. ``'CPython'``. """ python_version: str """The Python version as string ``'major.minor'``.""" sys_platform: str """ This string contains a platform identifier that can be used to append platform-specific components to :py:data:`sys.path`, for instance. For Unix systems, except on Linux and AIX, this is the lowercased OS name as returned by ``uname -s`` with the first part of the version as returned by ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python was built. """ def _normalize_extras( result: MarkerList | MarkerAtom | str, ) -> MarkerList | MarkerAtom | str: if isinstance(result, list): return [_normalize_extras(r) for r in result] if not isinstance(result, tuple): return result lhs, op, rhs = result if isinstance(lhs, Variable) and lhs.value == "extra" and isinstance(rhs, Value): normalized_extra = canonicalize_name(rhs.value) rhs = Value(normalized_extra) elif isinstance(rhs, Variable) and rhs.value == "extra" and isinstance(lhs, Value): normalized_extra = canonicalize_name(lhs.value) lhs = Value(normalized_extra) elif ( isinstance(rhs, Variable) and rhs.value in MARKERS_ALLOWING_SET and isinstance(lhs, Value) ): # PEP 685 (extras) / PEP 735 (dependency_groups): the set-valued membership # literal must also be normalized. evaluate() already canonicalizes both # operands for these keys (see _normalize), so normalizing the literal at # parse time keeps __str__/__eq__/__hash__ consistent with evaluate() -- e.g. # Marker('"Foo" in extras') and Marker('"foo" in extras') must compare and # hash equal (the membership variable is always the right-hand operand). lhs = Value(canonicalize_name(lhs.value)) return lhs, op, rhs def _normalize_extra_values(results: MarkerList) -> MarkerList: """ Normalize extra values. """ return [_normalize_extras(r) for r in results] def _format_marker( marker: list[str] | MarkerAtom | str, first: bool | None = True ) -> str: assert isinstance(marker, (list, tuple, str)) # Unwrap a redundant [[...]] wrapper, but keep the nesting context so a # nested group keeps the parentheses its and/or precedence needs. if ( isinstance(marker, list) and len(marker) == 1 and isinstance(marker[0], (list, tuple)) ): return _format_marker(marker[0], first=first) if isinstance(marker, list): inner = (_format_marker(m, first=False) for m in marker) if first: return " ".join(inner) else: return "(" + " ".join(inner) + ")" elif isinstance(marker, tuple): return " ".join([m.serialize() for m in marker]) else: return marker _operators: dict[str, Operator] = { "in": lambda lhs, rhs: lhs in rhs, "not in": lambda lhs, rhs: lhs not in rhs, "<": lambda _lhs, _rhs: False, "<=": operator.eq, "==": operator.eq, "!=": operator.ne, ">=": operator.eq, ">": lambda _lhs, _rhs: False, } def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool: op_str = op.serialize() if key in MARKERS_REQUIRING_VERSION: try: spec = Specifier(f"{op_str}{rhs}") except InvalidSpecifier: pass else: return spec.contains(lhs, prereleases=True) oper: Operator | None = _operators.get(op_str) if oper is None: raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") return oper(lhs, rhs) def _normalize( lhs: str, rhs: str | AbstractSet[str], key: str ) -> tuple[str, str | AbstractSet[str]]: # PEP 685 - Comparison of extra names for optional distribution dependencies # https://peps.python.org/pep-0685/ # > When comparing extra names, tools MUST normalize the names being # > compared using the semantics outlined in PEP 503 for names if key == "extra": assert isinstance(rhs, str), "extra value must be a string" # Both sides are normalized at this point already return (lhs, rhs) if key in MARKERS_ALLOWING_SET: if isinstance(rhs, str): # pragma: no cover return (canonicalize_name(lhs), canonicalize_name(rhs)) else: return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs}) # other environment markers don't have such standards return lhs, rhs def _lookup_environment( environment: dict[str, str | AbstractSet[str]], key: str ) -> str | AbstractSet[str]: try: return environment[key] except KeyError: raise UndefinedEnvironmentName(key) from None def _evaluate_markers( markers: MarkerList, environment: dict[str, str | AbstractSet[str]] ) -> bool: groups: list[list[bool]] = [[]] for marker in markers: if isinstance(marker, list): groups[-1].append(_evaluate_markers(marker, environment)) elif isinstance(marker, tuple): lhs, op, rhs = marker if isinstance(lhs, Variable): environment_key = lhs.value lhs_value = _lookup_environment(environment, environment_key) rhs_value = rhs.value else: lhs_value = lhs.value environment_key = rhs.value rhs_value = _lookup_environment(environment, environment_key) if not isinstance(lhs_value, str): raise UndefinedComparison( f"Set-valued marker {environment_key!r} can only be used " f'with the membership form (e.g. "" in ' f"{environment_key}); it cannot appear on the left-hand " f"side of {op.serialize()!r}." ) lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key)) elif marker == "or": groups.append([]) elif marker == "and": pass else: # pragma: nocover raise TypeError(f"Unexpected marker {marker!r}") return any(all(item) for item in groups) def _format_full_version(info: sys._version_info) -> str: version = f"{info.major}.{info.minor}.{info.micro}" kind = info.releaselevel if kind != "final": version += kind[0] + str(info.serial) return version @functools.cache def _cached_default_environment() -> Environment: """Build the default marker environment for the current Python process. The values are derived from process-constant data (the running interpreter and the host platform), so this is cached and built only once. The result is shared between callers and must never be mutated; :func:`default_environment` returns a fresh copy. """ iver = _format_full_version(sys.implementation.version) implementation_name = sys.implementation.name return { "implementation_name": implementation_name, "implementation_version": iver, "os_name": os.name, "platform_machine": platform.machine(), "platform_release": platform.release(), "platform_system": platform.system(), "platform_version": platform.version(), "python_full_version": platform.python_version(), "platform_python_implementation": platform.python_implementation(), "python_version": ".".join(platform.python_version_tuple()[:2]), "sys_platform": sys.platform, } def default_environment() -> Environment: """Return the default marker environment for the current Python process. This is the base environment used by :meth:`Marker.evaluate`. A fresh copy is returned on every call so callers may freely mutate the result; a shallow copy suffices because all values are immutable strings. .. versionchanged:: 26.3 The environment is computed once per process and cached, since it is derived from process-constant data. Patching ``platform``/``sys``/``os`` after the first call has no effect; pass an explicit ``environment`` to :meth:`Marker.evaluate` to evaluate against different values. """ return cast("Environment", dict(_cached_default_environment())) class Marker: """Represents a parsed dependency marker expression. Marker expressions are parsed according to the :ref:`specification of dependency specifiers `. :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: """Combine this marker with another using ``and``. .. versionadded:: 26.1 """ if not isinstance(other, Marker): return NotImplemented return self._from_markers([self._markers, "and", other._markers]) def __or__(self, other: Marker) -> Marker: """Combine this marker with another using ``or``. .. versionadded:: 26.1 """ if not isinstance(other, Marker): return NotImplemented return self._from_markers([self._markers, "or", other._markers]) def evaluate( self, environment: Mapping[str, str | AbstractSet[str]] | None = None, context: EvaluateContext = "metadata", ) -> bool: """Evaluate a marker. Return the boolean from evaluating this marker against the environment. The environment is determined from the current Python process unless passed in explicitly. :param environment: Mapping containing keys and values to override the detected environment. :param EvaluateContext context: The context in which the marker is evaluated, which influences what marker names are considered valid. Accepted values are ``"metadata"`` (for core metadata; default), ``"lock_file"``, and ``"requirement"`` (i.e. all other situations). :raises UndefinedComparison: If the marker uses a comparison on values that are not valid versions per the :ref:`specification of version specifiers `. :raises UndefinedEnvironmentName: If the marker references a value that is missing from the evaluation environment. :returns: ``True`` if the marker matches, otherwise ``False``. .. versionchanged:: 25.0 Added the ``context`` parameter, which influences which marker names are considered valid. """ current_environment = cast( "dict[str, str | AbstractSet[str]]", default_environment() ) if context == "lock_file": current_environment |= { "extras": frozenset(), "dependency_groups": frozenset(), } elif context == "metadata": current_environment["extra"] = "" if environment is not None: current_environment |= environment if "extra" in current_environment: # The API used to allow setting extra to None. We need to handle # this case for backwards compatibility. Also skip running # normalize name if extra is empty. extra = cast("str | None", current_environment["extra"]) current_environment["extra"] = canonicalize_name(extra) if extra else "" return _evaluate_markers( self._markers, _repair_python_full_version(current_environment) ) def _pep440_python_full_version(python_full_version: str) -> str: """ Work around platform.python_version() returning something that is not PEP 440 compliant for non-tagged Python builds. """ if python_full_version.endswith("+"): return f"{python_full_version}local" return python_full_version def _repair_python_full_version( env: dict[str, str | AbstractSet[str]], ) -> dict[str, str | AbstractSet[str]]: """ Work around platform.python_version() returning something that is not PEP 440 compliant for non-tagged Python builds. """ python_full_version = cast("str", env["python_full_version"]) env["python_full_version"] = _pep440_python_full_version(python_full_version) return env ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4533734 packaging-26.3/src/packaging/metadata.py0000644000000000000000000012211315234171317015167 0ustar00from __future__ import annotations import email.header import email.message import email.parser import email.policy import keyword import pathlib import re 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 from .version import Version T = typing.TypeVar("T") __all__ = [ "ExceptionGroup", # Keep this for a bit (makes mypy happy w/ 26.0 compat) "InvalidMetadata", "Metadata", "RFC822Message", "RFC822Policy", "RawMetadata", "parse_email", ] def __dir__() -> list[str]: return __all__ class InvalidMetadata(ValueError): """A metadata field contains invalid data. .. versionadded:: 23.2 """ field: str """The name of the field that contains invalid data.""" def __init__(self, field: str, message: str) -> None: self.field = field super().__init__(message) # Support pickling; ``args`` does not match ``__init__``'s signature. def __reduce__(self) -> tuple[type[InvalidMetadata], tuple[str, str]]: return (self.__class__, (self.field, self.args[0])) # The RawMetadata class attempts to make as few assumptions about the underlying # serialization formats as possible. The idea is that as long as a serialization # formats offer some very basic primitives in *some* way then we can support # serializing to and from that format. class RawMetadata(TypedDict, total=False): """A dictionary of raw core metadata. Each field in core metadata maps to a key of this dictionary (when data is provided). The key is lower-case and underscores are used instead of dashes compared to the equivalent core metadata field. Any core metadata field that can be specified multiple times or can hold multiple values in a single field have a key with a plural name. See :class:`Metadata` whose attributes match the keys of this dictionary. Core metadata fields that can be specified multiple times are stored as a list or dict depending on which is appropriate for the field. Any fields which hold multiple values in a single field are stored as a list. All fields are considered optional. """ # Metadata 1.0 - PEP 241 metadata_version: str name: str version: str platforms: list[str] summary: str description: str keywords: list[str] home_page: str author: str author_email: str license: str # Metadata 1.1 - PEP 314 supported_platforms: list[str] download_url: str classifiers: list[str] requires: list[str] provides: list[str] obsoletes: list[str] # Metadata 1.2 - PEP 345 maintainer: str maintainer_email: str requires_dist: list[str] provides_dist: list[str] obsoletes_dist: list[str] requires_python: str requires_external: list[str] project_urls: dict[str, str] # Metadata 2.0 # PEP 426 attempted to completely revamp the metadata format # but got stuck without ever being able to build consensus on # it and ultimately ended up withdrawn. # # However, a number of tools had started emitting METADATA with # `2.0` Metadata-Version, so for historical reasons, this version # was skipped. # Metadata 2.1 - PEP 566 description_content_type: str provides_extra: list[str] # Metadata 2.2 - PEP 643 dynamic: list[str] # Metadata 2.3 - PEP 685 # No new fields were added in PEP 685, just some edge case were # tightened up to provide better interoperability. # Metadata 2.4 - PEP 639 license_expression: str """.. versionadded:: 24.2""" license_files: list[str] """.. versionadded:: 24.2""" # Metadata 2.5 - PEP 794 import_names: list[str] """.. versionadded:: 26.0""" import_namespaces: list[str] """.. versionadded:: 26.0""" # Metadata 2.6 - PEP 808 (no new fields, behavior change for Dynamic) # 'keywords' is special as it's a string in the core metadata spec, but we # represent it as a list. _STRING_FIELDS = { "author", "author_email", "description", "description_content_type", "download_url", "home_page", "license", "license_expression", "maintainer", "maintainer_email", "metadata_version", "name", "requires_python", "summary", "version", } _LIST_FIELDS = { "classifiers", "dynamic", "license_files", "obsoletes", "obsoletes_dist", "platforms", "provides", "provides_dist", "provides_extra", "requires", "requires_dist", "requires_external", "supported_platforms", "import_names", "import_namespaces", } _DICT_FIELDS = { "project_urls", } def _parse_keywords(data: str) -> list[str]: """Split a string of comma-separated keywords into a list of keywords.""" return [k.strip() for k in data.split(",")] def _parse_project_urls(data: list[str]) -> dict[str, str]: """Parse a list of label/URL string pairings separated by a comma.""" urls = {} for pair in data: # Our logic is slightly tricky here as we want to try and do # *something* reasonable with malformed data. # # The main thing that we have to worry about, is data that does # not have a ',' at all to split the label from the Value. There # isn't a singular right answer here, and we will fail validation # later on (if the caller is validating) so it doesn't *really* # matter, but since the missing value has to be an empty str # and our return value is dict[str, str], if we let the key # be the missing value, then they'd have multiple '' values that # overwrite each other in a accumulating dict. # # The other potential issue is that it's possible to have the # same label multiple times in the metadata, with no solid "right" # answer with what to do in that case. As such, we'll do the only # thing we can, which is treat the field as unparsable and add it # to our list of unparsed fields. # # TODO: The spec doesn't say anything about if the keys should be # considered case sensitive or not... logically they should # be case-preserving and case-insensitive, but doing that # would open up more cases where we might have duplicate # entries. label, _, url = (s.strip() for s in pair.partition(",")) if label in urls: # The label already exists in our set of urls, so this field # is unparsable, and we can just add the whole thing to our # unparsable data and stop processing it. raise KeyError("duplicate labels in project urls") urls[label] = url return urls def _get_payload(msg: email.message.Message, source: bytes | str) -> str: """Get the body of the message.""" # If our source is a str, then our caller has managed encodings for us, # and we don't need to deal with it. if isinstance(source, str): payload = msg.get_payload() # A multipart payload makes get_payload() return a list of messages # rather than a str; route it to ``unparsed``. if not isinstance(payload, str): raise ValueError("payload is not a string") # noqa: TRY004 return payload # If our source is a bytes, then we're managing the encoding and we need # to deal with it. else: bpayload = msg.get_payload(decode=True) # A multipart payload makes get_payload(decode=True) return None; # route it to ``unparsed``. if not isinstance(bpayload, bytes): raise ValueError("payload in an invalid encoding") # noqa: TRY004 try: return bpayload.decode("utf8", "strict") except UnicodeDecodeError as exc: raise ValueError("payload in an invalid encoding") from exc # The various parse_FORMAT functions here are intended to be as lenient as # possible in their parsing, while still returning a correctly typed # RawMetadata. # # To aid in this, we also generally want to do as little touching of the # data as possible, except where there are possibly some historic holdovers # that make valid data awkward to work with. # # While this is a lower level, intermediate format than our ``Metadata`` # class, some light touch ups can make a massive difference in usability. # Map METADATA fields to RawMetadata. _EMAIL_TO_RAW_MAPPING = { "author": "author", "author-email": "author_email", "classifier": "classifiers", "description": "description", "description-content-type": "description_content_type", "download-url": "download_url", "dynamic": "dynamic", "home-page": "home_page", "import-name": "import_names", "import-namespace": "import_namespaces", "keywords": "keywords", "license": "license", "license-expression": "license_expression", "license-file": "license_files", "maintainer": "maintainer", "maintainer-email": "maintainer_email", "metadata-version": "metadata_version", "name": "name", "obsoletes": "obsoletes", "obsoletes-dist": "obsoletes_dist", "platform": "platforms", "project-url": "project_urls", "provides": "provides", "provides-dist": "provides_dist", "provides-extra": "provides_extra", "requires": "requires", "requires-dist": "requires_dist", "requires-external": "requires_external", "requires-python": "requires_python", "summary": "summary", "supported-platform": "supported_platforms", "version": "version", } _RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} # A bare "\r" makes the email generator raise ``HeaderWriteError``, and on # CPython releases without the CVE-2024-6923 fix any ``str.splitlines`` # boundary ends the header line, so fold all of them, not just "\n". _LINE_BOUNDARY_RE = re.compile(r"\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]") # This class is for writing RFC822 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. .. versionadded:: 26.0 """ utf8 = True mangle_from_ = False max_line_length = 0 def header_store_parse(self, name: str, value: str) -> tuple[str, str]: size = len(name) + 2 value = _LINE_BOUNDARY_RE.sub("\n" + " " * size, value) return (name, value) # This class is for writing RFC822 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()`. .. versionadded:: 26.0 """ def __init__(self) -> None: super().__init__(policy=RFC822Policy()) def as_bytes( self, unixfrom: bool = False, policy: email.policy.Policy | None = None ) -> bytes: """ Return the bytes representation of the message. This handles unicode encoding. """ return self.as_string(unixfrom, policy=policy).encode("utf-8") def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). This function returns a two-item tuple of dicts. The first dict is of recognized fields from the core metadata specification. Fields that can be parsed and translated into Python's built-in types are converted appropriately. All other fields are left as-is. Fields that are allowed to appear multiple times are stored as lists. The second dict contains all other fields from the metadata. This includes any unrecognized fields. It also includes any fields which are expected to be parsed into a built-in type but were not formatted appropriately. Finally, any fields that are expected to appear only once but are repeated are included in this dict. """ raw: dict[str, str | list[str] | dict[str, str]] = {} unparsed: dict[str, list[str]] = {} if isinstance(data, str): parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) else: parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) # We have to wrap parsed.keys() in a set, because in the case of multiple # values for a key (a list), the key will appear multiple times in the # list of keys, but we're avoiding that by using get_all(). for name_with_case in frozenset(parsed.keys()): # Header names in RFC are case insensitive, so we'll normalize to all # lower case to make comparisons easier. name = name_with_case.lower() # We use get_all() here, even for fields that aren't multiple use, # because otherwise someone could have e.g. two Name fields, and we # would just silently ignore it rather than doing something about it. headers = parsed.get_all(name) or [] # The way the email module works when parsing bytes is that it # unconditionally decodes the bytes as ascii using the surrogateescape # handler. When you pull that data back out (such as with get_all() ), # it looks to see if the str has any surrogate escapes, and if it does # it wraps it in a Header object instead of returning the string. # # As such, we'll look for those Header objects, and fix up the encoding. value = [] # Flag if we have run into any issues processing the headers, thus # signalling that the data belongs in 'unparsed'. valid_encoding = True for h in headers: # It's unclear if this can return more types than just a Header or # a str, so we'll just assert here to make sure. assert isinstance(h, (email.header.Header, str)) # If it's a header object, we need to do our little dance to get # the real data out of it. In cases where there is invalid data # we're going to end up with mojibake, but there's no obvious, good # way around that without reimplementing parts of the Header object # ourselves. # # That should be fine since, if mojibacked happens, this key is # going into the unparsed dict anyways. if isinstance(h, email.header.Header): # The Header object stores it's data as chunks, and each chunk # can be independently encoded, so we'll need to check each # of them. chunks: list[tuple[bytes, str | None]] = [] for binary, _encoding in email.header.decode_header(h): try: binary.decode("utf8", "strict") except UnicodeDecodeError: # Enable mojibake. encoding = "latin1" valid_encoding = False else: encoding = "utf8" chunks.append((binary, encoding)) # Turn our chunks back into a Header object, then let that # Header object do the right thing to turn them into a # string for us. value.append(str(email.header.make_header(chunks))) # This is already a string, so just add it. else: value.append(h) # We've processed all of our values to get them into a list of str, # but we may have mojibake data, in which case this is an unparsed # field. if not valid_encoding: unparsed[name] = value continue raw_name = _EMAIL_TO_RAW_MAPPING.get(name) if raw_name is None: # This is a bit of a weird situation, we've encountered a key that # we don't know what it means, so we don't know whether it's meant # to be a list or not. # # Since we can't really tell one way or another, we'll just leave it # as a list, even though it may be a single item list, because that's # what makes the most sense for email headers. unparsed[name] = value continue # If this is one of our string fields, then we'll check to see if our # value is a list of a single item. If it is then we'll assume that # it was emitted as a single string, and unwrap the str from inside # the list. # # If it's any other kind of data, then we haven't the faintest clue # what we should parse it as, and we have to just add it to our list # of unparsed stuff. if raw_name in _STRING_FIELDS and len(value) == 1: raw[raw_name] = value[0] # If this is import_names, we need to special case the empty field # case, which converts to an empty list instead of None. We can't let # the empty case slip through, as it will fail validation. elif raw_name == "import_names" and value == [""]: raw[raw_name] = [] # If this is one of our list of string fields, then we can just assign # the value, since email *only* has strings, and our get_all() call # above ensures that this is a list. elif raw_name in _LIST_FIELDS: raw[raw_name] = value # Special Case: Keywords # The keywords field is implemented in the metadata spec as a str, # but it conceptually is a list of strings, and is serialized using # ", ".join(keywords), so we'll do some light data massaging to turn # this into what it logically is. elif raw_name == "keywords" and len(value) == 1: raw[raw_name] = _parse_keywords(value[0]) # Special Case: Project-URL # The project urls is implemented in the metadata spec as a list of # specially-formatted strings that represent a key and a value, which # is fundamentally a mapping, however the email format doesn't support # mappings in a sane way, so it was crammed into a list of strings # instead. # # We will do a little light data massaging to turn this into a map as # it logically should be. elif raw_name == "project_urls": try: raw[raw_name] = _parse_project_urls(value) except KeyError: unparsed[name] = value # Nothing that we've done has managed to parse this, so it'll just # throw it in our unparsable data and move on. else: unparsed[name] = value # We need to support getting the Description from the message payload in # addition to getting it from the the headers. This does mean, though, there # is the possibility of it being set both ways, in which case we put both # in 'unparsed' since we don't know which is right. try: payload = _get_payload(parsed, data) except ValueError: unparsed.setdefault("description", []).append( parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] ) else: if payload: # Check to see if we've already got a description, if so then both # it, and this body move to unparsable. if "description" in raw: description_header = cast("str", raw.pop("description")) unparsed.setdefault("description", []).extend( [description_header, payload] ) elif "description" in unparsed: unparsed["description"].append(payload) else: raw["description"] = payload # We need to cast our `raw` to a metadata, because a TypedDict only support # literal key names, but we're computing our key names on purpose, but the # way this function is implemented, our `TypedDict` can only have valid key # names. return cast("RawMetadata", raw), unparsed _NOT_FOUND = object() # Keep the two values in sync. _VALID_METADATA_VERSIONS = [ "1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6", ] _MetadataVersion = Literal[ "1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6" ] _REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) class _Validator(Generic[T]): """Validate a metadata field. All _process_*() methods correspond to a core metadata field. The method is called with the field's raw value. If the raw value is valid it is returned in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause as appropriate). """ name: str raw_name: str added: _MetadataVersion def __init__( self, *, added: _MetadataVersion = "1.0", ) -> None: self.added = added def __set_name__(self, _owner: Metadata, name: str) -> None: self.name = name self.raw_name = _RAW_TO_EMAIL_MAPPING[name] def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: # With Python 3.8, the caching can be replaced with functools.cached_property(). # No need to check the cache as attribute lookup will resolve into the # instance's __dict__ before __get__ is called. cache = instance.__dict__ value = instance._raw.get(self.name) # To make the _process_* methods easier, we'll check if the value is None # and if this field is NOT a required attribute, and if both of those # things are true, we'll skip the the converter. This will mean that the # converters never have to deal with the None union. if self.name in _REQUIRED_ATTRS or value is not None: try: converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") except AttributeError: pass else: value = converter(value) cache[self.name] = value try: del instance._raw[self.name] # type: ignore[misc] except KeyError: pass return cast("T", value) def _invalid_metadata( self, msg: str, cause: Exception | None = None ) -> InvalidMetadata: exc = InvalidMetadata(self.raw_name, msg) exc.__cause__ = cause return exc def _process_metadata_version(self, value: str) -> _MetadataVersion: # Implicitly makes Metadata-Version required. if value not in _VALID_METADATA_VERSIONS: raise self._invalid_metadata(f"{value!r} is not a valid metadata version") return cast("_MetadataVersion", value) def _process_name(self, value: str) -> str: if not value: raise self._invalid_metadata(f"{self.raw_name!r} is a required field") # Validate the name as a side-effect. try: utils.canonicalize_name(value, validate=True) except utils.InvalidName as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc else: return value def _process_version(self, value: str) -> Version: if not value: raise self._invalid_metadata(f"{self.raw_name!r} is a required field") try: return version_module.parse(value) except version_module.InvalidVersion as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc def _process_summary(self, value: str) -> str: """Check the field contains no line breaks.""" if _LINE_BOUNDARY_RE.search(value): raise self._invalid_metadata(f"{self.raw_name!r} must be a single line") return value def _process_description_content_type(self, value: str) -> str: content_types = {"text/plain", "text/x-rst", "text/markdown"} invalid_msg = ( f"{self.raw_name!r} must be one of {list(content_types)}, not {value!r}" ) message = email.message.EmailMessage() try: message["content-type"] = value # The email parser can raise IndexError on malformed RFC 2231 # parameters such as "text/plain; x*". except (ValueError, IndexError) as exc: msg = f"{value!r} is not a valid content type for {self.raw_name!r}" raise self._invalid_metadata(msg, cause=exc) from exc content_type_header = message["content-type"] if content_type_header.defects: defect = content_type_header.defects[0] msg = ( f"{value!r} is not a valid content type for {self.raw_name!r}: {defect}" ) raise self._invalid_metadata(msg, cause=defect) from defect content_type, parameters = ( # Defaults to `text/plain` if parsing failed. message.get_content_type().lower(), content_type_header.params, ) # Check if content-type is valid or defaulted to `text/plain` and thus was # not parseable. if content_type not in content_types or content_type not in value.lower(): raise self._invalid_metadata(invalid_msg) charset = parameters.get("charset", "UTF-8") if charset.lower() != "utf-8": raise self._invalid_metadata( f"{self.raw_name!r} can only specify the UTF-8 charset, not {charset!r}" ) markdown_variants = {"GFM", "CommonMark"} variant = parameters.get("variant", "GFM") # Use an acceptable default. if content_type == "text/markdown" and variant not in markdown_variants: raise self._invalid_metadata( f"valid Markdown variants for {self.raw_name!r} are " f"{list(markdown_variants)}, not {variant!r}", ) return value def _process_dynamic(self, value: list[str]) -> list[str]: dynamic_fields = list(map(str.lower, value)) for dynamic_field in dynamic_fields: if dynamic_field in {"name", "version", "metadata-version"}: raise self._invalid_metadata( f"{dynamic_field!r} is not allowed as a dynamic field" ) elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: raise self._invalid_metadata( f"{dynamic_field!r} is not a valid dynamic field" ) return dynamic_fields def _process_provides_extra( self, value: list[str], ) -> list[utils.NormalizedName]: normalized_names = [] try: for name in value: normalized_names.append(utils.canonicalize_name(name, validate=True)) except utils.InvalidName as exc: raise self._invalid_metadata( f"{name!r} is invalid for {self.raw_name!r}", cause=exc ) from exc else: return normalized_names def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: try: return specifiers.SpecifierSet(value) except specifiers.InvalidSpecifier as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc def _process_requires_dist( self, value: list[str], ) -> list[requirements.Requirement]: reqs = [] try: for req in value: reqs.append(requirements.Requirement(req)) except requirements.InvalidRequirement as exc: raise self._invalid_metadata( f"{req!r} is invalid for {self.raw_name!r}", cause=exc ) from exc else: return reqs def _process_license_expression(self, value: str) -> NormalizedLicenseExpression: try: return licenses.canonicalize_license_expression(value) except ValueError as exc: raise self._invalid_metadata( f"{value!r} is invalid for {self.raw_name!r}", cause=exc ) from exc def _process_license_files(self, value: list[str]) -> list[str]: paths = [] for path in value: if ".." in path: raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, " "parent directory indicators are not allowed" ) if "*" in path: raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, paths must be resolved" ) if ( pathlib.PurePosixPath(path).is_absolute() or pathlib.PureWindowsPath(path).is_absolute() ): raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, paths must be relative" ) if pathlib.PureWindowsPath(path).as_posix() != path: raise self._invalid_metadata( f"{path!r} is invalid for {self.raw_name!r}, " "paths must use '/' delimiter" ) paths.append(path) return paths def _process_import_names(self, value: list[str]) -> list[str]: for import_name in value: name, semicolon, private = import_name.partition(";") name = name.rstrip() for identifier in name.split("."): if not identifier.isidentifier(): raise self._invalid_metadata( f"{name!r} is invalid for {self.raw_name!r}; " f"{identifier!r} is not a valid identifier" ) elif keyword.iskeyword(identifier): raise self._invalid_metadata( f"{name!r} is invalid for {self.raw_name!r}; " f"{identifier!r} is a keyword" ) if semicolon and private.lstrip() != "private": raise self._invalid_metadata( f"{import_name!r} is invalid for {self.raw_name!r}; " "the only valid option is 'private'" ) return value _process_import_namespaces = _process_import_names class Metadata: """Representation of distribution metadata. Compared to :class:`RawMetadata`, this class provides objects representing metadata fields instead of only using built-in types. Any invalid metadata will cause :exc:`InvalidMetadata` to be raised (with a :py:attr:`~BaseException.__cause__` attribute as appropriate). .. versionadded:: 23.2 .. versionchanged:: 24.0 Optional attributes now return None when the field is absent instead of raising. """ _raw: RawMetadata @classmethod def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: """Create an instance from :class:`RawMetadata`. If *validate* is true, all metadata will be validated and all related exceptions will be gathered and raised as an :class:`ExceptionGroup`; otherwise, validation happens per attribute when it is accessed. """ ins = cls() ins._raw = data.copy() # Mutations occur due to caching enriched values. if validate: collector = _ErrorCollector() metadata_version = None with collector.collect(InvalidMetadata): metadata_version = ins.metadata_version metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) # Make sure to check for the fields that are present, the required # fields (so their absence can be reported). fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS # Remove fields that have already been checked. fields_to_check -= {"metadata_version"} for key in fields_to_check: try: if metadata_version: # Can't use getattr() as that triggers descriptor protocol which # will fail due to no value for the instance argument. try: field_metadata_version = cls.__dict__[key].added except KeyError: exc = InvalidMetadata(key, f"unrecognized field: {key!r}") collector.error(exc) continue field_age = _VALID_METADATA_VERSIONS.index( field_metadata_version ) if field_age > metadata_age: field = _RAW_TO_EMAIL_MAPPING[key] exc = InvalidMetadata( field, f"{field} introduced in metadata version " f"{field_metadata_version}, not {metadata_version}", ) collector.error(exc) continue getattr(ins, key) except InvalidMetadata as exc: collector.error(exc) collector.finalize("invalid metadata") return ins @classmethod def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: """Parse metadata from email headers. If *validate* is true, the metadata will be validated. All exceptions related to validation will be gathered and raised as an :class:`ExceptionGroup`. """ raw, unparsed = parse_email(data) if validate: with _ErrorCollector().on_exit("invalid or unparsed metadata") as collector: for unparsed_key in unparsed: if unparsed_key in _EMAIL_TO_RAW_MAPPING: message = f"{unparsed_key!r} has invalid data" else: message = f"unrecognized field: {unparsed_key!r}" collector.error(InvalidMetadata(unparsed_key, message)) try: validated = cls.from_raw(raw, validate=validate) except ExceptionGroup as exc_group: # The no-branch pragmas cover arcs only seen by Python 3.9. for exc in exc_group.exceptions: # pragma: no branch # A required field reported above as unparsed is absent # from `raw`, so skip from_raw's duplicate "missing" # complaint. if not ( isinstance(exc, InvalidMetadata) and exc.field in unparsed and _EMAIL_TO_RAW_MAPPING.get(exc.field) not in raw ): collector.error(exc) else: if not collector.errors: # pragma: no branch return validated return cls.from_raw(raw, validate=validate) metadata_version: _Validator[_MetadataVersion] = _Validator() """:external:ref:`core-metadata-metadata-version` (required; validated to be a valid metadata version)""" # `name` is not normalized/typed to NormalizedName so as to provide access to # the original/raw name. name: _Validator[str] = _Validator() """:external:ref:`core-metadata-name` (required; validated using :func:`~packaging.utils.canonicalize_name` and its *validate* parameter)""" version: _Validator[Version] = _Validator() """:external:ref:`core-metadata-version` (required)""" dynamic: _Validator[list[str] | None] = _Validator( added="2.2", ) """:external:ref:`core-metadata-dynamic` (validated against core metadata field names and lowercased)""" platforms: _Validator[list[str] | None] = _Validator() """:external:ref:`core-metadata-platform`""" supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") """:external:ref:`core-metadata-supported-platform`""" summary: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body """:external:ref:`core-metadata-description`""" description_content_type: _Validator[str | None] = _Validator(added="2.1") """:external:ref:`core-metadata-description-content-type` (validated)""" keywords: _Validator[list[str] | None] = _Validator() """:external:ref:`core-metadata-keywords`""" home_page: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-home-page`""" download_url: _Validator[str | None] = _Validator(added="1.1") """:external:ref:`core-metadata-download-url`""" author: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-author`""" author_email: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-author-email`""" maintainer: _Validator[str | None] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer`""" maintainer_email: _Validator[str | None] = _Validator(added="1.2") """:external:ref:`core-metadata-maintainer-email`""" license: _Validator[str | None] = _Validator() """:external:ref:`core-metadata-license`""" license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( added="2.4" ) """:external:ref:`core-metadata-license-expression` .. versionadded:: 24.2 """ license_files: _Validator[list[str] | None] = _Validator(added="2.4") """:external:ref:`core-metadata-license-file` .. versionadded:: 24.2 """ classifiers: _Validator[list[str] | None] = _Validator(added="1.1") """:external:ref:`core-metadata-classifier`""" requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-dist`""" requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( added="1.2" ) """:external:ref:`core-metadata-requires-python`""" # Because `Requires-External` allows for non-PEP 440 version specifiers, we # don't do any processing on the values. requires_external: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-requires-external`""" project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-project-url`""" # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation # regardless of metadata version. provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( added="2.1", ) """:external:ref:`core-metadata-provides-extra`""" provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-provides-dist`""" obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") """:external:ref:`core-metadata-obsoletes-dist`""" import_names: _Validator[list[str] | None] = _Validator(added="2.5") """:external:ref:`core-metadata-import-name` .. versionadded:: 26.0 """ import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") """:external:ref:`core-metadata-import-namespace` .. versionadded:: 26.0 """ requires: _Validator[list[str] | None] = _Validator(added="1.1") """``Requires`` (deprecated)""" provides: _Validator[list[str] | None] = _Validator(added="1.1") """``Provides`` (deprecated)""" obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") """``Obsoletes`` (deprecated)""" def as_rfc822(self) -> RFC822Message: """ Return an RFC822 message with the metadata. .. versionadded:: 26.0 """ message = RFC822Message() self._write_metadata(message) return message def _write_metadata(self, message: RFC822Message) -> None: """ Return an RFC822 message with the metadata. """ for name, validator in self.__class__.__dict__.items(): if isinstance(validator, _Validator) and name != "description": value = getattr(self, name) email_name = _RAW_TO_EMAIL_MAPPING[name] if value is not None: if email_name == "project-url": for label, url in value.items(): message[email_name] = f"{label}, {url}" elif email_name == "keywords": message[email_name] = ",".join(value) elif email_name == "import-name" and value == []: message[email_name] = "" elif isinstance(value, list): for item in value: message[email_name] = str(item) else: message[email_name] = str(value) # The description is a special case because it is in the body of the message. if self.description is not None: message.set_payload(self.description) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4533734 packaging-26.3/src/packaging/py.typed0000644000000000000000000000000015234171317014522 0ustar00././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4533734 packaging-26.3/src/packaging/pylock.py0000644000000000000000000010464015234171317014715 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 unquote, urlparse from .markers import ( Environment, Marker, _pep440_python_full_version, 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", "PylockSelectError", "PylockUnsupportedVersionError", "PylockValidationError", "is_valid_pylock_path", ] def __dir__() -> list[str]: return __all__ _T = TypeVar("_T") _T2 = TypeVar("_T2") class _FromMappingProtocol(Protocol): # pragma: no cover @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... _FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) _PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$") def is_valid_pylock_path(path: Path) -> bool: """Check if the given path is a valid pylock file path.""" return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name)) def _toml_key(key: str) -> str: return key.replace("_", "-") def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 if isinstance(value, (Version, Marker, SpecifierSet)): return str(value) if isinstance(value, Sequence) and key == "environments": return [str(v) for v in value] return value def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: return { _toml_key(key): _toml_value(key, value) for key, value in data if value is not None } def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: """Get a value from the dictionary and verify it's the expected type.""" if (value := d.get(key)) is None: return None if not isinstance(value, expected_type) or ( # Special case: bool is a subclass of int, but TOML distinguishes the two expected_type is int and isinstance(value, bool) ): raise PylockValidationError( f"Unexpected type {type(value).__name__} " f"(expected {expected_type.__name__})", context=key, ) return value def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: """Get a required value from the dictionary and verify it's the expected type.""" if (value := _get(d, expected_type, key)) is None: raise _PylockRequiredKeyError(key) return value def _get_sequence( d: Mapping[str, Any], expected_item_type: type[_T], key: str ) -> Sequence[_T] | None: """Get a list value from the dictionary and verify it's the expected items type.""" if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] return None if isinstance(value, (str, bytes)): # special case: str and bytes are Sequences, but we want to reject it raise PylockValidationError( f"Unexpected type {type(value).__name__} (expected Sequence)", context=key, ) for i, item in enumerate(value): if not isinstance(item, expected_item_type): raise PylockValidationError( f"Unexpected type {type(item).__name__} " f"(expected {expected_item_type.__name__})", context=f"{key}[{i}]", ) return value def _get_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str, ) -> _T2 | None: """Get a value from the dictionary, verify it's the expected type, and convert to the target type. This assumes the target_type constructor accepts the value. """ if (value := _get(d, expected_type, key)) is None: return None try: return target_type(value) except Exception as e: raise PylockValidationError(e, context=key) from e def _get_required_as( d: Mapping[str, Any], expected_type: type[_T], target_type: Callable[[_T], _T2], key: str, ) -> _T2: """Get a required value from the dict, verify it's the expected type, and convert to the target type.""" if (value := _get_as(d, expected_type, target_type, key)) is None: raise _PylockRequiredKeyError(key) return value def _get_sequence_as( d: Mapping[str, Any], expected_item_type: type[_T], target_item_type: Callable[[_T], _T2], key: str, ) -> list[_T2] | None: """Get list value from dictionary and verify expected items type.""" if (value := _get_sequence(d, expected_item_type, key)) is None: return None result = [] try: for item in value: typed_item = target_item_type(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result def _get_object( d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str ) -> _FromMappingProtocolT | None: """Get a dictionary value from the dictionary and convert it to a dataclass.""" if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] return None try: return target_type._from_dict(value) except Exception as e: raise PylockValidationError(e, context=key) from e def _get_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str ) -> list[_FromMappingProtocolT] | None: """Get a list value from the dictionary and convert its items to a dataclass.""" if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] return None result: list[_FromMappingProtocolT] = [] try: for item in value: typed_item = target_item_type._from_dict(item) result.append(typed_item) except Exception as e: raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e return result def _get_required_sequence_of_objects( d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str ) -> Sequence[_FromMappingProtocolT]: """Get a required list value from the dictionary and convert its items to a dataclass.""" if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: raise _PylockRequiredKeyError(key) return result def _validate_normalized_name(name: str) -> NormalizedName: """Validate that a string is a NormalizedName.""" if not is_normalized_name(name): raise PylockValidationError(f"Name {name!r} is not normalized") return NormalizedName(name) def _validate_path_url(path: str | None, url: str | None) -> None: if not path and not url: raise PylockValidationError("path or url must be provided") def _path_name(path: str | None) -> str | None: if not path: return None # If the path is relative it MAY use POSIX-style path separators explicitly # for portability if "/" in path: return path.rsplit("/", 1)[-1] elif "\\" in path: return path.rsplit("\\", 1)[-1] else: return path def _url_name(url: str | None) -> str | None: if not url: return None url_path = urlparse(url).path # The last path component is percent-encoded, so decode it to the file name return unquote(url_path.rsplit("/", 1)[-1]) def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: if not hashes: raise PylockValidationError("At least one hash must be provided") if not all(isinstance(hash_val, str) for hash_val in hashes.values()): raise PylockValidationError("Hash values must be strings") return hashes class PylockValidationError(Exception): """Raised when when input data is not spec-compliant.""" context: str | None = None message: str def __init__( self, cause: str | Exception, *, context: str | None = None, ) -> None: if isinstance(cause, PylockValidationError): if cause.context: self.context = ( f"{context}.{cause.context}" if context else cause.context ) else: self.context = context self.message = cause.message else: self.context = context self.message = str(cause) def __str__(self) -> str: if self.context: return f"{self.message} in {self.context!r}" return self.message class _PylockRequiredKeyError(PylockValidationError): def __init__(self, key: str) -> None: super().__init__("Missing required value", context=key) class PylockUnsupportedVersionError(PylockValidationError): """Raised when encountering an unsupported `lock_version`.""" class PylockSelectError(Exception): """Base exception for errors raised by :meth:`Pylock.select`. .. versionadded:: 26.1 """ @dataclass(frozen=True, init=False) class PackageVcs: type: str url: str | None = None path: str | None = None requested_revision: str | None = None commit_id: str # type: ignore[misc] subdirectory: str | None = None def __init__( self, *, type: str, url: str | None = None, path: str | None = None, requested_revision: str | None = None, commit_id: str, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "type", type) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "requested_revision", requested_revision) object.__setattr__(self, "commit_id", commit_id) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_vcs = cls( type=_get_required(d, str, "type"), url=_get(d, str, "url"), path=_get(d, str, "path"), requested_revision=_get(d, str, "requested-revision"), commit_id=_get_required(d, str, "commit-id"), subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_vcs.path, package_vcs.url) return package_vcs @dataclass(frozen=True, init=False) class PackageDirectory: path: str editable: bool | None = None subdirectory: str | None = None def __init__( self, *, path: str, editable: bool | None = None, subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "path", path) object.__setattr__(self, "editable", editable) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: return cls( path=_get_required(d, str, "path"), editable=_get(d, bool, "editable"), subdirectory=_get(d, str, "subdirectory"), ) @dataclass(frozen=True, init=False) class PackageArchive: url: str | None = None path: str | None = None size: int | None = None upload_time: datetime | None = None hashes: Mapping[str, str] # type: ignore[misc] subdirectory: str | None = None def __init__( self, *, url: str | None = None, path: str | None = None, size: int | None = None, upload_time: datetime | None = None, hashes: Mapping[str, str], subdirectory: str | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "hashes", hashes) object.__setattr__(self, "subdirectory", subdirectory) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_archive = cls( url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), upload_time=_get(d, datetime, "upload-time"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] subdirectory=_get(d, str, "subdirectory"), ) _validate_path_url(package_archive.path, package_archive.url) return package_archive @dataclass(frozen=True, init=False) class PackageSdist: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc] def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_sdist = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_sdist.path, package_sdist.url) return package_sdist @property def filename(self) -> str: """Get the filename of the sdist. .. versionadded:: 26.1 """ filename = self.name or _path_name(self.path) or _url_name(self.url) if not filename: raise PylockValidationError("Cannot determine sdist filename") return filename @dataclass(frozen=True, init=False) class PackageWheel: name: str | None = None upload_time: datetime | None = None url: str | None = None path: str | None = None size: int | None = None hashes: Mapping[str, str] # type: ignore[misc] def __init__( self, *, name: str | None = None, upload_time: datetime | None = None, url: str | None = None, path: str | None = None, size: int | None = None, hashes: Mapping[str, str], ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "upload_time", upload_time) object.__setattr__(self, "url", url) object.__setattr__(self, "path", path) object.__setattr__(self, "size", size) object.__setattr__(self, "hashes", hashes) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package_wheel = cls( name=_get(d, str, "name"), upload_time=_get(d, datetime, "upload-time"), url=_get(d, str, "url"), path=_get(d, str, "path"), size=_get(d, int, "size"), hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] ) _validate_path_url(package_wheel.path, package_wheel.url) return package_wheel @property def filename(self) -> str: """Get the filename of the wheel.""" filename = self.name or _path_name(self.path) or _url_name(self.url) if not filename: raise PylockValidationError("Cannot determine wheel filename") return filename @dataclass(frozen=True, init=False) class Package: name: NormalizedName version: Version | None = None marker: Marker | None = None requires_python: SpecifierSet | None = None dependencies: Sequence[Mapping[str, Any]] | None = None vcs: PackageVcs | None = None directory: PackageDirectory | None = None archive: PackageArchive | None = None index: str | None = None sdist: PackageSdist | None = None wheels: Sequence[PackageWheel] | None = None attestation_identities: Sequence[Mapping[str, Any]] | None = None tool: Mapping[str, Any] | None = None def __init__( self, *, name: NormalizedName, version: Version | None = None, marker: Marker | None = None, requires_python: SpecifierSet | None = None, dependencies: Sequence[Mapping[str, Any]] | None = None, vcs: PackageVcs | None = None, directory: PackageDirectory | None = None, archive: PackageArchive | None = None, index: str | None = None, sdist: PackageSdist | None = None, wheels: Sequence[PackageWheel] | None = None, attestation_identities: Sequence[Mapping[str, Any]] | None = None, tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "name", name) object.__setattr__(self, "version", version) object.__setattr__(self, "marker", marker) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "dependencies", dependencies) object.__setattr__(self, "vcs", vcs) object.__setattr__(self, "directory", directory) object.__setattr__(self, "archive", archive) object.__setattr__(self, "index", index) object.__setattr__(self, "sdist", sdist) object.__setattr__(self, "wheels", wheels) object.__setattr__(self, "attestation_identities", attestation_identities) object.__setattr__(self, "tool", tool) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: package = cls( name=_get_required_as(d, str, _validate_normalized_name, "name"), version=_get_as(d, str, Version, "version"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] marker=_get_as(d, str, Marker, "marker"), vcs=_get_object(d, PackageVcs, "vcs"), directory=_get_object(d, PackageDirectory, "directory"), archive=_get_object(d, PackageArchive, "archive"), index=_get(d, str, "index"), sdist=_get_object(d, PackageSdist, "sdist"), wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) distributions = bool(package.sdist) + len(package.wheels or []) direct_urls = ( bool(package.vcs) + bool(package.directory) + bool(package.archive) ) if distributions > 0 and direct_urls > 0: raise PylockValidationError( "None of vcs, directory, archive must be set if sdist or wheels are set" ) if distributions == 0 and direct_urls != 1: raise PylockValidationError( "Exactly one of vcs, directory, archive must be set " "if sdist and wheels are not set" ) for i, wheel in enumerate(package.wheels or []): try: (name, version, _, _) = parse_wheel_filename(wheel.filename) except Exception as e: raise PylockValidationError( f"Invalid wheel filename {wheel.filename!r}", context=f"wheels[{i}]", ) from e if name != package.name: raise PylockValidationError( f"Name in {wheel.filename!r} is not consistent with " f"package name {package.name!r}", context=f"wheels[{i}]", ) if package.version and version != package.version: raise PylockValidationError( f"Version in {wheel.filename!r} is not consistent with " f"package version {str(package.version)!r}", context=f"wheels[{i}]", ) if package.sdist: try: name, version = parse_sdist_filename(package.sdist.filename) except Exception as e: raise PylockValidationError( f"Invalid sdist filename {package.sdist.filename!r}", context="sdist", ) from e if name != package.name: raise PylockValidationError( f"Name in {package.sdist.filename!r} is not consistent with " f"package name {package.name!r}", context="sdist", ) if package.version and version != package.version: raise PylockValidationError( f"Version in {package.sdist.filename!r} is not consistent with " f"package version {str(package.version)!r}", context="sdist", ) try: for i, attestation_identity in enumerate( # noqa: B007 package.attestation_identities or [] ): _get_required(attestation_identity, str, "kind") except Exception as e: raise PylockValidationError( e, context=f"attestation-identities[{i}]" ) from e return package @property def is_direct(self) -> bool: return not (self.sdist or self.wheels) @dataclass(frozen=True, init=False) class Pylock: """A class representing a pylock file.""" lock_version: Version environments: Sequence[Marker] | None = None requires_python: SpecifierSet | None = None extras: Sequence[NormalizedName] | None = None dependency_groups: Sequence[str] | None = None default_groups: Sequence[str] | None = None created_by: str # type: ignore[misc] packages: Sequence[Package] # type: ignore[misc] tool: Mapping[str, Any] | None = None def __init__( self, *, lock_version: Version, environments: Sequence[Marker] | None = None, requires_python: SpecifierSet | None = None, extras: Sequence[NormalizedName] | None = None, dependency_groups: Sequence[str] | None = None, default_groups: Sequence[str] | None = None, created_by: str, packages: Sequence[Package], tool: Mapping[str, Any] | None = None, ) -> None: # In Python 3.10+ make dataclass kw_only=True and remove __init__ object.__setattr__(self, "lock_version", lock_version) object.__setattr__(self, "environments", environments) object.__setattr__(self, "requires_python", requires_python) object.__setattr__(self, "extras", extras) object.__setattr__(self, "dependency_groups", dependency_groups) object.__setattr__(self, "default_groups", default_groups) object.__setattr__(self, "created_by", created_by) object.__setattr__(self, "packages", packages) object.__setattr__(self, "tool", tool) @classmethod def _from_dict(cls, d: Mapping[str, Any]) -> Self: pylock = cls( lock_version=_get_required_as(d, str, Version, "lock-version"), environments=_get_sequence_as(d, str, Marker, "environments"), extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), dependency_groups=_get_sequence(d, str, "dependency-groups"), default_groups=_get_sequence(d, str, "default-groups"), created_by=_get_required(d, str, "created-by"), requires_python=_get_as(d, str, SpecifierSet, "requires-python"), packages=_get_required_sequence_of_objects(d, Package, "packages"), tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] ) if not Version("1") <= pylock.lock_version < Version("2"): raise PylockUnsupportedVersionError( f"pylock version {pylock.lock_version} is not supported" ) if pylock.lock_version > Version("1.0"): _logger.warning( "pylock minor version %s is not supported", pylock.lock_version ) return pylock @classmethod def from_dict(cls, d: Mapping[str, Any], /) -> Self: """Create and validate a Pylock instance from a TOML dictionary. Raises :class:`PylockValidationError` if the input data is not spec-compliant. """ return cls._from_dict(d) def to_dict(self) -> Mapping[str, Any]: """Convert the Pylock instance to a TOML dictionary.""" return dataclasses.asdict(self, dict_factory=_toml_dict_factory) def validate(self) -> None: """Validate the Pylock instance against the specification. Raises :class:`PylockValidationError` otherwise.""" self.from_dict(self.to_dict()) def select( self, *, environment: Environment | None = None, tags: Sequence[Tag] | None = None, extras: Collection[str] | None = None, dependency_groups: Collection[str] | None = None, prefer_sdist_predicate: Callable[[NormalizedName], bool] | None = None, ) -> Iterator[ tuple[ Package, PackageVcs | PackageDirectory | PackageArchive | PackageWheel | PackageSdist, ] ]: """Select what to install from the lock file. The *environment* and *tags* parameters represent the environment being selected for. If unspecified, ``packaging.markers.default_environment()`` and ``packaging.tags.sys_tags()`` are used. The *extras* parameter represents the extras to install. The *dependency_groups* parameter represents the groups to install. If unspecified, the default groups are used. The *prefer_sdist_predicate* parameter is called for packages with a source distribution. If it returns ``True``, the source distribution is selected before attempting wheel compatibility. If no source distribution is available, wheel selection proceeds as usual without calling the predicate. This method must be used on valid Pylock instances (i.e. one obtained from :meth:`Pylock.from_dict` or if constructed manually, after calling :meth:`Pylock.validate`). .. versionadded:: 26.1 .. versionchanged:: 26.3 Added the *prefer_sdist_predicate* parameter. """ compatible_tags_selector = create_compatible_tags_selector( tags if tags is not None else sys_tags() ) # #. Gather the extras and dependency groups to install and set ``extras`` and # ``dependency_groups`` for marker evaluation, respectively. # # #. ``extras`` SHOULD be set to the empty set by default. # #. ``dependency_groups`` SHOULD be the set created from # :ref:`pylock-default-groups` by default. env = cast( "dict[str, str | frozenset[str]]", dict( environment or {}, # Marker.evaluate will fill-up extras=frozenset(extras or []), dependency_groups=frozenset( (self.default_groups or []) if dependency_groups is None # to allow selecting no group else dependency_groups ), ), ) env_python_full_version = _pep440_python_full_version( environment["python_full_version"] if environment else default_environment()["python_full_version"] ) # #. Check if the metadata version specified by :ref:`pylock-lock-version` is # supported; an error or warning MUST be raised as appropriate. # Covered by lock.validate() which is a precondition for this method. # #. If :ref:`pylock-requires-python` is specified, check that the environment # being installed for meets the requirement; an error MUST be raised if it is # not met. if self.requires_python and not self.requires_python.contains( env_python_full_version, ): raise PylockSelectError( f"python_full_version {env_python_full_version!r} " f"in provided environment does not satisfy the Python version " f"requirement {str(self.requires_python)!r}" ) # #. If :ref:`pylock-environments` is specified, check that at least one of the # environment marker expressions is satisfied; an error MUST be raised if no # expression is satisfied. if self.environments: for env_marker in self.environments: if env_marker.evaluate( cast("dict[str, str]", environment or {}), context="requirement" ): break else: raise PylockSelectError( "Provided environment does not satisfy any of the " "environments specified in the lock file" ) # #. For each package listed in :ref:`pylock-packages`: selected_packages_by_name: dict[str, tuple[int, Package]] = {} for package_index, package in enumerate(self.packages): # #. If :ref:`pylock-packages-marker` is specified, check if it is # satisfied;if it isn't, skip to the next package. if package.marker and not package.marker.evaluate(env, context="lock_file"): continue # #. If :ref:`pylock-packages-requires-python` is specified, check if it is # satisfied; an error MUST be raised if it isn't. if package.requires_python and not package.requires_python.contains( env_python_full_version, ): raise PylockSelectError( f"python_full_version {env_python_full_version!r} " f"in provided environment does not satisfy the Python version " f"requirement {str(package.requires_python)!r} for package " f"{package.name!r} at packages[{package_index}]" ) # #. Check that no other conflicting instance of the package has been slated # to be installed; an error about the ambiguity MUST be raised otherwise. if package.name in selected_packages_by_name: raise PylockSelectError( f"Multiple packages with the name {package.name!r} are " f"selected at packages[{package_index}] and " f"packages[{selected_packages_by_name[package.name][0]}]" ) # #. Check that the source of the package is specified appropriately (i.e. # there are no conflicting sources in the package entry); # an error MUST be raised if any issues are found. # Covered by lock.validate() which is a precondition for this method. # #. Add the package to the set of packages to install. selected_packages_by_name[package.name] = (package_index, package) # #. For each package to be installed: for package_index, package in selected_packages_by_name.values(): # - If :ref:`pylock-packages-vcs` is set: if package.vcs is not None: yield package, package.vcs # - Else if :ref:`pylock-packages-directory` is set: elif package.directory is not None: yield package, package.directory # - Else if :ref:`pylock-packages-archive` is set: elif package.archive is not None: yield package, package.archive # - Else if source preference selects an available # :ref:`pylock-packages-sdist`: elif ( package.sdist is not None and prefer_sdist_predicate is not None and prefer_sdist_predicate(package.name) ): yield package, package.sdist # - Else if there are entries for :ref:`pylock-packages-wheels`: elif package.wheels: # #. Look for the appropriate wheel file based on # :ref:`pylock-packages-wheels-name`; if one is not found then move # on to :ref:`pylock-packages-sdist` or an error MUST be raised about # a lack of source for the project. best_wheel = next( compatible_tags_selector( (wheel, parse_wheel_filename(wheel.filename)[-1]) for wheel in package.wheels ), None, ) if best_wheel: yield package, best_wheel elif package.sdist is not None: yield package, package.sdist else: raise PylockSelectError( f"No wheel found matching the provided tags " f"for package {package.name!r} " f"at packages[{package_index}], " f"and no sdist available as a fallback" ) # - Else if no :ref:`pylock-packages-wheels` file is found or # :ref:`pylock-packages-sdist` is solely set: elif package.sdist is not None: yield package, package.sdist else: # Covered by lock.validate() which is a precondition for this method. raise NotImplementedError # pragma: no cover ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4537523 packaging-26.3/src/packaging/ranges.py0000644000000000000000000024215615234171317014700 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. """Public :class:`VersionRange` API. A set-algebra view of the versions accepted by a :class:`~packaging.specifiers.SpecifierSet`. Ranges support intersection, union, complement, and difference; membership and filtering match the originating specifier set; and conversion back to a :class:`~packaging.specifiers.SpecifierSet` is available where a PEP 440 form exists. .. testsetup:: from packaging.ranges import VersionRange from packaging.specifiers import SpecifierSet from packaging.version import Version """ from __future__ import annotations import enum import typing from typing import ( TYPE_CHECKING, Any, TypeVar, Union, ) from ._ranges import ( FULL_RANGE, MIN_VERSION, NEG_INF, POS_INF, BoundaryKind, BoundaryVersion, LowerBound, UpperBound, coerce_version, filter_by_ranges, intersect_ranges, least_version_above, matches_bounds_only, range_is_empty, ranges_are_prerelease_only, trim_release, ) from .version import Version if TYPE_CHECKING: from collections.abc import Callable, Iterable, Iterator, Sequence from ._ranges import Interval from .specifiers import SpecifierSet __all__ = ["VersionRange"] T = TypeVar("T") UnparsedVersion = Union[Version, str] UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) #: The most ``!=`` exclusion fragments (``!=V`` points or ``!=P.*`` prefixes) #: that :meth:`VersionRange.to_specifier_set` will materialize to spell a #: single gap or run. Every site that expands a version-number-driven chain #: charges it against this cap, and chains that spell one gap together share #: it (see :func:`_decompose_dev0_gap` and :func:`_encode_gap`), #: so no gap ever materializes more than this many exclusions. Past the cap #: the recovery returns ``None`` rather than emit the unbounded chain a range #: such as ``==5.* | ==1000000.*`` would otherwise drive. _MAX_EXCLUSION_RUN = 128 class _SetOp(enum.Enum): """The binary set operation ``_combine_literals`` resolves over ``===`` literals.""" INTERSECTION = enum.auto() UNION = enum.auto() DIFFERENCE = enum.auto() def __dir__() -> list[str]: return __all__ # Range algebra: intersection and the empty-interval test live in the engine # (``intersect_ranges`` / ``range_is_empty``); union and complement are only # needed here, so they live in this module. def _union_ranges( left: Sequence[Interval], right: Sequence[Interval], ) -> list[Interval]: """Union two sorted, non-overlapping interval lists. A linear merge over the two pre-sorted inputs followed by a single coalescing pass: adjacent or overlapping intervals collapse so the result is itself sorted and non-overlapping. """ if not left: return list(right) if not right: return list(left) merged_input: list[Interval] = [] left_index = right_index = 0 while left_index < len(left) and right_index < len(right): if left[left_index][0] <= right[right_index][0]: merged_input.append(left[left_index]) left_index += 1 else: merged_input.append(right[right_index]) right_index += 1 merged_input.extend(left[left_index:]) merged_input.extend(right[right_index:]) merged: list[Interval] = [merged_input[0]] for lower, upper in merged_input[1:]: prev_lower, prev_upper = merged[-1] if ( prev_upper.version is None or lower.version is None or prev_upper.version > lower.version ): overlaps = True elif prev_upper.version == lower.version: overlaps = prev_upper.inclusive or lower.inclusive else: # An ordering gap may still hold no version when the two bounds # straddle a synthetic boundary; merge across an empty gap to # stay canonical. gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) gap_upper = UpperBound(lower.version, not lower.inclusive) overlaps = range_is_empty(gap_lower, gap_upper) if overlaps: merged[-1] = (prev_lower, max(prev_upper, upper)) else: merged.append((lower, upper)) return merged def _complement_ranges(ranges: Sequence[Interval]) -> list[Interval]: """Complement a sorted, non-overlapping interval list. Yields the gaps between intervals plus a leading gap before the first and a trailing gap after the last. Bound inclusivity flips so that complement-of-complement round-trips back to the input. """ if not ranges: return list(FULL_RANGE) result: list[Interval] = [] prev_upper: UpperBound | None = None for lower, upper in ranges: if prev_upper is None: # Leading gap below the first interval. Every range reaching here is # floor-canonical: ``_canonical_floor`` has already folded an # inclusive lower at or below ``0.dev0`` into ``-inf``. So a finite # first lower always leaves a non-empty gap down to ``-inf``, while a # ``-inf`` lower leaves no leading gap at all. if lower.version is not None: gap_upper = UpperBound(lower.version, not lower.inclusive) result.append((NEG_INF, gap_upper)) else: gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) gap_upper = UpperBound(lower.version, not lower.inclusive) # Input intervals are canonical (sorted, disjoint, non-touching), # so the gap between two of them always holds at least one version. result.append((gap_lower, gap_upper)) prev_upper = upper # The empty-input early return guarantees the loop ran. assert prev_upper is not None if prev_upper.version is not None: gap_lower = LowerBound(prev_upper.version, not prev_upper.inclusive) result.append((gap_lower, POS_INF)) return result def _canonical_floor(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: """Collapse the PEP 440 floor in a sorted interval list. Only the first interval can touch ``0.dev0`` (the minimum version). An inclusive lower at or below it admits everything below, the same as ``-inf``, so ``>=0.dev0`` becomes the one canonical full range. An exclusive upper at or below it leaves the interval empty, so it is dropped. """ if not bounds: return bounds lower, upper = bounds[0] if range_is_empty(NEG_INF, upper): return bounds[1:] if ( lower.inclusive and isinstance(lower.version, Version) and lower.version <= MIN_VERSION ): return ((NEG_INF, upper), *bounds[1:]) return bounds def _predecessor_boundary(version: Version) -> BoundaryVersion | None: """The boundary whose least successor is *version*, or ``None``. Inverse of :func:`~packaging._ranges.least_version_above`. A plain version that is exactly such a successor (``1.0a2.dev0`` sits just above ``AFTER_POSTS(1.0a1)``) folds back to that boundary, so ``>=1.0a2.dev0`` and ``>1.0a1`` share one form. The proposed boundary is confirmed by round-tripping through ``least_version_above``. """ # Only a least successor carries a dev segment, so nothing else can fold. if version.dev is None: return None candidate: BoundaryVersion | None = None if version.pre is not None and version.dev == 0 and version.post is None: # 1.0a2.dev0 -> AFTER_POSTS(1.0a1) kind, number = version.pre if number >= 1: candidate = BoundaryVersion( version.__replace__(pre=(kind, number - 1), dev=None), BoundaryKind.AFTER_POSTS, ) elif version.dev >= 1: # 1.0.dev3 -> AFTER_LOCALS(1.0.dev2) candidate = BoundaryVersion( version.__replace__(dev=version.dev - 1), BoundaryKind.AFTER_LOCALS ) elif version.dev == 0 and version.post is not None: # 1.0.post1.dev0 -> AFTER_LOCALS(1.0.post0); 1.0.post0.dev0 -> AFTER_LOCALS(1.0) base = ( version.__replace__(post=None, dev=None) if version.post == 0 else version.__replace__(post=version.post - 1, dev=None) ) candidate = BoundaryVersion(base, BoundaryKind.AFTER_LOCALS) if candidate is not None and least_version_above(candidate) == version: return candidate return None def _canonicalize(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: """Fold least-successor bounds to their boundary form. ``>=1.0a2.dev0`` and ``>1.0a1`` denote the same set, so both must reduce to one representation for ``==`` and ``hash`` to agree. An inclusive lower or exclusive upper sitting on a boundary's least successor becomes that boundary; the engine's emptiness check has already dropped the synthetic gaps such intervals would otherwise leave. """ result: list[Interval] = [] for lower, upper in bounds: new_lower, new_upper = lower, upper if isinstance(lower.version, Version) and lower.inclusive: boundary = _predecessor_boundary(lower.version) if boundary is not None: new_lower = LowerBound(boundary, inclusive=False) if isinstance(upper.version, Version) and not upper.inclusive: boundary = _predecessor_boundary(upper.version) if boundary is not None: new_upper = UpperBound(boundary, inclusive=True) result.append((new_lower, new_upper)) return tuple(result) def _struct_admits( bounds: tuple[Interval, ...], admit_arbitrary: bool, literal: str ) -> bool: """True when the bounds (plus arbitrary admission) admit ``literal``. Skips the explicit admit/reject sets, which the caller layers on top. A non-version string matches via ``admit_arbitrary`` only on full bounds; on narrower bounds the flag is metadata only. """ parsed = coerce_version(literal) if parsed is None: return admit_arbitrary and bounds == FULL_RANGE return matches_bounds_only(bounds, parsed) # Repr helpers: def _bound_version_str(value: BoundaryVersion | Version) -> str: """Printout for a bound's inner value, kind-tagged for boundaries.""" if isinstance(value, BoundaryVersion): return f"{value.version}[{value.kind.name}]" return str(value) def _format_lower(bound: LowerBound) -> str: if bound.version is None: return "(-inf" bracket = "[" if bound.inclusive else "(" return f"{bracket}{_bound_version_str(bound.version)}" def _format_upper(bound: UpperBound) -> str: if bound.version is None: return "+inf)" bracket = "]" if bound.inclusive else ")" return f"{_bound_version_str(bound.version)}{bracket}" def _format_intervals(intervals: Sequence[Interval]) -> str: """Render a sorted interval list as ``lower, upper | lower, upper``.""" return " | ".join( f"{_format_lower(lower)}, {_format_upper(upper)}" for lower, upper in intervals ) # ``to_specifier_set`` recovery: encode a range's interval list back into # specifier fragments. Each helper returns ``None`` when its shape has no # PEP 440 form. The ``keep_dev0`` argument threaded through is a spelling # mode, not a pre-release policy: false emits a prerelease-free form (no # synthetic ``.dev0``, so the recovered range has an empty opt-in region), # true keeps the ``.dev0`` markers (so the range opts its bounds in). # ``to_specifier_set`` encodes in both modes and keeps whichever round-trips. # # Bound and interval encoding: turn one interval's bounds into fragments. def _is_dev0_version(version: Version) -> bool: """True when version is exactly ``X[.Y]*.dev0`` (the shape `` list[str] | None: """A prerelease-free spelling for an inclusive ``[version`` lower, or ``None``. Several ``[V`` lowers come from an operator whose own spelling carries no synthetic ``.dev0``. Recovering that spelling gives the range an empty opt-in region, so it is offered in the prerelease-free spelling mode (see :meth:`VersionRange.to_specifier_set`). """ if version.dev != 0 or version.pre is not None or version.local is not None: return None # ``[B.post(k).dev0`` is the lower ``>B.post(k-1)`` builds (k >= 1). if version.post is not None: if version.post < 1: return None return [f">{version.__replace__(post=version.post - 1, dev=None)}"] # ``[F.dev0`` is family F's base. The prefix P just below F has # ``==P.* == [P.dev0, F.dev0)``, so ``>=P,!=P.*`` lands exactly on ``[F.dev0``. family = trim_release(version.release) last = family[-1] if last < 1: return None below_release = (*family[:-1], last - 1) below = Version.from_parts(epoch=version.epoch, release=below_release) # At the epoch-0 floor ``==P.*`` already reaches ``0.dev0``, so the ``>=P`` # half is redundant: ``[1.dev0, +inf)`` is plain ``!=0.*``. if version.epoch == 0 and not any(below_release): return [f"!={below}.*"] return [f">={below}", f"!={below}.*"] def _epoch_floor_lower( lower: LowerBound, upper: UpperBound ) -> tuple[Version, int, bool] | None: """The ``E!0`` family of a lower sitting on an epoch>0 zero-family floor. An epoch>0 zero-family base such as ``1!0.dev0`` has no ``>=P,!=P.*`` spelling since no version sorts below ``E!0`` within the epoch. While the interval stays within ``==E!0.*`` it is that wildcard, trimmed by the upper and with a leading ``.dev`` run excluded: an ``AFTER_LOCALS(E!0.dev(k))`` lower drops ``E!0.dev0..E!0.dev(k)``, a plain inclusive ``E!0.dev0`` lower drops none. Returns the ``E!0`` family, how many leading ``.dev`` releases to exclude, and whether the upper sits at the family cap (so ``==E!0.*`` needs no upper), else ``None``. """ version = lower.version if isinstance(version, BoundaryVersion): if version.kind != BoundaryKind.AFTER_LOCALS: return None version = version.version if version.dev is None: return None excluded_devs = version.dev + 1 elif isinstance(version, Version) and lower.inclusive: # A plain inclusive lower only reaches the floor as ``>=E!0.dev0``; # higher ``.dev`` would have canonicalized to an AFTER_LOCALS boundary. if version.dev != 0: return None excluded_devs = 0 else: return None # Only the bare ``E!0`` floor of a non-zero epoch qualifies. if version.epoch == 0: return None if version.pre is not None or version.post is not None or version.local is not None: return None if any(trim_release(version.release)): return None # ``==E!0.*`` spans ``[E!0.dev0, E!1.dev0)``; it fits only below that cap. next_family = Version.from_parts(epoch=version.epoch, release=(1,), dev=0) cap = UpperBound(next_family, False) if upper > cap: return None family = Version.from_parts(epoch=version.epoch, release=(0,)) return family, excluded_devs, upper == cap def _dev_family_anchor(family: Version) -> list[str] | None: """Prerelease-free fragments for ``[family, ..)``, or ``None`` if it has none. ``family`` is an ``X.dev0``. The floor gives ``[]`` (every version); a release base its ``_clean_lower`` family-floor spelling (``!=0.*`` ...); an ``X.post0`` base ``>=X,!=X``. A pre-release base has no prerelease-free spelling. """ if family <= MIN_VERSION: return [] clean = _clean_lower(family) if clean is not None: return clean if family.pre is None and family.post == 0: base = family.__replace__(post=None, dev=None) return [f">={base}", f"!={base}"] return None def _encode_lower(lower: LowerBound, keep_dev0: bool) -> list[str] | None: """Encode a lower bound as specifier fragments, or ``None``. ``[]`` for ``-inf``. An ``AFTER_POSTS(V)`` lower is ``>V``. An ``AFTER_LOCALS(V)`` lower is the set ``[successor, ..)`` and emits ``>=V,!=V``, except in the prerelease-free spelling mode (``keep_dev0`` false), where it recovers a spelling with no synthetic ``.dev0`` when one exists: ``>3.8.post1`` for a post release, or a dev family's anchor plus the dev run up to V for a ``.dev`` release. """ lower_version = lower.version if lower_version is None: return [] if isinstance(lower_version, BoundaryVersion): if lower_version.kind == BoundaryKind.AFTER_POSTS: # AFTER_POSTS only ever appears as an exclusive ``>V`` lower. return [f">{lower_version.version}"] inner = lower_version.version if inner <= MIN_VERSION: # The ``(-inf, V)`` side was dropped at the floor, so the lone # ``(AFTER_LOCALS(0.dev0), +inf)`` interval is exactly ``!=0.dev0``. return [f"!={inner}"] # An ``(AFTER_LOCALS(V), ..)`` lower is the set ``[successor, ..)``. In # the prerelease-free mode, recover a spelling with no synthetic ``.dev0`` # so the range's opt-in region stays empty. if not keep_dev0: if inner.dev is not None: # A ``.dev`` V makes ``[successor, ..)`` its dev family's # prerelease-free anchor minus the finite dev run up to ``V`` # (e.g. ``>=1.0,!=1.0,!=1.0.post0.dev0``), carrying no synthetic # ``.dev0``. family = inner.__replace__(dev=0) anchor = _dev_family_anchor(family) if anchor is not None: if inner.dev + 1 > _MAX_EXCLUSION_RUN: return None run = [ f"!={family.__replace__(dev=d)}" for d in range(inner.dev + 1) ] return anchor + run else: # A ``.post`` release recovers its prerelease-free ``>`` spelling # from the successor (``>3.8.post1`` for ``AFTER_LOCALS(3.8.post1)``). successor = least_version_above(lower_version) clean = _clean_lower(successor) if successor is not None else None if clean is not None: return clean # Otherwise it is ``[V, ..)`` minus V's local family, i.e. ``>=V,!=V``. # The prerelease-free recoveries above have already returned in that mode; # a residual ``.dev`` V here opts pre-releases in, so this spelling round # trips only for a range whose opt-in region wants it. return [f">={inner}", f"!={inner}"] if not lower.inclusive: return None # In the prerelease-free mode a ``.dev0`` lower prefers its clean spelling. if not keep_dev0: clean = _clean_lower(lower_version) if clean is not None: return clean return [f">={lower_version}"] def _encode_upper(upper: UpperBound, keep_dev0: bool) -> list[str] | None: """Encode an upper bound as specifier fragments, or ``None``. ``[]`` for ``+inf``. In the prerelease-free spelling mode (``keep_dev0`` false) the `` Version | None: """If ``[lower, upper)`` is the ``==V.*`` shape, return ``V``.""" if isinstance(lower.version, BoundaryVersion) or isinstance( upper.version, BoundaryVersion ): return None if lower.version is None or upper.version is None: return None if not lower.inclusive or upper.inclusive: return None if not (_is_dev0_version(lower.version) and _is_dev0_version(upper.version)): return None if lower.version.epoch != upper.version.epoch: return None lower_release = trim_release(lower.version.release) upper_release = trim_release(upper.version.release) padded_length = max(len(lower_release), len(upper_release)) assert padded_length > 0 lower_release += (0,) * (padded_length - len(lower_release)) upper_release += (0,) * (padded_length - len(upper_release)) if lower_release[:-1] != upper_release[:-1]: return None # A genuine ``==V.*`` spans one family: the upper is exactly the next prefix. # A wider span like ``[3.8.dev0, 3.14.dev0)`` shares the prefix but is not a # single wildcard, so it falls through to the generic ``>=...,<...`` form. if upper_release[-1] != lower_release[-1] + 1: return None return lower.version.__replace__(release=lower_release, dev=None) def _encode_interval( lower: LowerBound, upper: UpperBound, keep_dev0: bool ) -> list[str] | None: """Encode one interval as specifier fragments, or ``None``. Special-cases the ``==V`` singleton (``[V, AFTER_LOCALS(V)]`` for a plain ``V``, and ``[V+local, V+local]`` for a local one) and the ``==V.*`` shape so the fragment is one equality rather than a bound pair. """ # ``[V+local, V+local]`` (an inclusive local point) is the singleton ``==V+local``. if ( lower.version is not None and upper.version is not None and not isinstance(lower.version, BoundaryVersion) and not isinstance(upper.version, BoundaryVersion) and lower.inclusive and upper.inclusive and lower.version == upper.version and lower.version.local is not None ): return [f"=={lower.version}"] # ``[V, AFTER_LOCALS(V)]`` (V without a local) is the singleton ``==V``, # which also matches V's local family: one equality, not ``>=V,<=V``. if ( isinstance(lower.version, Version) and lower.inclusive and upper.inclusive and isinstance(upper.version, BoundaryVersion) and upper.version.kind == BoundaryKind.AFTER_LOCALS and upper.version.version == lower.version ): return [f"=={lower.version}"] wildcard = _detect_equal_wildcard(lower, upper) if wildcard is not None: return [f"=={wildcard}.*"] # A ``[E!0.dev0`` lower has no prerelease-free ``>=`` spelling; within its own # family it is ``==E!0.*`` trimmed by the upper. floor = _epoch_floor_lower(lower, upper) if not keep_dev0 else None if floor is not None: family, excluded_devs, upper_at_cap = floor if excluded_devs > _MAX_EXCLUSION_RUN: return None parts = [f"=={family}.*"] parts.extend(f"!={family.__replace__(dev=d)}" for d in range(excluded_devs)) # ``==E!0.*`` already caps at the next family; add the upper only if tighter. if not upper_at_cap: upper_parts = _encode_upper(upper, keep_dev0) if upper_parts is None: return None parts.extend(upper_parts) return parts lower_parts = _encode_lower(lower, keep_dev0) if lower_parts is None: return None upper_parts = _encode_upper(upper, keep_dev0) if upper_parts is None: return None return lower_parts + upper_parts # Gap encoding: spell the gap between two adjacent intervals as exclusions. def _detect_not_equal( left_upper: UpperBound, right_lower: LowerBound ) -> list[Version] | None: """If the gap between two intervals is a ``!=V`` chain, list its points. A plain exclusive left upper names the first excluded V directly; an inclusive boundary left upper names it via its least successor. Adjacent exclusions (``V`` and its immediate successors) share a single gap spanning a contiguous dev run, so one gap can name a short chain: ``!=1.0,!=1.0.post0.dev0`` is one gap from ``1.0`` up to ``AFTER_LOCALS(1.0.post0.dev0)``. """ if isinstance(left_upper.version, BoundaryVersion): # A boundary upper is always inclusive; its least successor is the first # excluded V (``None`` for a final AFTER_POSTS, which names no point). first = least_version_above(left_upper.version) if first is None: return None elif left_upper.version is None or left_upper.inclusive: return None else: first = left_upper.version if not isinstance(right_lower.version, BoundaryVersion): if ( right_lower.version is not None and not right_lower.inclusive and right_lower.version == first and first.local is not None ): return [first] return None if right_lower.version.kind != BoundaryKind.AFTER_LOCALS: return None # The right interval resumes just above the last excluded V and its locals. last = right_lower.version.version if first == last: return [first] # Adjacent exclusions: the successor of ``first`` opens a ``.dev`` family and # every later point is a higher ``.dev`` in that same family, so the gap is # exactly ``first`` plus a contiguous dev run up to ``last``. Any other gap # (e.g. ``2.3`` to ``AFTER_LOCALS(2.7)`` from complementing ``>=2.3,<=2.7``) # spans a whole interval and fails this test. second = least_version_above(BoundaryVersion(first, BoundaryKind.AFTER_LOCALS)) if ( second is not None and second.dev is not None and last.dev is not None and last.dev >= second.dev and last.__replace__(dev=second.dev) == second ): # ``first`` and the run spell this gap together, so they share the cap. if last.dev - second.dev + 2 > _MAX_EXCLUSION_RUN: return None run = (second.__replace__(dev=d) for d in range(second.dev, last.dev + 1)) return [first, *run] return None def _decompose_dev0_gap( lower_trim: tuple[int, ...], upper_trim: tuple[int, ...], epoch: int, budget: int = _MAX_EXCLUSION_RUN, ) -> list[Version] | None: """Decompose the gap ``[L.dev0, U.dev0)`` into wildcard prefixes. ``lower_trim``/``upper_trim`` are trimmed release tuples with ``lower_trim < upper_trim`` lexicographically. The chain sweeps at the first differing level. The gap is undecomposable when L has trailing components below that level (the chain cannot escape L's subtree), or when the chain, summed across levels, would exceed ``budget`` prefixes. """ diff = 0 while ( diff < len(lower_trim) and diff < len(upper_trim) and lower_trim[diff] == upper_trim[diff] ): diff += 1 if len(lower_trim) > diff + 1: return None common = lower_trim[:diff] lower_val = lower_trim[diff] if len(lower_trim) > diff else 0 upper_val = upper_trim[diff] span = upper_val - lower_val if span > budget: return None fragments = [ Version.from_parts(epoch=epoch, release=(*common, segment)) for segment in range(lower_val, upper_val) ] if len(upper_trim) == diff + 1: return fragments # Recurse into the next release component, charging at least one to the budget # per level (not just the span), so a run of zero-span levels (a release with # many trailing components) exhausts the budget and returns None instead of # recursing past the interpreter's stack limit. tail = _decompose_dev0_gap( (*common, upper_val), upper_trim, epoch, budget - max(span, 1) ) if tail is None: return None return fragments + tail def _encode_gap(left_upper: UpperBound, right_lower: LowerBound) -> list[str] | None: """Encode the gap between two adjacent intervals as ``!=`` fragments. A point chain becomes ``!=V`` fragments and a dev0 family span becomes ``!=P.*`` prefixes, followed by a leading dev run in the last family when the gap ends inside it. Any other gap has no exclusion form and returns ``None``. """ # Cheapest first: a plain ``!=V`` chain never pays for the budgeted # wildcard sweep below. points = _detect_not_equal(left_upper, right_lower) if points is not None: return [f"!={point}" for point in points] # Both wildcard shapes start at an exclusive family base ``L.dev0``. left_v = left_upper.version if ( not isinstance(left_v, Version) or left_upper.inclusive or not _is_dev0_version(left_v) ): return None right_v = right_lower.version if isinstance(right_v, Version) and right_lower.inclusive: # ``[L.dev0, U.dev0)`` is a pure ``!=P.*`` chain up to U's family. upper_dev0 = right_v run_length = 0 budget = _MAX_EXCLUSION_RUN elif ( isinstance(right_v, BoundaryVersion) and right_v.kind == BoundaryKind.AFTER_LOCALS and not right_lower.inclusive ): # ``[L.dev0, AFTER_LOCALS(U.dev(k))]`` ends inside U's family: the # ``!=P.*`` chain, then the ``U.dev0..U.dev(k)`` run. Both spell the # gap together, so they share one ``_MAX_EXCLUSION_RUN`` budget. upper = right_v.version if upper.dev is None or upper.dev + 1 > _MAX_EXCLUSION_RUN: return None upper_dev0 = upper.__replace__(dev=0) run_length = upper.dev + 1 budget = _MAX_EXCLUSION_RUN - run_length else: return None # ``U`` must be a plain release base in L's epoch, above L. # ``_is_dev0_version`` on ``U.dev0`` rejects any pre/post/local on ``U``. if not _is_dev0_version(upper_dev0): return None if left_v.epoch != upper_dev0.epoch or left_v >= upper_dev0: return None prefixes = _decompose_dev0_gap( trim_release(left_v.release), trim_release(upper_dev0.release), left_v.epoch, budget, ) if prefixes is None: return None exclusions = [f"!={prefix}.*" for prefix in prefixes] exclusions.extend(f"!={upper_dev0.__replace__(dev=d)}" for d in range(run_length)) return exclusions def _encode_gaps(bounds: Sequence[Interval]) -> list[str] | None: """Encode every between-interval gap as ``!=`` fragments, or ``None``. When each gap has an exclusion spelling, the intervals fuse into one contiguous span (``==1.* | ==3.*`` is ``!=0.*,!=2.*,<4``): the outer interval across all the bounds plus these exclusions. A gap with no exclusion spelling makes the bounds a disjoint union, which no single set expresses. """ exclusions: list[str] = [] for index in range(1, len(bounds)): gap = _encode_gap(bounds[index - 1][1], bounds[index][0]) if gap is None: return None exclusions.extend(gap) return exclusions def _tighten_no_prereleases(bounds: tuple[Interval, ...]) -> tuple[Interval, ...]: """Snap the range's final upper out of the pre-release band ``False`` drops. An exclusive upper at a final ``V`` admits the versions in ``[V.dev0, V)`` at the bounds level, but a ``prereleases=False`` policy filters them all out, so it accepts the same releases as ``>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> "1.5" in r True >>> "2.0" in r False >>> SpecifierSet(">=2.0,<1.0").to_range().is_empty True PEP 440's ``===`` operator matches a candidate string verbatim (case-insensitive) rather than a set of versions. Ranges built from ``===`` specifiers still support membership, set operations, and conversion back to a :class:`~packaging.specifiers.SpecifierSet`; matching follows the literal-equality rule. A ``===`` literal that names a pre-release is admitted under the default policy by both :meth:`contains` and :meth:`filter`, since it was named outright. .. versionadded:: 26.3 """ __slots__ = ( "_admit", "_admit_arbitrary", "_bounds", "_pre_region", "_prereleases_configured", "_reject", ) #: The disjoint, sorted, non-overlapping interval list. _bounds: tuple[Interval, ...] #: Whether this range matches non-version strings as well as versions. #: True only by construction on ``SpecifierSet("")`` / :meth:`full`. The flag #: rides set algebra but is inert except at full bounds (see #: :meth:`_arbitrary_active`). An intersection or difference that shrinks #: the bounds drops it (``full() & ~full()`` is plain empty, and #: ``full() - r == full() & ~r``); :meth:`complement` and a union of #: empty-bounds operands keep it, so ``~~full() == full()`` and #: ``~full() | ~full() == ~full()``. Part of equality, since membership #: reads it. _admit_arbitrary: bool #: Case-folded strings the range admits in addition to its bounds. #: ``===wat`` produces ``_admit = {"wat"}``. _admit: frozenset[str] #: Case-folded strings the range rejects (overrides ``_admit`` and the #: bounds). Populated by :meth:`complement` of an admit-bearing range and by #: literal resolution in :meth:`_combine_literals`. _reject: frozenset[str] #: Sorted, disjoint intervals where pre-releases are force-admitted under #: the PEP 440 default policy (a ``None`` ``prereleases`` argument and no #: configured override). The opt-in flows only from the pre-release-naming #: specifiers that built the range. :meth:`_build` clips the region to the #: bounds, so it is always a subset of them: an opt-in that overflowed its #: own cap cannot ride a later union into versions no specifier asked for. #: :meth:`union` and :meth:`intersection` accumulate the operands' clipped #: regions and re-clip to the result bounds; :meth:`difference` keeps only #: the minuend's; and :meth:`complement` drops it, since an exclusion grants #: no opt-in. Equality keys on the clipped region, so it stays a congruence. _pre_region: tuple[Interval, ...] #: Raw configured pre-release override of the originating specifier set #: (an explicit ``True`` / ``False``, else ``None``). When set, :meth:`_build` #: forces ``_pre_region`` empty since the policy governs globally. #: :meth:`intersection` and :meth:`union` require it to match on both #: operands. Part of equality. _prereleases_configured: bool | None def __new__(cls, *args: object, **kwargs: object) -> VersionRange: # noqa: PYI034 raise TypeError( "cannot create 'VersionRange' instances directly; use " "SpecifierSet.to_range(), VersionRange.full(), " "VersionRange.empty(), or VersionRange.singleton() instead" ) @classmethod def _build( cls, bounds: tuple[Interval, ...], admit: frozenset[str] = frozenset(), reject: frozenset[str] = frozenset(), admit_arbitrary: bool = False, *, pre_region: tuple[Interval, ...] = (), prereleases_configured: bool | None = None, ) -> VersionRange: """Internal factory; bypasses :meth:`__new__`. Canonicalizes the bounds so equal version sets share one representation, then drops admit literals the bounds already admit and reject literals the bounds do not match anyway. Reject wins over admit on overlap. The pre-release policy is set here and never reassigned afterwards; ``pre_region`` is canonicalized like the bounds and clipped to them, or dropped when a configured policy makes it inert. """ bounds = _canonicalize(bounds) if admit and reject: admit = admit - reject if admit: admit = frozenset( literal for literal in admit if not _struct_admits(bounds, admit_arbitrary, literal) ) if reject: reject = frozenset( literal for literal in reject if _struct_admits(bounds, admit_arbitrary, literal) ) instance = object.__new__(cls) instance._bounds = bounds instance._admit = admit instance._reject = reject instance._admit_arbitrary = admit_arbitrary instance._prereleases_configured = prereleases_configured # A configured policy makes the region inert, so drop it. Otherwise fold # least-successor bounds (_from_specifier_set passes the region unfolded), # so ``>1.0a1`` and ``>=1.0a2.dev0`` carry the same region, then clip it # to the bounds so the opt-in never reaches past the range's own versions. if prereleases_configured is not None or not pre_region: instance._pre_region = () else: instance._pre_region = tuple( intersect_ranges(_canonicalize(pre_region), bounds) ) return instance def _has_literals(self) -> bool: return bool(self._admit) or bool(self._reject) def _arbitrary_active(self) -> bool: """True when ``_admit_arbitrary`` actually admits non-version strings. The flag rides through set algebra but only fires admission on full bounds. Intersection and difference drop it when the bounds shrink, so away from full bounds it survives only on empty-bounds ranges, where it keeps ``~~full() == full()`` and union idempotent. """ return self._admit_arbitrary and self._bounds == FULL_RANGE def _is_plain(self) -> bool: """True when membership is decided by ``_bounds`` alone, enabling the bounds-only fast paths in :meth:`is_subset` and :meth:`is_disjoint`. """ return ( not self._has_literals() and not self._admit_arbitrary and self._prereleases_configured is not False ) def _check_policy_compat(self, other: VersionRange) -> None: """Refuse combining ranges with different pre-release policies.""" if not isinstance(other, VersionRange): raise TypeError(f"expected VersionRange, got {type(other).__name__}") if self._prereleases_configured != other._prereleases_configured: raise ValueError( "Cannot combine VersionRange operands with different " f"pre-release policies: {self._prereleases_configured!r} " f"and {other._prereleases_configured!r}" ) def _merged_region(self, other: VersionRange) -> tuple[Interval, ...]: """Union of ``self`` and ``other``'s opt-in regions. Used by :meth:`union` and :meth:`intersection`; :meth:`_build` clips the merge to the result bounds. A configured operand carries an empty region, so it contributes nothing to the merge. """ # Reuse an operand's canonical tuple when only one side has a region; # an empty side contributes nothing to the union. if not other._pre_region: return self._pre_region if not self._pre_region: return other._pre_region # Both sides carry a region; merge them. _build re-canonicalizes and # clips, so the plain union is fine here. return tuple(_union_ranges(self._pre_region, other._pre_region)) def _with_policy( self, *, pre_region: tuple[Interval, ...], configured: bool | None ) -> VersionRange: """A structural copy of this range carrying the given pre-release policy.""" return self._build( self._bounds, admit=self._admit, reject=self._reject, admit_arbitrary=self._admit_arbitrary, pre_region=pre_region, prereleases_configured=configured, ) @classmethod def empty(cls, *, prereleases: bool | None = None) -> VersionRange: """Return the empty range. No version satisfies it. >>> VersionRange.empty().is_empty True >>> "1.0" in VersionRange.empty() False """ return cls._build((), prereleases_configured=prereleases) @classmethod def full( cls, *, admit_arbitrary: bool = True, prereleases: bool | None = None ) -> VersionRange: """Return the full range. Every PEP 440 version satisfies it. ``admit_arbitrary=False`` restricts the range to PEP 440 versions only (matching the same versions as ``SpecifierSet(">=0.dev0").to_range()``); its complement is :meth:`empty`. The flag propagates through set algebra and is part of equality. Default ``True`` so that ``r & full()`` preserves ``r``'s own flag structurally. >>> "1.0" in VersionRange.full() True >>> "wat" in VersionRange.full() True >>> "wat" in VersionRange.full(admit_arbitrary=False) False """ return cls._build( FULL_RANGE, admit_arbitrary=admit_arbitrary, prereleases_configured=prereleases, ) @classmethod def singleton( cls, version: Version | str, *, prereleases: bool | None = None ) -> VersionRange: """Return the strict singleton range ``{version}``. Built as the closed interval ``[version, version]`` with strict equality. ``Specifier("==V")`` matches ``V+local`` too, so the strict singleton is narrower: >>> "1.0+local" in VersionRange.singleton("1.0") False >>> "1.0+local" in SpecifierSet("==1.0").to_range() True :raises packaging.version.InvalidVersion: if version is a string that does not parse as a PEP 440 version. """ if not isinstance(version, Version): version = Version(version) lower = LowerBound(version, True) upper = UpperBound(version, True) # Collapse the floor: nothing sorts below ``MIN_VERSION``, so the # ``0.dev0`` singleton is ``(-inf, 0.dev0]`` in canonical form. return cls._build( _canonical_floor(((lower, upper),)), prereleases_configured=prereleases, ) def intersection(self, other: VersionRange) -> VersionRange: """Range containing exactly the versions in both self and other. Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised. >>> a = SpecifierSet(">=1.0").to_range() >>> b = SpecifierSet("<2.0").to_range() >>> a.intersection(b) == SpecifierSet(">=1.0,<2.0").to_range() True """ self._check_policy_compat(other) configured = self._prereleases_configured new_bounds = tuple(intersect_ranges(self._bounds, other._bounds)) new_region = self._merged_region(other) # An empty intersection (e.g. ``full() & ~full()``) is the empty range, # so it drops the arbitrary flag, agreeing with difference when the # subtrahend consumes the bounds. combined_arb = ( self._admit_arbitrary and other._admit_arbitrary and bool(new_bounds) ) if not self._has_literals() and not other._has_literals(): return self._build( new_bounds, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, ) return self._combine_literals( other, new_bounds, op=_SetOp.INTERSECTION, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, ) def union(self, other: VersionRange) -> VersionRange: """Range containing every version in self or other. Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised. >>> a = VersionRange.singleton("1.0") >>> b = VersionRange.singleton("2.0") >>> "1.0" in a.union(b) and "2.0" in a.union(b) True >>> "1.5" in a.union(b) False """ self._check_policy_compat(other) configured = self._prereleases_configured new_bounds = tuple(_union_ranges(self._bounds, other._bounds)) new_region = self._merged_region(other) # An empty-bounds operand (e.g. ``~full()``) carries an inert arbitrary # flag only to keep complement an involution; it admits nothing, so it # must not revive arbitrary admission as the union re-widens the bounds. if new_bounds: combined_arb = (self._admit_arbitrary and bool(self._bounds)) or ( other._admit_arbitrary and bool(other._bounds) ) else: # Nothing widened, so keeping the flags keeps ``r | r == r``. combined_arb = self._admit_arbitrary or other._admit_arbitrary if not self._has_literals() and not other._has_literals(): return self._build( new_bounds, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, ) return self._combine_literals( other, new_bounds, op=_SetOp.UNION, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=configured, ) def complement(self) -> VersionRange: """Range containing every version not in self. Preserves the configured pre-release policy. On the version set, double negation holds for a range with no ``===`` literals (the arbitrary-string flag round-trips, so ``~~full() == full()``); for ``===`` ranges complement is one-way. The opt-in region is not restored (see below). The opt-in region is dropped: a complement is an exclusion, and an exclusion expresses no pre-release preference. This is what lets ``a & ~b`` shed ``b``'s opt-in, so an excluded ``b`` never force-admits a pre-release into the result. Complement stays involutive on the version set, but not on the opt-in region: ``~~r`` covers the same versions as ``r`` yet force-admits none of its pre-releases. >>> r = SpecifierSet(">=1.0").to_range() >>> "0.5" in r.complement() True >>> "1.5" in r.complement() False >>> r.complement().complement() == r True """ # Complement swaps literal admission: what the range rejects, its # complement admits. return self._build( tuple(_complement_ranges(self._bounds)), admit=self._reject, reject=self._admit, admit_arbitrary=self._admit_arbitrary, pre_region=(), prereleases_configured=self._prereleases_configured, ) def difference(self, other: VersionRange) -> VersionRange: """Range containing the versions in self but not in other. Matches ``self & ~other`` on the version set and the opt-in region; ``other`` acts as a bounds-only exclusion that grants no opt-in. The arbitrary-string flag survives only when ``other`` removed no versions: a difference that shrinks the bounds forgets it, as ``self & ~other`` would, so no later widening union can revive it. They still part on ``===`` literals, whose complement is one-way: a ``===`` literal stays when ``self`` admits it and ``other`` does not. Both operands must share the same configured pre-release policy (as :meth:`intersection` and :meth:`union` require); otherwise :exc:`ValueError` is raised. ``a - empty()`` returns a range equal to ``a``. >>> a = SpecifierSet(">=1.0").to_range() >>> b = SpecifierSet(">=2.0").to_range() >>> "1.5" in a.difference(b) True >>> "2.0" in a.difference(b) False >>> a.difference(VersionRange.empty()) == a True """ self._check_policy_compat(other) # Subtracting a nothing-admitting set is a no-op; return self unchanged. if not other._bounds and not other._admit: return self # Bound complement is two-way, so subtracting other's versions is an # intersection with its gaps. new_bounds = tuple( intersect_ranges(self._bounds, _complement_ranges(other._bounds)) ) # Match ``self & ~other`` on the opt-in region: a complement carries no # opt-in, so only ``self``'s region survives. ``other`` acts as a # bounds-only exclusion. A configured ``self`` keeps no region. new_region: tuple[Interval, ...] = () if self._prereleases_configured is None: new_region = self._pre_region # Keep self's arbitrary admission only when subtracting removed no # versions. A difference that shrinks the bounds forgets the flag, as # ``self & ~other`` would, so no later widening union can revive an # admission neither operand had. combined_arb = self._admit_arbitrary and new_bounds == self._bounds if not self._has_literals() and not other._has_literals(): return self._build( new_bounds, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=self._prereleases_configured, ) return self._combine_literals( other, new_bounds, op=_SetOp.DIFFERENCE, admit_arbitrary=combined_arb, pre_region=new_region, prereleases_configured=self._prereleases_configured, ) def _combine_literals( self, other: VersionRange, new_bounds: tuple[Interval, ...], *, op: _SetOp, admit_arbitrary: bool, pre_region: tuple[Interval, ...], prereleases_configured: bool | None, ) -> VersionRange: """Resolve admit/reject for ``self`` ``op`` ``other`` over their literals.""" admits: set[str] = set() rejects: set[str] = set() # Each literal is decided independently of the others. for literal in self._admit | self._reject | other._admit | other._reject: self_in = self._matches_literal(literal) other_in = other._matches_literal(literal) if op is _SetOp.INTERSECTION: want = self_in and other_in elif op is _SetOp.UNION: want = self_in or other_in else: want = self_in and not other_in if want: admits.add(literal) else: rejects.add(literal) return self._build( new_bounds, admit=frozenset(admits), reject=frozenset(rejects), admit_arbitrary=admit_arbitrary, pre_region=pre_region, prereleases_configured=prereleases_configured, ) def _matches_literal(self, literal: str) -> bool: """Whether literal (case-folded) matches this range's predicate.""" if literal in self._reject: return False if literal in self._admit: return True parsed = coerce_version(literal) if parsed is None: return self._arbitrary_active() return matches_bounds_only(self._bounds, parsed) def __and__(self, other: object) -> VersionRange: """Operator alias for :meth:`intersection`.""" if not isinstance(other, VersionRange): return NotImplemented return self.intersection(other) def __or__(self, other: object) -> VersionRange: """Operator alias for :meth:`union`.""" if not isinstance(other, VersionRange): return NotImplemented return self.union(other) def __invert__(self) -> VersionRange: """Operator alias for :meth:`complement`.""" return self.complement() def __sub__(self, other: object) -> VersionRange: """Operator alias for :meth:`difference`.""" if not isinstance(other, VersionRange): return NotImplemented return self.difference(other) def is_subset(self, other: VersionRange) -> bool: """Return whether every member of self is also a member of other. On versions and ``===`` literals this is ``self.difference(other).is_empty``: subtracting other leaves nothing behind. A live arbitrary admission (the flag at full bounds) is only a subset of another live one. Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised. >>> inner = SpecifierSet(">=1.5,<1.8").to_range() >>> outer = SpecifierSet(">=1.0,<2.0").to_range() >>> inner.is_subset(outer) True >>> outer.is_subset(inner) False >>> VersionRange.empty().is_subset(outer) True """ self._check_policy_compat(other) # A live arbitrary admission has non-version strings as members, which # no bounds cover; only another live admission contains them. if self._arbitrary_active() and not other._arbitrary_active(): return False # Plain ranges: subset reduces to bounds containment, no algebra needed. if self._is_plain() and other._is_plain(): return not intersect_ranges(self._bounds, _complement_ranges(other._bounds)) # difference (unlike intersection with the one-way complement) resolves # ``===`` literals against both operands, so it stays correct for them. return self.difference(other).is_empty def is_superset(self, other: VersionRange) -> bool: """Return whether every member of other is also a member of self. The mirror of :meth:`is_subset`: ``a.is_superset(b)`` is ``b.is_subset(a)``. Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised. >>> outer = SpecifierSet(">=1.0,<2.0").to_range() >>> outer.is_superset(SpecifierSet(">=1.5,<1.8").to_range()) True """ # Type-guards a non-VersionRange other before delegating to is_subset. self._check_policy_compat(other) return other.is_subset(self) def is_disjoint(self, other: VersionRange) -> bool: """Return whether self and other share no member. Equivalent to ``(self & other).is_empty``. Both operands must share the same configured pre-release policy; otherwise :exc:`ValueError` is raised. >>> a = SpecifierSet(">=1.0,<2.0").to_range() >>> a.is_disjoint(SpecifierSet(">=2.0,<3.0").to_range()) True >>> a.is_disjoint(SpecifierSet(">=1.5,<2.5").to_range()) False """ self._check_policy_compat(other) # Plain ranges: disjointness is an empty bounds intersection. if self._is_plain() and other._is_plain(): return not intersect_ranges(self._bounds, other._bounds) return self.intersection(other).is_empty def _same_releases(self, other: VersionRange) -> bool: """Whether self and other admit the same non-pre-release versions. Used by :meth:`to_specifier_set` under a ``prereleases=False`` policy, where pre-releases are unobservable: the symmetric difference is empty exactly when the two ranges accept the same releases. Both operands carry that policy, so the difference below reads emptiness through it. """ return self.difference(other).is_empty and other.difference(self).is_empty @typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ... @typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ... def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], Version | str] | None = None, ) -> Iterator[Any]: """Yield items from iterable whose version falls inside the range. With prereleases ``None`` the PEP 440 default applies: pre-releases are buffered and only emitted if no final release in iterable is in range, except that a pre-release inside the autodetected opt-in region, or named outright by a ``===`` literal, is force-admitted in place (as ``prereleases=True`` would yield it). A flushed buffer comes after every in-place yield, so the output is not version-sorted. The signature mirrors :meth:`~packaging.specifiers.SpecifierSet.filter`. >>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> list(r.filter(["0.9", "1.5", "2.0"])) ['1.5'] """ region: tuple[Interval, ...] = () if prereleases is None: # The region applies only under the autodetect default; a configured # policy governs instead (and then ``_pre_region`` is already empty). prereleases = self._prereleases_configured region = self._pre_region arbitrary_active = self._arbitrary_active() if not self._admit and not self._reject and not arbitrary_active: # A region spanning the whole bounds force-admits every in-bounds # pre-release, i.e. ``prereleases=True``; take the cheaper no-buffer # path. (Confined to this branch: the admission path orders arbitrary # strings differently under True than under the region.) if region and region == self._bounds: return filter_by_ranges(self._bounds, iterable, key, True) return filter_by_ranges(self._bounds, iterable, key, prereleases, region) return self._filter_with_admission( iterable, key, prereleases, arbitrary_active, region ) def _filter_with_admission( self, iterable: Iterable[Any], key: Callable[[Any], Version | str] | None, prereleases: bool | None, arbitrary_active: bool, region: tuple[Interval, ...], ) -> Iterator[Any]: """Filter for ranges with admit/reject literals or live arbitrary admission (including the universal ``SpecifierSet("")`` range).""" admit_set = self._admit reject_set = self._reject def admit(item: Any) -> tuple[bool, Version | None, bool]: # noqa: ANN401 raw: Version | str = item if key is None else key(item) raw_lower = str(raw).lower() if reject_set and raw_lower in reject_set: return False, None, False if admit_set and raw_lower in admit_set: # An explicit ``===`` literal names this version outright. return True, coerce_version(raw), True parsed = coerce_version(raw) if parsed is None: return arbitrary_active, None, False if not matches_bounds_only(self._bounds, parsed): return False, None, False return True, parsed, False if prereleases is True: for item in iterable: ok, _, _ = admit(item) if ok: yield item return if prereleases is False: for item in iterable: ok, parsed, _ = admit(item) if not ok: continue if parsed is not None and parsed.is_prerelease: continue yield item return # PEP 440 default: emit finals eagerly and buffer the other pre-releases, # releasing the buffer only if no final ever matches. all_nonfinal: list[Any] = [] arbitrary_strings: list[Any] = [] found_final = False for item in iterable: ok, parsed, by_literal = admit(item) if not ok: continue if parsed is None: if found_final: yield item else: arbitrary_strings.append(item) all_nonfinal.append(item) continue if not parsed.is_prerelease: if not found_final: yield from arbitrary_strings arbitrary_strings.clear() found_final = True yield item continue # A pre-release is force-admitted when it is named outright by a # ``===`` literal or falls in the opt-in region, as ``prereleases=True`` # would yield it; otherwise the PEP 440 default buffers it. if by_literal or (region and matches_bounds_only(region, parsed)): yield item continue if not found_final: all_nonfinal.append(item) if not found_final: yield from all_nonfinal @classmethod def _from_specifier_set(cls, specifier_set: SpecifierSet) -> VersionRange: """Build the range accepted by ``specifier_set``. Friend constructor for :meth:`~packaging.specifiers.SpecifierSet.to_range`. The intersection of every specifier in the set: an empty set yields the full range, an unsatisfiable set yields the empty range, and ``===`` specifiers contribute literal-string admission. """ if not specifier_set: result = cls.full() elif not specifier_set._has_arbitrary: result = cls._build( bounds=_canonical_floor(tuple(specifier_set._get_ranges())) ) else: result = cls.full() for spec in specifier_set: if spec.operator == "===": operand = cls._build( bounds=(), admit=frozenset({spec.version.lower()}) ) else: operand = cls._build( bounds=_canonical_floor(tuple(spec._to_ranges())) ) result = result.intersection(operand) # Each pre-release-naming specifier opts its own versions in; their union, # clipped to the set's bounds by _build, is the region. Clipping refolds # under intersection, so a set built directly equals one built by # intersecting its specifiers one at a time. region: list[Interval] = [] if specifier_set._prereleases is None: # a configured policy has no region for spec in specifier_set: # ``===`` literals are not a range; filter force-admits them. if spec.operator != "===" and spec.prereleases: spec_bounds = _canonical_floor(tuple(spec._to_ranges())) region = _union_ranges(region, spec_bounds) return result._with_policy( pre_region=tuple(region), configured=specifier_set._prereleases, ) def to_specifier_set(self) -> SpecifierSet | None: """Return a :class:`~packaging.specifiers.SpecifierSet` matching the same versions as self, or ``None`` if no single set expresses it. PEP 440 has no syntax for the strict singleton ``{V}`` (an exclusive plain-version bound), a disjoint union of two or more intervals, or a partial pre-release opt-in region, so ranges built by set algebra often return ``None``. A gap that takes more than ``_MAX_EXCLUSION_RUN`` contiguous ``!=`` exclusions to spell returns ``None`` too, rather than a pathologically long chain; reaching that cap takes either set algebra or a specifier set that already spells the gap out with over a hundred contiguous ``!=N.*`` exclusions. An empty range maps to ``SpecifierSet("<0")``, unless it still carries the arbitrary-string flag (which no set reproduces), and a full range that admits arbitrary strings maps to ``SpecifierSet("")``. A range built from a :class:`~packaging.specifiers.SpecifierSet` re-encodes, short of that exclusion cap. The result is the simplest candidate whose own :meth:`~packaging.specifiers.SpecifierSet.to_range` reproduces self exactly (bounds, ``===`` literals, and the opt-in region are all part of equality), so it filters the same versions. Two cases relax that exactness without changing what is filtered: an empty range recovers as the canonical empty range (same versions, none, but not self's bounds), and under a ``prereleases=False`` policy the result need only match self's releases, so ``(-inf, 3.14)`` recovers as the tighter ``<3.14`` rather than ``!=3.14,<=3.14``. Each call encodes a handful of candidate spellings and keeps the simplest one that verifies, where verifying means parsing the candidate and round-tripping it through :meth:`~packaging.specifiers.SpecifierSet.to_range`. The work grows with the number of intervals and exclusions in the range, and the result is not cached, so convert once and reuse the returned set rather than converting per candidate version in a hot loop. >>> str(SpecifierSet(">=1.0,<2.0").to_range().to_specifier_set()) '<2.0,>=1.0' >>> str(SpecifierSet("==1.0").to_range().to_specifier_set()) '==1.0' >>> VersionRange.singleton("1.5").to_specifier_set() is None True """ from .specifiers import InvalidSpecifier, SpecifierSet # noqa: PLC0415 configured = self._prereleases_configured if self._reject: return None if self._admit_arbitrary and self._bounds != FULL_RANGE: return None if self.is_empty: # Every member-free spelling accepts the same versions (none), so the # canonical ``<0`` stands in for all of them; a configured policy # rides along it. return SpecifierSet("<0", prereleases=configured) if not self._bounds: # Pure ``===`` literals; only a single literal has a single-set form. if len(self._admit) != 1: return None (literal,) = self._admit bases = [f"==={literal}"] elif self._admit: # Bounds plus literals cannot be one set. return None elif self._bounds == FULL_RANGE: bases = ["" if self._admit_arbitrary else ">=0.dev0"] else: # Under ``prereleases=False`` an exclusive final upper admits the same # releases as ``=0.dev0`` floor restores a ``True`` opt-in that # rode on a floor the clean encoding dropped (e.g. ``>=0.dev0,!=1.0``). # It always recovers the whole bounds as the opt-in region, so it can # only round-trip when self opts everything in. add_floor = configured is None and self._pre_region == self._bounds # Keep the simplest candidate that recovers self. ``==`` compares bounds, # literals, and the opt-in region, so a candidate that would filter # differently, or an op-built range with no single-set form, is rejected # below. Under ``prereleases=False`` a candidate need only match self's # releases (policies never mix, so the excluded pre-releases are # unobservable), which admits the tightened spellings above. best: SpecifierSet | None = None best_key = (0, 0) for base in bases: candidates = [base] if add_floor: candidates.append(f"{base},>=0.dev0" if base else ">=0.dev0") for spec_str in candidates: # A ``===`` literal can hold a comma (its arbitrary version # excludes only whitespace, ``;`` and ``)``), which the set # string splits on. Such a literal has no single specifier-set # spelling, so drop the unparsable candidate and let the range # fall through to ``None`` rather than raise. try: recovered = SpecifierSet(spec_str, prereleases=configured) except InvalidSpecifier: continue # Fewest fragments, then shortest string. Rank before the round # trip so a candidate that cannot beat the best skips the check # (its ``==`` and, under ``False``, two ``difference`` calls). key = (len(recovered), len(str(recovered))) if best is not None and key >= best_key: continue # Accept an exact round trip, or (under ``False``) one that only # matches the releases the policy leaves observable. candidate = recovered.to_range() matches = candidate == self or ( configured is False and self._same_releases(candidate) ) if matches: best, best_key = recovered, key return best @property def is_empty(self) -> bool: """``True`` if no version or string satisfies this range. Agrees with :meth:`~packaging.specifiers.SpecifierSet.is_unsatisfiable`, including the pre-release policy: a range whose only members are pre-releases is empty when that policy excludes them. >>> SpecifierSet(">=2,<1").to_range().is_empty True >>> SpecifierSet(">=1,<2").to_range().is_empty False >>> SpecifierSet("==1.0a1", prereleases=False).to_range().is_empty True """ # An arbitrary-string admission or a surviving ``===`` literal is a # member; a literal that is a pre-release is dropped when the policy is. if self._arbitrary_active(): return False excludes_prereleases = self._prereleases_configured is False for literal in self._admit: if excludes_prereleases: parsed = coerce_version(literal) if parsed is not None and parsed.is_prerelease: continue return False if not self._bounds: return True return excludes_prereleases and ranges_are_prerelease_only(self._bounds) def contains( self, item: Version | str, prereleases: bool | None = None, installed: bool | None = None, ) -> bool: """Return whether item is contained in this range. :param item: a version string or :class:`~packaging.version.Version`. :param prereleases: whether to match pre-releases. ``None`` (default) uses the range's own policy. :param installed: when ``True``, accept a pre-release item even if the range would not otherwise allow it. Unlike :meth:`filter`, this does not consult the autodetected pre-release opt-in region; it reads only the configured policy. This mirrors :meth:`~packaging.specifiers.SpecifierSet.contains` versus :meth:`~packaging.specifiers.SpecifierSet.filter`. Unparsable strings do not match, except where the full ``SpecifierSet`` would also match: the full range admits any string, and a ``===`` range admits items equal to the literal case-insensitively. >>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> r.contains("1.5") True >>> r.contains("2.0") False :raises TypeError: if item is not a str or Version. """ if not isinstance(item, (str, Version)): raise TypeError( f"VersionRange.contains() expected str or Version, " f"got {type(item).__name__}" ) parsed: Version | None = item if isinstance(item, Version) else None if installed and parsed is None: parsed = coerce_version(item) if installed and parsed is not None and parsed.is_prerelease: prereleases = True effective_pre = ( self._prereleases_configured if prereleases is None else prereleases ) if self._admit or self._reject: item_str = str(item).lower() if item_str in self._reject: return False if item_str in self._admit: if effective_pre is False: literal_parsed = coerce_version(item_str) if literal_parsed is not None and literal_parsed.is_prerelease: return False return True if not isinstance(item, Version): if parsed is None: parsed = coerce_version(item) if parsed is None: return self._arbitrary_active() item = parsed if effective_pre is False and item.is_prerelease: return False return matches_bounds_only(self._bounds, item) def __contains__(self, item: Version | str) -> bool: """Return whether item is contained in this range. Forwards to :meth:`contains` with default arguments. >>> "1.5" in SpecifierSet(">=1.0,<2.0").to_range() True """ return self.contains(item) def __eq__(self, other: object) -> bool: """Structural equality. Compares the bounds, the ``===`` admit/reject literals, the arbitrary-string flag, the configured pre-release policy, and the opt-in region, not just the version set. Keying on the region makes equality a congruence (equal ranges stay equal under further operations), so equal implies same :meth:`contains` and :meth:`filter`, but not the converse: an empty range keeps the flag it was built with, so two empty ranges need not be equal. Different specifiers for the same range fold to one canonical form: >>> SpecifierSet(">1.0a1").to_range() == SpecifierSet(">=1.0a2.dev0").to_range() True The opt-in region is part of equality, so ``<=1.0`` (no pre-releases) and ``<1.0.post0.dev0`` (autodetects a ``.dev`` opt-in) cover the same versions yet compare unequal: >>> le, lt = SpecifierSet("<=1.0"), SpecifierSet("<1.0.post0.dev0") >>> le.to_range() == lt.to_range() False >>> r = SpecifierSet(">=1.0,<2.0").to_range() >>> r == SpecifierSet(">=1.0,<2.0").to_range() True """ if not isinstance(other, VersionRange): return NotImplemented return ( self._bounds == other._bounds and self._admit == other._admit and self._reject == other._reject and self._admit_arbitrary == other._admit_arbitrary and self._prereleases_configured == other._prereleases_configured and self._pre_region == other._pre_region ) def __hash__(self) -> int: return hash( ( self._bounds, self._admit, self._reject, self._admit_arbitrary, self._prereleases_configured, self._pre_region, ) ) def __repr__(self) -> str: """Human-readable representation for debugging. >>> SpecifierSet(">=1.0,<2.0").to_range() >>> SpecifierSet("").to_range() >>> SpecifierSet(">=2.0,<1.0").to_range() """ # Body: the bounds and any ``===``-admitted literals. parts: list[str] = [] if self._bounds: parts.append(_format_intervals(self._bounds)) if self._admit: parts.append("{" + ", ".join(sorted(self._admit)) + "}") body = " | ".join(parts) if parts else "(empty)" # Rejected literals subtract from the body. if self._reject: body = f"{body} \\ {{{', '.join(sorted(self._reject))}}}" # Tail: the policy flags carried alongside the version set. tail = "" if self._admit_arbitrary: tail += " arbitrary" if self._prereleases_configured is not None: tail += f" pre={self._prereleases_configured}" if self._pre_region: tail += f" pre-region={_format_intervals(self._pre_region)!r}" return f"<{self.__class__.__name__} {body!r}{tail}>" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4537523 packaging-26.3/src/packaging/requirements.py0000644000000000000000000001560015234171317016134 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 TYPE_CHECKING from ._parser import parse_requirement as _parse_requirement from ._tokenizer import ParserSyntaxError from .markers import Marker, _normalize_extra_values from .specifiers import InvalidSpecifier, SpecifierSet from .utils import canonicalize_name if TYPE_CHECKING: from collections.abc import Iterator __all__ = [ "InvalidRequirement", "Requirement", ] def __dir__() -> list[str]: return __all__ class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. .. versionadded:: 16.1 """ class Requirement: """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. .. versionadded:: 16.1 .. versionchanged:: 22.0 Added equality (``__eq__``) and hashing (``__hash__``) so requirements can be compared and stored in sets / dicts. .. versionchanged:: 23.2 Equality and hashing began canonicalizing requirement names, so requirements whose names differ only by normalization (e.g. ``Requirement("Foo")`` vs ``Requirement("foo")``) now compare and hash equal. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. .. versionchanged:: 26.3 The dedicated pickle support introduced in 26.2 did not preserve the specifier's explicit :attr:`~packaging.specifiers.SpecifierSet.prereleases` override; it is now included again. Equality and hashing normalize requirement names, extras, and equivalent specifiers. The string representation still preserves the parsed name and extras spelling. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? __slots__ = ("extras", "marker", "name", "specifier", "url") def __init__(self, requirement_string: str) -> None: try: parsed = _parse_requirement(requirement_string) except ParserSyntaxError as e: raise InvalidRequirement(str(e)) from e self.name: str = parsed.name self.url: str | None = parsed.url or None self.extras: set[str] = set(parsed.extras) try: self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) except InvalidSpecifier as e: raise InvalidRequirement(str(e)) from e self.marker: Marker | None = None if parsed.marker is not None: self.marker = Marker.__new__(Marker) self.marker._markers = _normalize_extra_values(parsed.marker) def _iter_parts(self, name: str) -> Iterator[str]: yield name if self.extras: formatted_extras = ",".join(sorted(self.extras)) yield f"[{formatted_extras}]" if self.specifier: yield str(self.specifier) if self.url: yield f" @ {self.url}" if self.marker: yield " " if self.marker: yield f"; {self.marker}" def __getstate__(self) -> tuple[str, bool | None]: # Return the requirement string for compactness and stability, paired # with the specifier's explicit prereleases override, which is not # captured by the string form. Re-parsed on load to reconstruct all # other fields. return (str(self), self.specifier._prereleases) def __setstate__(self, state: object) -> None: if isinstance(state, str): # Format (26.2): just the requirement string. requirement_string: str = state prereleases: bool | None = None elif ( isinstance(state, tuple) and len(state) == 2 and isinstance(state[0], str) and (state[1] is None or isinstance(state[1], bool)) ): # New format (26.3+): (requirement string, specifier prereleases). requirement_string, prereleases = state elif isinstance(state, dict) and state.keys() >= set(self.__slots__): # Old format (packaging <= 26.1, no __slots__): plain __dict__. for key in self.__slots__: setattr(self, key, state[key]) return else: raise TypeError(f"Cannot restore Requirement from {state!r}") try: tmp = Requirement(requirement_string) except InvalidRequirement as exc: raise TypeError(f"Cannot restore Requirement from {state!r}") from exc self.name = tmp.name self.url = tmp.url self.extras = tmp.extras self.specifier = tmp.specifier self.specifier._prereleases = prereleases self.marker = tmp.marker def __str__(self) -> str: return "".join(self._iter_parts(self.name)) def __repr__(self) -> str: return f"<{self.__class__.__name__}({str(self)!r})>" def __hash__(self) -> int: # Mirror __eq__ by hashing the canonical specifier object rather than # its raw string. ``_iter_parts`` yields ``str(self.specifier)``, which # is non-canonical, so trailing-zero-equivalent requirements such as # ``foo==1.0.0`` and ``foo==1.0.0.0`` (which compare equal) would # otherwise hash differently, breaking the hash/__eq__ invariant. return hash( ( canonicalize_name(self.name), frozenset(canonicalize_name(e) for e in self.extras), self.specifier, self.url, self.marker, ) ) def __eq__(self, other: object) -> bool: if not isinstance(other, Requirement): return NotImplemented # Extras must be normalized before comparison as per PEP 685. self_extras = frozenset(canonicalize_name(e) for e in self.extras) other_extras = frozenset(canonicalize_name(e) for e in other.extras) return ( canonicalize_name(self.name) == canonicalize_name(other.name) and self_extras == other_extras and self.specifier == other.specifier and self.url == other.url and self.marker == other.marker ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4537523 packaging-26.3/src/packaging/specifiers.py0000644000000000000000000014707615234171317015562 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 re import typing from typing import ( TYPE_CHECKING, Any, Callable, Final, TypeVar, Union, ) from ._ranges import ( FULL_RANGE, bounds_for_spec, coerce_version, filter_by_ranges, intersect_specifier_bounds, matches_bounds_only, ranges_are_prerelease_only, resolve_prereleases, trim_release, ) from .utils import canonicalize_version from .version import Version if TYPE_CHECKING: import sys from collections.abc import Iterable, Iterator, Sequence if sys.version_info >= (3, 10): from typing import TypeGuard else: from typing_extensions import TypeGuard from . import ranges from ._ranges import Interval __all__ = [ "BaseSpecifier", "InvalidSpecifier", "Specifier", "SpecifierSet", ] def __dir__() -> list[str]: return __all__ def _validate_spec(spec: object, /) -> TypeGuard[tuple[str, str]]: return ( isinstance(spec, tuple) and len(spec) == 2 and isinstance(spec[0], str) and isinstance(spec[1], str) ) def _validate_pre(pre: object, /) -> TypeGuard[bool | None]: return pre is None or isinstance(pre, bool) T = TypeVar("T") UnparsedVersion = Union[Version, str] UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) # Operators whose result is just a direct Version comparison, given a parsed # item with no local. ``<=``/``==``/``!=`` need that no-local guard because # PEP 440 strips locals on those; ``>=`` works regardless. _DIRECT_COMPARE_OPS: dict[str, Callable[[Version, Version], bool]] = { ">=": Version.__ge__, "<=": Version.__le__, "==": Version.__eq__, "!=": Version.__ne__, } def _fast_match(specifier: Specifier, parsed: Version) -> bool | None: """Match ``parsed`` against ``specifier`` without building a range. Handles ``>=``, ``<=``, ``==``, ``!=``, ``<``, ``>`` when the spec is not a wildcard and ``parsed`` has no local. Returns ``None`` when the range path must be used. Pre-release policy is left to the caller. """ op_str, ver_str = specifier._spec if ver_str.endswith(".*") or parsed.local is not None: return None direct_compare = _DIRECT_COMPARE_OPS.get(op_str) if direct_compare is not None: return direct_compare(parsed, specifier._require_spec_version(ver_str)) if op_str in ("<", ">"): spec_v = specifier._require_spec_version(ver_str) # ``V`` carve out V's family (pre/dev/post); that only # matters when parsed shares V's epoch and trimmed release. # Otherwise a direct cmpkey comparison is correct. if parsed.epoch != spec_v.epoch or trim_release(parsed.release) != trim_release( spec_v.release ): return parsed < spec_v if op_str == "<" else parsed > spec_v return None return None class InvalidSpecifier(ValueError): """ Raised when attempting to create a :class:`Specifier` with a specifier string that is invalid. >>> Specifier("lolwat") Traceback (most recent call last): ... packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' """ class BaseSpecifier(metaclass=abc.ABCMeta): """ Abstract base class for :class:`Specifier` and :class:`SpecifierSet`. """ __slots__ = () __match_args__ = ("_str",) @property def _str(self) -> str: """Internal property for match_args""" return str(self) @abc.abstractmethod def __str__(self) -> str: """ Returns the str representation of this Specifier-like object. This should be representative of the Specifier itself. """ @abc.abstractmethod def __hash__(self) -> int: """ Returns a hash value for this Specifier-like object. """ @abc.abstractmethod def __eq__(self, other: object) -> bool: """ Returns a boolean representing whether or not the two Specifier-like objects are equal. :param other: The other object to check against. """ @property @abc.abstractmethod def prereleases(self) -> bool | None: """Whether or not pre-releases as a whole are allowed. This can be set to either ``True`` or ``False`` to explicitly enable or disable prereleases or it can be set to ``None`` (the default) to use default semantics. """ @prereleases.setter # noqa: B027 def prereleases(self, value: bool) -> None: """Setter for :attr:`prereleases`. :param value: The value to set. """ @abc.abstractmethod def contains(self, item: str, prereleases: bool | None = None) -> bool: """ Determines if the given item is contained within this specifier. """ @typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ... @typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ... @abc.abstractmethod def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """ class Specifier(BaseSpecifier): """This class abstracts handling of version specifiers. .. tip:: It is generally not required to instantiate this manually. You should instead prefer to work with :class:`SpecifierSet` instead, which can parse comma-separated version specifiers (which is what package metadata contains). Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ __slots__ = ( "_prereleases", "_ranges", "_spec", "_spec_version", ) _specifier_regex_str = r""" (?: (?: # The identity operators allow for an escape hatch that will # do an exact string match of the version you wish to install. # This will not be parsed by PEP 440 and we cannot determine # any semantic meaning from it. This operator is discouraged # but included entirely as an escape hatch. === # Only match for the identity operator \s* [^\s;)]* # The arbitrary version can be just about anything, # we match everything except for whitespace, a # semi-colon for marker support, and a closing paren # since versions can be enclosed in them. ) | (?: # The (non)equality operators allow for wild card and local # versions to be specified so we have to define these two # operators separately to enable that. (?:==|!=) # Only match for equals and not equals \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release # You cannot use a wild card and a pre-release, post-release, a dev or # local version together so group them with a | and make them optional. (?: \.\* # Wild card syntax of .* | (?a: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?a: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release (?a:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local )? ) | (?: # The compatible operator requires at least two digits in the # release segment. (?:~=) # Only match for the compatible operator \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) (?: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) | (?: # All other operators only allow a sub set of what the # (non)equality operators do. Specifically they do not allow # local versions to be specified nor do they allow the prefix # matching wild cards. (?:<=|>=|<|>) \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release (?a: # pre release [-_\.]? (alpha|beta|preview|pre|a|b|c|rc) [-_\.]? [0-9]* )? (?a: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) ) """ _regex = re.compile( r"\s*" + _specifier_regex_str + r"\s*", re.VERBOSE | re.IGNORECASE ) # Legacy unused attribute, kept for backward compatibility _operators: Final = { "~=": "compatible", "==": "equal", "!=": "not_equal", "<=": "less_than_equal", ">=": "greater_than_equal", "<": "less_than", ">": "greater_than", "===": "arbitrary", } def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: """Initialize a Specifier instance. :param spec: The string representation of a specifier which will be parsed and normalized before use. :param prereleases: This tells the specifier if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given specifier is invalid (i.e. bad syntax). """ if not self._regex.fullmatch(spec): raise InvalidSpecifier(f"Invalid specifier: {spec!r}") spec = spec.strip() if spec.startswith("==="): operator, version = spec[:3], spec[3:].strip() elif spec.startswith(("~=", "==", "!=", "<=", ">=")): operator, version = spec[:2], spec[2:].strip() else: operator, version = spec[:1], spec[1:].strip() self._spec: tuple[str, str] = (operator, version) # Store whether or not this Specifier should accept prereleases self._prereleases = prereleases # Specifier version cache self._spec_version: tuple[str, Version] | None = None # Version range cache (populated by _to_ranges) self._ranges: Sequence[Interval] | None = None def _get_spec_version(self, version: str) -> Version | None: """One element cache, as only one spec Version is needed per Specifier.""" if self._spec_version is not None and self._spec_version[0] == version: return self._spec_version[1] version_specifier = coerce_version(version) if version_specifier is None: return None self._spec_version = (version, version_specifier) return version_specifier def _require_spec_version(self, version: str) -> Version: """Get spec version, asserting it's valid (not for === operator). This method should only be called for operators where version strings are guaranteed to be valid PEP 440 versions (not ===). """ spec_version = self._get_spec_version(version) assert spec_version is not None return spec_version def _to_ranges(self) -> Sequence[Interval]: """Convert this specifier to sorted, non-overlapping version ranges. Each standard operator maps to one or two ranges. ``===`` is modeled as full range (actual check done separately). Cached. """ if self._ranges is not None: return self._ranges op = self.operator ver_str = self.version if op == "===": result: Sequence[Interval] = FULL_RANGE else: version = self._require_spec_version(ver_str.removesuffix(".*")) result = bounds_for_spec(op, ver_str, version) self._ranges = result return result @property def prereleases(self) -> bool | None: # If there is an explicit prereleases set for this, then we'll just # blindly use that. if self._prereleases is not None: return self._prereleases # Only the "!=" operator does not imply prereleases when # the version in the specifier is a prerelease. operator, version_str = self._spec if operator == "!=": return False # The == specifier with trailing .* cannot include prereleases # e.g. "==1.0a1.*" is not valid. if operator == "==" and version_str.endswith(".*"): return False # "===" can have arbitrary string versions, so we cannot parse # those, we take prereleases as unknown (None) for those. version = self._get_spec_version(version_str) if version is None: return None # For all other operators, use the check if spec Version # object implies pre-releases. return version.is_prerelease @prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value def __getstate__(self) -> tuple[tuple[str, str], bool | None]: # Return state as a 2-item tuple for compactness: # ((operator, version), prereleases) # Cache members are excluded and will be recomputed on demand. return (self._spec, self._prereleases) def __setstate__(self, state: object) -> None: # Always discard cached values - they will be recomputed on demand. self._spec_version = None self._ranges = None if isinstance(state, tuple): if len(state) == 2: # New format (26.2+): ((operator, version), prereleases) spec, prereleases = state if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return if len(state) == 2 and isinstance(state[1], dict): # Format (packaging 26.0-26.1): (None, {slot: value}). _, slot_dict = state spec = slot_dict.get("_spec") prereleases = slot_dict.get("_prereleases", "invalid") if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return if isinstance(state, dict): # Old format (packaging <= 25.x, no __slots__): state is a plain dict. spec = state.get("_spec") prereleases = state.get("_prereleases", "invalid") if _validate_spec(spec) and _validate_pre(prereleases): self._spec = spec self._prereleases = prereleases return raise TypeError(f"Cannot restore Specifier from {state!r}") @property def operator(self) -> str: """The operator of this specifier. >>> Specifier("==1.2.3").operator '==' """ return self._spec[0] @property def version(self) -> str: """The version of this specifier. >>> Specifier("==1.2.3").version '1.2.3' """ return self._spec[1] def __repr__(self) -> str: """A representation of the Specifier that shows all internal state. >>> Specifier('>=1.0.0') =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 __contains__(self, item: str | Version) -> bool: """Return whether or not the item is contained in this specifier. :param item: The item to check for. This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed. >>> "1.2.3" in Specifier(">=1.2.3") True >>> Version("1.2.3") in Specifier(">=1.2.3") True >>> "1.0.0" in Specifier(">=1.2.3") False >>> "1.3.0a1" in Specifier(">=1.2.3") True >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) True """ return self.contains(item) def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: """Return whether or not the item is contained in this specifier. :param item: The item to check for, which can be a version string or a :class:`~packaging.version.Version` instance. :param prereleases: Whether or not to match prereleases with this Specifier. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases, as there are no other versions. >>> Specifier(">=1.2.3").contains("1.2.3") True >>> Specifier(">=1.2.3").contains(Version("1.2.3")) True >>> Specifier(">=1.2.3").contains("1.0.0") False >>> Specifier(">=1.2.3").contains("1.3.0a1") True >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1") False >>> Specifier(">=1.2.3").contains("1.3.0a1") True .. versionchanged:: 26.0 With ``prereleases=None``, a prerelease now matches. A single version has no alternatives, so the :pep:`440` rule to accept prereleases when nothing else satisfies the specifier applies. Earlier versions rejected it. An unparsable version now returns ``False`` instead of raising :exc:`~packaging.version.InvalidVersion`. """ # ``===`` compares the raw string, so a Version parse here would # be wasted. if self._spec[0] == "===": return bool(list(self.filter([item], prereleases=prereleases))) parsed = coerce_version(item) if parsed is None: # Standard operators never match an unparsable input. return False if prereleases is None: prereleases = resolve_prereleases(self._prereleases, self.prereleases) if prereleases is False and parsed.is_prerelease: return False # ``_fast_match`` answers the simple operators without building a # range; otherwise fall back to the engine's bounds membership. match = _fast_match(self, parsed) if match is not None: return match return matches_bounds_only(self._to_ranges(), parsed) @typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ... @typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ... def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """Filter items in the given iterable, that match the specifier. :param iterable: An iterable that can contain version strings and :class:`~packaging.version.Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions. :param key: A callable that takes a single argument (an item from the iterable) and returns a version string or :class:`~packaging.version.Version` instance to be used for filtering. >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) ['1.2.3', '1.3', ] >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(Specifier(">=1.2.3").filter( ... [{"ver": "1.2"}, {"ver": "1.3"}], ... key=lambda x: x["ver"])) [{'ver': '1.3'}] .. versionchanged:: 26.1 Added the ``key`` parameter. """ if prereleases is None: prereleases = resolve_prereleases(self._prereleases, self.prereleases) if self.operator == "===": spec_lower = self.version.lower() matches = ( item for item in iterable if str(item if key is None else key(item)).lower() == spec_lower ) return _apply_prereleases_filter(matches, key, prereleases) return filter_by_ranges(self._to_ranges(), iterable, key, prereleases) def _apply_prereleases_filter( matches: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None, prereleases: bool | None, ) -> Iterator[Any]: """Apply ``prereleases=`` handling to an already-matched iterable. ``None`` means PEP 440 default (buffer pre-releases until a final appears); ``True`` yields everything; ``False`` drops pre-releases. """ if prereleases is None: return _pep440_filter_prereleases(matches, key) if prereleases: return iter(matches) return ( item for item in matches if (parsed := coerce_version(item if key is None else key(item))) is None or not parsed.is_prerelease ) class SpecifierSet(BaseSpecifier): """This class abstracts handling of a set of version specifiers. It can be passed a single specifier (``>=3.0``), a comma-separated list of specifiers (``>=3.0,!=3.1``), or no specifier at all. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ __slots__ = ( "_canonicalized", "_has_arbitrary", "_is_unsatisfiable", "_prereleases", "_ranges", "_specs", ) def __init__( self, specifiers: str | Iterable[Specifier] = "", prereleases: bool | None = None, ) -> None: """Initialize a SpecifierSet instance. :param specifiers: The string representation of a specifier or a comma-separated list of specifiers which will be parsed and normalized before use. May also be an iterable of ``Specifier`` instances, which will be used as is. :param prereleases: This tells the SpecifierSet if it should accept prerelease versions if applicable or not. The default of ``None`` will autodetect it from the given specifiers. :raises InvalidSpecifier: If the given ``specifiers`` are not parseable than this exception will be raised. """ if isinstance(specifiers, str): # Split on `,` to break each individual specifier into its own item, and # strip each item to remove leading/trailing whitespace. split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] self._specs: tuple[Specifier, ...] = tuple(map(Specifier, split_specifiers)) # Fast substring check; avoids iterating parsed specs. self._has_arbitrary = "===" in specifiers else: self._specs = tuple(specifiers) # Substring check works for both Specifier objects and plain # strings (setuptools passes lists of strings). self._has_arbitrary = any("===" in str(s) for s in self._specs) self._canonicalized = len(self._specs) <= 1 self._is_unsatisfiable: bool | None = None self._ranges: Sequence[Interval] | None = None # Store our prereleases value so we can use it later to determine if # we accept prereleases or not. self._prereleases = prereleases def _canonical_specs(self) -> tuple[Specifier, ...]: """Deduplicate, sort, and cache specs for order-sensitive operations.""" if not self._canonicalized: self._specs = tuple(dict.fromkeys(sorted(self._specs, key=str))) self._canonicalized = True return self._specs @property def prereleases(self) -> bool | None: # If we have been given an explicit prerelease modifier, then we'll # pass that through here. if self._prereleases is not None: return self._prereleases # If we don't have any specifiers, and we don't have a forced value, # then we'll just return None since we don't know if this should have # pre-releases or not. if not self._specs: return None # Otherwise we'll see if any of the given specifiers accept # prereleases, if any of them do we'll return True, otherwise False. if any(s.prereleases for s in self._specs): return True return None @prereleases.setter def prereleases(self, value: bool | None) -> None: self._prereleases = value self._is_unsatisfiable = None def __getstate__(self) -> tuple[tuple[Specifier, ...], bool | None]: # Return state as a 2-item tuple for compactness: # (specs, prereleases) # Cache members are excluded and will be recomputed on demand. return (self._specs, self._prereleases) def __setstate__(self, state: object) -> None: # Always discard cached values - they will be recomputed on demand. self._ranges = None self._is_unsatisfiable = None if isinstance(state, tuple): if len(state) == 2: # New format (26.2+): (specs, prereleases) specs, prereleases = state if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in specs) return if len(state) == 2 and isinstance(state[1], dict): # Format (packaging 26.0-26.1): (None, {slot: value}). _, slot_dict = state specs = slot_dict.get("_specs", ()) prereleases = slot_dict.get("_prereleases") # Convert frozenset to tuple (26.0 stored as frozenset) if isinstance(specs, frozenset): specs = tuple(sorted(specs, key=str)) if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(self._specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in self._specs) return if isinstance(state, dict): # Old format (packaging <= 25.x, no __slots__): state is a plain dict. specs = state.get("_specs", ()) prereleases = state.get("_prereleases") # Convert frozenset to tuple (26.0 stored as frozenset) if isinstance(specs, frozenset): specs = tuple(sorted(specs, key=str)) if ( isinstance(specs, tuple) and all(isinstance(s, Specifier) for s in specs) and _validate_pre(prereleases) ): self._specs = specs self._prereleases = prereleases self._canonicalized = len(self._specs) <= 1 self._has_arbitrary = any("===" in str(s) for s in self._specs) return raise TypeError(f"Cannot restore SpecifierSet from {state!r}") def __repr__(self) -> str: """A representation of the specifier set that shows all internal state. Note that the ordering of the individual specifiers within the set may not match the input string. >>> SpecifierSet('>=1.0.0,!=2.0.0') =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 # 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[Interval]: """Intersect all specifiers into a single sequence of version ranges. Empty when unsatisfiable. Callers must ensure ``self._specs`` is non-empty. """ if self._ranges is not None: return self._ranges self._ranges = intersect_specifier_bounds(s._to_ranges() for s in self._specs) return self._ranges def is_unsatisfiable(self) -> bool: """Check whether this specifier set can never be satisfied. Returns True if no version can satisfy all specifiers simultaneously. >>> SpecifierSet(">=2.0,<1.0").is_unsatisfiable() True >>> SpecifierSet(">=1.0,<2.0").is_unsatisfiable() False >>> SpecifierSet("").is_unsatisfiable() False >>> SpecifierSet("==1.0,!=1.0").is_unsatisfiable() True .. versionadded:: 26.1 """ cached = self._is_unsatisfiable if cached is not None: return cached if not self._specs: self._is_unsatisfiable = False return False result = not self._get_ranges() if not result: result = self._check_arbitrary_unsatisfiable() if not result and self.prereleases is False: result = ranges_are_prerelease_only(self._get_ranges()) self._is_unsatisfiable = result return result def _check_arbitrary_unsatisfiable(self) -> bool: """Check === (arbitrary equality) specs for unsatisfiability. === uses case-insensitive string comparison, so the only candidate that can match ``===V`` is the literal string V. This method checks whether that candidate is excluded by other specifiers. """ arbitrary = [s for s in self._specs if s.operator == "==="] if not arbitrary: return False # Multiple === must agree on the same string (case-insensitive). first = arbitrary[0].version.lower() if any(s.version.lower() != first for s in arbitrary[1:]): return True # The sole candidate is the === version string. Check whether # it can satisfy every standard spec. candidate = coerce_version(arbitrary[0].version) # With prereleases=False, a prerelease candidate is excluded # by contains() before the === string check even runs. if ( self.prereleases is False and candidate is not None and candidate.is_prerelease ): return True standard = [s for s in self._specs if s.operator != "==="] if not standard: return False if candidate is None: # Unparsable string cannot satisfy any standard spec. return True return not all(s.contains(candidate) for s in standard) def to_range(self) -> ranges.VersionRange: """Return the :class:`~packaging.ranges.VersionRange` this set accepts. An empty set yields the full range; an unsatisfiable set yields the empty range. ``===`` specifiers contribute literal-string admission. >>> SpecifierSet(">=1.0,<2.0").to_range() .. versionadded:: 26.3 """ from .ranges import VersionRange # noqa: PLC0415 return VersionRange._from_specifier_set(self) def _check_relation_operand(self, other: object) -> None: if not isinstance(other, SpecifierSet): raise TypeError("expected a SpecifierSet") if self._has_arbitrary or other._has_arbitrary: raise ValueError("set relations do not support === specifiers") def is_subset(self, other: SpecifierSet) -> bool: """Return whether every version matching this set also matches other. :raises ValueError: If either set uses ``===`` specifiers, or the two sets were given different ``prereleases`` arguments (unset on one side counts as different). :raises TypeError: If other is not a :class:`SpecifierSet`. >>> SpecifierSet(">=3.12,<3.13").is_subset(SpecifierSet(">=3.12")) True >>> SpecifierSet(">=3.12").is_subset(SpecifierSet(">=3.12,<3.13")) False .. versionadded:: 26.3 """ self._check_relation_operand(other) return self.to_range().is_subset(other.to_range()) def is_superset(self, other: SpecifierSet) -> bool: """Return whether every version matching other also matches this set. :raises ValueError: If either set uses ``===`` specifiers, or the two sets were given different ``prereleases`` arguments (unset on one side counts as different). :raises TypeError: If other is not a :class:`SpecifierSet`. >>> SpecifierSet(">=3.12").is_superset(SpecifierSet(">=3.12,<3.13")) True .. versionadded:: 26.3 """ self._check_relation_operand(other) return self.to_range().is_superset(other.to_range()) def is_disjoint(self, other: SpecifierSet) -> bool: """Return whether this set and other share no matching versions. :raises ValueError: If either set uses ``===`` specifiers, or the two sets were given different ``prereleases`` arguments (unset on one side counts as different). :raises TypeError: If other is not a :class:`SpecifierSet`. >>> SpecifierSet("<3.12").is_disjoint(SpecifierSet(">=3.12")) True >>> SpecifierSet("<3.12").is_disjoint(SpecifierSet(">=3.11")) False .. versionadded:: 26.3 """ self._check_relation_operand(other) return self.to_range().is_disjoint(other.to_range()) def __contains__(self, item: UnparsedVersion) -> bool: """Return whether or not the item is contained in this specifier. :param item: The item to check for. This is used for the ``in`` operator and behaves the same as :meth:`contains` with no ``prereleases`` argument passed. >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") True >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") True >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") False >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") True >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) True """ return self.contains(item) def contains( self, item: UnparsedVersion, prereleases: bool | None = None, installed: bool | None = None, ) -> bool: """Return whether or not the item is contained in this SpecifierSet. :param item: The item to check for, which can be a version string or a :class:`~packaging.version.Version` instance. :param prereleases: Whether or not to match prereleases with this SpecifierSet. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases, as there are no other versions. :param installed: Whether or not the item is installed. If set to ``True``, it will accept prerelease versions even if the specifier does not allow them. >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) True >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") False >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") True >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1") False >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) True .. versionchanged:: 26.0 With ``prereleases=None``, a prerelease now matches. A single version has no alternatives, so the :pep:`440` rule to accept prereleases when nothing else satisfies the specifiers applies. Earlier versions rejected it. An unparsable version now returns ``False`` instead of raising :exc:`~packaging.version.InvalidVersion`. """ version = coerce_version(item) if version is not None and installed and version.is_prerelease: prereleases = True # When item is a string and === is involved, keep it as-is # so the comparison isn't done against the normalized form. if version is None or (self._has_arbitrary and not isinstance(item, Version)): check_item = item else: check_item = version # Fast path: a parseable, local-free version against a rangelike set. # A local on ``version`` needs PEP 440 stripping that the range path # applies. if ( version is not None and not self._has_arbitrary and version.local is None and self._specs ): if version.is_prerelease and ( prereleases is False or (prereleases is None and self._prereleases is False) ): return False bounds = self._ranges if bounds is None: # Per-spec ``_fast_match`` answers a set of simple specifiers # without folding anything. If a spec needs the range path, # fold the intersected bounds once and cache them so repeated # checks on the same set stay cheap. for spec in self._specs: match = _fast_match(spec, version) if match is None: break if not match: return False else: return True bounds = self._ranges = self._get_ranges() return matches_bounds_only(bounds, version) return bool(list(self.filter([check_item], prereleases=prereleases))) @typing.overload def filter( self, iterable: Iterable[UnparsedVersionVar], prereleases: bool | None = None, key: None = ..., ) -> Iterator[UnparsedVersionVar]: ... @typing.overload def filter( self, iterable: Iterable[T], prereleases: bool | None = None, key: Callable[[T], UnparsedVersion] = ..., ) -> Iterator[T]: ... def filter( self, iterable: Iterable[Any], prereleases: bool | None = None, key: Callable[[Any], UnparsedVersion] | None = None, ) -> Iterator[Any]: """Filter items in the given iterable, that match the specifiers in this set. :param iterable: An iterable that can contain version strings and :class:`~packaging.version.Version` instances. The items in the iterable will be filtered according to the specifier. :param prereleases: Whether or not to allow prereleases in the returned iterator. If set to ``None`` (the default), it will follow the recommendation from :pep:`440` and match prereleases if there are no other versions. :param key: A callable that takes a single argument (an item from the iterable) and returns a version string or :class:`~packaging.version.Version` instance to be used for filtering. >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) ['1.3', ] >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) ['1.5a1'] >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet(">=1.2.3").filter( ... [{"ver": "1.2"}, {"ver": "1.3"}], ... key=lambda x: x["ver"])) [{'ver': '1.3'}] An "empty" SpecifierSet will filter items based on the presence of prerelease versions in the set. >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) ['1.3'] >>> list(SpecifierSet("").filter(["1.5a1"])) ['1.5a1'] >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) ['1.3', '1.5a1'] >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) ['1.3', '1.5a1'] .. versionchanged:: 26.0 Prerelease filtering now follows the PEP 440 recommendation of yielding prereleases only when no final release is present. .. versionchanged:: 26.1 Added the ``key`` parameter. """ # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None and self.prereleases is not None: prereleases = self.prereleases if self._specs: if self._has_arbitrary: # Slow path for === specs = self._specs matches = ( item for item in iterable if all( s.contains(item if key is None else key(item), prereleases=True) for s in specs ) ) return _apply_prereleases_filter(matches, key, prereleases) ranges = self._ranges if ranges is None: ranges = self._get_ranges() return filter_by_ranges(ranges, iterable, key, prereleases) # Empty SpecifierSet. return _apply_prereleases_filter(iterable, key, prereleases) def _pep440_filter_prereleases( iterable: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None ) -> Iterator[Any]: """Filter per PEP 440: exclude prereleases unless no finals exist.""" # Two lists used: # * all_nonfinal to preserve order if no finals exist # * arbitrary_strings for streaming when first final found all_nonfinal: list[Any] = [] arbitrary_strings: list[Any] = [] found_final = False for item in iterable: parsed = coerce_version(item if key is None else key(item)) if parsed is None: # Arbitrary strings are always included as it is not # possible to determine if they are prereleases, # and they have already passed all specifiers. if found_final: yield item else: arbitrary_strings.append(item) all_nonfinal.append(item) continue if not parsed.is_prerelease: # Final release found - flush arbitrary strings, then yield if not found_final: yield from arbitrary_strings found_final = True yield item continue # Prerelease - buffer if no finals yet, otherwise skip if not found_final: all_nonfinal.append(item) # No finals found - yield all buffered items if not found_final: yield from all_nonfinal ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4537523 packaging-26.3/src/packaging/tags.py0000644000000000000000000011263615234171317014356 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 collections.abc import Iterable, Iterator, Sequence from importlib.machinery import EXTENSION_SUFFIXES from typing import ( TYPE_CHECKING, TypeVar, cast, ) from . import _manylinux, _musllinux if TYPE_CHECKING: from collections.abc import Callable from collections.abc import Set as AbstractSet __all__ = [ "INTERPRETER_SHORT_NAMES", "AppleVersion", "InvalidTag", "PythonVersion", "Tag", "TooManyTagsError", "UnsortedTagsError", "android_platforms", "compatible_tags", "cpython_tags", "create_compatible_tags_selector", "generic_tags", "interpreter_name", "interpreter_version", "ios_platforms", "mac_platforms", "parse_tag", "platform_tags", "pure_python_tags", "sys_tags", ] def __dir__() -> list[str]: return __all__ logger = logging.getLogger(__name__) PythonVersion = Sequence[int] """ A sequence of integers describing a Python version, e.g. ``(3, 13)``. .. versionadded:: 20.0 """ AppleVersion = tuple[int, int] """ A ``(major, minor)`` integer pair describing an Apple OS version. .. versionadded:: 24.2 """ _T = TypeVar("_T") INTERPRETER_SHORT_NAMES: dict[str, str] = { "python": "py", # Generic. "cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy", } # This function can be unit tested without reloading the module # (Unlike _32_BIT_INTERPRETER) def _compute_32_bit_interpreter() -> bool: return struct.calcsize("P") == 4 _32_BIT_INTERPRETER = _compute_32_bit_interpreter() class UnsortedTagsError(ValueError): """ Raised when a tag component is not in sorted order per PEP 425. .. versionadded:: 26.1 """ class InvalidTag(ValueError): """ Raised when an interpreter component is not an identifier, a tag component is empty, or a tag does not have exactly three components. .. versionadded:: 26.3 """ class TooManyTagsError(ValueError): """ Raised when a compressed tag set exceeds the configured limit. .. versionadded:: 26.3 """ class Tag: """ A representation of the tag triple for a wheel. Instances are considered immutable and thus are hashable. Equality checking is also supported. Instances are safe to serialize with :mod:`pickle`. They use a stable format so the same pickle can be loaded in future packaging releases. .. versionchanged:: 26.2 Added a stable pickle format. Pickles created with packaging 26.2+ can be unpickled with future releases. Backward compatibility with pickles from packaging < 26.2 is supported but may be removed in a future release. """ __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] def __init__(self, interpreter: str, abi: str, platform: str) -> None: """ :param str interpreter: The interpreter name, e.g. ``"py"`` (see :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter names to their short names). :param str abi: The ABI that a wheel supports, e.g. ``"cp37m"``. :param str platform: The OS/platform the wheel supports, e.g. ``"win_amd64"``. """ self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() # The __hash__ of every single element in a Set[Tag] will be evaluated each time # that a set calls its `.disjoint()` method, which may be called hundreds of # times when scanning a page of links for packages with tags matching that # Set[Tag]. Pre-computing the value here produces significant speedups for # downstream consumers. self._hash = hash((self._interpreter, self._abi, self._platform)) @property def interpreter(self) -> str: """ The interpreter name, e.g. ``"py"`` (see :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter names to their short names). """ return self._interpreter @property def abi(self) -> str: """ The supported ABI. """ return self._abi @property def platform(self) -> str: """ The OS/platform. """ return self._platform def __eq__(self, other: object) -> bool: if not isinstance(other, Tag): return NotImplemented return ( (self._hash == other._hash) # Short-circuit ASAP for perf reasons. and (self._platform == other._platform) and (self._abi == other._abi) and (self._interpreter == other._interpreter) ) def __hash__(self) -> int: return self._hash def __str__(self) -> str: return f"{self._interpreter}-{self._abi}-{self._platform}" def __repr__(self) -> str: return f"<{self} @ {id(self)}>" def __getstate__(self) -> tuple[str, str, str]: # Return state as a 3-item tuple: (interpreter, abi, platform). # Cache member _hash is excluded and will be recomputed. return (self._interpreter, self._abi, self._platform) def __setstate__(self, state: object) -> None: if isinstance(state, tuple): if len(state) == 3 and all(isinstance(s, str) for s in state): # New format (26.2+): (interpreter, abi, platform) self._interpreter, self._abi, self._platform = state self._hash = hash((self._interpreter, self._abi, self._platform)) return if len(state) == 2 and isinstance(state[1], dict): # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). _, slots = state try: interpreter = slots["_interpreter"] abi = slots["_abi"] platform = slots["_platform"] except KeyError: raise TypeError(f"Cannot restore Tag from {state!r}") from None if not all( isinstance(value, str) for value in (interpreter, abi, platform) ): raise TypeError(f"Cannot restore Tag from {state!r}") self._interpreter = interpreter.lower() self._abi = abi.lower() self._platform = platform.lower() self._hash = hash((self._interpreter, self._abi, self._platform)) return raise TypeError(f"Cannot restore Tag from {state!r}") def parse_tag( tag: str, *, validate_order: bool = False, limit: int | None = None ) -> frozenset[Tag]: """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of :class:`Tag` instances. Returning a set is required due to the possibility that the tag is a `compressed tag set`_, e.g. ``"py2.py3-none-any"`` which supports both Python 2 and Python 3. If **validate_order** is true, compressed tag set components are checked to be in sorted order as required by PEP 425. If **limit** is not ``None``, the compressed tag set can generate at most that many tags. :param str tag: The tag to parse, e.g. ``"py3-none-any"``. :param bool validate_order: Check whether compressed tag set components are in sorted order. :param int | None limit: The maximum number of tags to parse. :raises UnsortedTagsError: If **validate_order** is true and any compressed tag set component is not in sorted order. :raises InvalidTag: If the interpreter field is not an identifier; if the interpreter, ABI, or platform field (or any member of a compressed tag set) is empty; or if the tag does not have exactly three components. :raises TooManyTagsError: If **limit** is not ``None`` and the compressed tag set would generate more than **limit** tags. :raises ValueError: If **limit** is negative. .. versionadded:: 26.1 The *validate_order* parameter. .. versionadded:: 26.3 Raises :class:`InvalidTag` when an interpreter component is not an identifier, a tag component is empty, or a tag does not have exactly three components. Added the *limit* parameter. Raises :class:`TooManyTagsError` if the compressed tag set would generate more than *limit* tags. """ if limit is not None and limit < 0: raise ValueError("limit must be non-negative") component_parts = [component.split(".") for component in tag.split("-")] for parts in component_parts: if "" in parts: component = ".".join(parts) raise InvalidTag(f"Tag {tag!r} has an empty component: {component!r}") if validate_order and parts != sorted(parts): component = ".".join(parts) raise UnsortedTagsError( f"Tag component {component!r} is not in sorted order per PEP 425" ) tag_count = 1 for parts in component_parts: tag_count *= len(parts) if limit is not None and tag_count > limit: raise TooManyTagsError( f"Compressed tag set would generate {tag_count} tags, exceeding " f"limit {limit}" ) try: interpreters, abis, platforms = component_parts except ValueError as exc: raise InvalidTag(f"Tag {tag!r} must have exactly three components") from exc for interpreter in interpreters: if not interpreter.isidentifier(): raise InvalidTag(f"Tag {tag!r} has an invalid interpreter: {interpreter!r}") return frozenset( Tag(interpreter, abi, platform_) for interpreter in interpreters for abi in abis for platform_ in platforms ) def _get_config_var(name: str, warn: bool = False) -> int | str | None: value: int | str | None = sysconfig.get_config_var(name) if value is None and warn: logger.debug( "Config variable '%s' is unset, Python ABI tag may be incorrect", name ) return value def _normalize_string(string: str) -> str: return string.replace(".", "_").replace("-", "_").replace(" ", "_") def _is_threaded_cpython(abis: list[str]) -> bool: """ Determine if the ABI corresponds to a threaded (`--disable-gil`) build. The threaded builds are indicated by a "t" in the abiflags. """ if len(abis) == 0: return False # expect e.g., cp313 m = re.match(r"cp\d+(.*)", abis[0]) if not m: return False abiflags = m.group(1) return "t" in abiflags def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: """ Determine if the Python version supports abi3. PEP 384 was first implemented in Python 3.2. The free-threaded builds do not support abi3. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading def _abi3t_applies(python_version: PythonVersion, threading: bool) -> bool: """ Determine if the Python version supports abi3t. PEP 803 was first implemented in Python 3.15 but, per PEP 803, this returns tags going back to Python 3.2 to mirror the abi3 implementation and leave open the possibility of abi3t wheels supporting older Python versions. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2) and threading def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: py_version = tuple(py_version) # To allow for version comparison. abis = [] version = _version_nodot(py_version[:2]) threading = debug = pymalloc = ucs4 = "" with_debug = _get_config_var("Py_DEBUG", warn) has_refcount = hasattr(sys, "gettotalrefcount") # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled # extension modules is the best option. # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 has_ext = "_d.pyd" in EXTENSION_SUFFIXES if with_debug or (with_debug is None and (has_refcount or has_ext)): debug = "d" if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): threading = "t" if py_version < (3, 8): with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) if with_pymalloc or with_pymalloc is None: pymalloc = "m" if py_version < (3, 3): unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) if unicode_size == 4 or ( unicode_size is None and sys.maxunicode == 0x10FFFF ): ucs4 = "u" elif debug: # Debug builds can also load "normal" extension modules. # We can also assume no UCS-4 or pymalloc requirement. abis.append(f"cp{version}{threading}") abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") return abis def cpython_tags( python_version: PythonVersion | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for the CPython interpreter. The specific tags generated are: - ``cp--`` - ``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``. .. versionadded:: 20.0 """ if not python_version: python_version = sys.version_info[:2] interpreter = f"cp{_version_nodot(python_version[:2])}" if abis is None: abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else [] abis = list(abis) threading = _is_threaded_cpython(abis) # Stable ABIs and 'none' are explicitly handled later. explicit_abis = ("abi3", "abi3t", "none") if threading else ("abi3", "none") for explicit_abi in explicit_abis: try: abis.remove(explicit_abi) except ValueError: # noqa: PERF203 pass platforms = list(platforms or platform_tags()) for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) use_abi3 = _abi3_applies(python_version, threading) use_abi3t = _abi3t_applies(python_version, threading) if use_abi3: yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) if use_abi3t: yield from (Tag(interpreter, "abi3t", platform_) for platform_ in platforms) yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) if use_abi3 or use_abi3t: for minor_version in range(python_version[1] - 1, 1, -1): for platform_ in platforms: version = _version_nodot((python_version[0], minor_version)) interpreter = f"cp{version}" if use_abi3: yield Tag(interpreter, "abi3", platform_) if use_abi3t: # Support for abi3t was introduced in Python 3.15, but in # principle abi3t wheels are possible for older limited API # versions, so allow things like ("cp37", "abi3t", "platform") yield Tag(interpreter, "abi3t", platform_) def _generic_abi() -> list[str]: """ Return the ABI tag based on EXT_SUFFIX. """ # The following are examples of `EXT_SUFFIX`. # We want to keep the parts which are related to the ABI and remove the # parts which are related to the platform: # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 # - mac: '.cpython-310-darwin.so' => cp310 # - win: '.cp310-win_amd64.pyd' => cp310 # - win: '.pyd' => cp37 (uses _cpython_abis()) # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' # => graalpy_38_native ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) if not isinstance(ext_suffix, str) or not ext_suffix.startswith("."): raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") parts = ext_suffix.split(".") if len(parts) < 3: # CPython3.7 and earlier uses ".pyd" on Windows. return _cpython_abis(sys.version_info[:2]) soabi = parts[1] if soabi.startswith("cpython"): # non-windows cpython_parts = soabi.split("-") if len(cpython_parts) < 2 or not cpython_parts[1]: raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") abi = "cp" + cpython_parts[1] elif soabi.startswith("cp"): # windows abi = soabi.split("-")[0] elif soabi.startswith("pypy"): abi = "-".join(soabi.split("-")[:2]) elif soabi.startswith("graalpy"): abi = "-".join(soabi.split("-")[:3]) elif soabi: # pyston, ironpython, others? abi = soabi else: return [] return [_normalize_string(abi)] def generic_tags( interpreter: str | None = None, abis: Iterable[str] | None = None, platforms: Iterable[str] | None = None, *, warn: bool = False, ) -> Iterator[Tag]: """ Yields the tags for an interpreter which requires no specialization. This function should be used if one of the other interpreter-specific functions provided by this module is not appropriate (i.e. not calculating tags for a CPython interpreter). The specific tags generated are: - ``--`` The ``"none"`` ABI will be added if it was not explicitly provided. :param str interpreter: The name of the interpreter. Defaults to being calculated. :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs compatible with the current system. :param Iterable platforms: Iterable of compatible platforms. Defaults to the platforms compatible with the current system. :param bool warn: Whether warnings should be logged. Defaults to ``False``. .. versionadded:: 20.0 """ if not interpreter: interp_name = interpreter_name() interp_version = interpreter_version(warn=warn) interpreter = f"{interp_name}{interp_version}" abis = _generic_abi() if abis is None else list(abis) platforms = list(platforms or platform_tags()) if "none" not in abis: abis.append("none") for abi in abis: for platform_ in platforms: yield Tag(interpreter, abi, platform_) def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: """ Yields Python versions in descending order. After the latest version, the major-only version will be yielded, and then all previous versions of that major version. """ if len(py_version) > 1: yield f"py{_version_nodot(py_version[:2])}" yield f"py{py_version[0]}" if len(py_version) > 1: for minor in range(py_version[1] - 1, -1, -1): yield f"py{_version_nodot((py_version[0], minor))}" def pure_python_tags( python_version: PythonVersion | None = None, ) -> Iterator[Tag]: """ Yields the pure-Python tags compatible with ``python_version``. The tags use the ``"none"`` ABI and ``"any"`` platform, so their generation does not depend on the running platform. .. versionadded:: 26.3 :param Sequence python_version: A one- or two-item sequence representing the compatible version of Python. Defaults to ``sys.version_info[:2]``. :raises ValueError: If ``python_version`` is an empty sequence. """ if python_version is None: python_version = sys.version_info[:2] elif not python_version: raise ValueError("python_version must contain at least one item") for version in _py_interpreter_range(python_version): yield Tag(version, "none", "any") def compatible_tags( python_version: PythonVersion | None = None, interpreter: str | None = None, platforms: Iterable[str] | None = None, ) -> Iterator[Tag]: """ Yields the tags for an interpreter compatible with the Python version specified by ``python_version``. The specific tags generated are: - ``py*-none-`` - ``-none-any`` if ``interpreter`` is provided - ``py*-none-any`` :param Sequence python_version: A one- or two-item sequence representing the compatible version of Python. Defaults to ``sys.version_info[:2]``. :param str interpreter: The name of the interpreter (if known), e.g. ``"cp38"``. Defaults to the current interpreter. :param Iterable platforms: Iterable of compatible platforms. Defaults to the platforms compatible with the current system. .. versionadded:: 20.0 """ if not python_version: python_version = sys.version_info[:2] platforms = list(platforms or platform_tags()) for version in _py_interpreter_range(python_version): for platform_ in platforms: yield Tag(version, "none", platform_) if interpreter: yield Tag(interpreter, "none", "any") yield from pure_python_tags(python_version) def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: if not is_32bit: return arch if arch.startswith("ppc"): return "ppc" return "i386" def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: formats = [cpu_arch] if cpu_arch == "x86_64": if version < (10, 4): return [] formats.extend(["intel", "fat64", "fat3"]) elif cpu_arch == "i386": if version < (10, 4): return [] formats.extend(["intel", "fat3", "fat"]) elif cpu_arch == "ppc64": # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? if version > (10, 5) or version < (10, 4): return [] formats.append("fat64") elif cpu_arch == "ppc": if version > (10, 6): return [] formats.extend(["fat3", "fat"]) if cpu_arch in {"arm64", "x86_64"}: formats.append("universal2") if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: formats.append("universal") return formats def mac_platforms( version: AppleVersion | None = None, arch: str | None = None ) -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for macOS. The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system. :param tuple version: A two-item tuple representing the version of macOS. Defaults to the current system's version. :param str arch: The CPU architecture. Defaults to the architecture of the current system, e.g. ``"x86_64"``. .. note:: Equivalent support for the other major platforms is purposefully not provided: - On Windows, platform compatibility is statically specified - On Linux, code must be run on the system itself to determine compatibility .. versionadded:: 20.0 """ if version is None or arch is None: version_str, _, cpu_arch = platform.mac_ver() if version is None: version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) if version == (10, 16): # When built against an older macOS SDK, Python will report macOS 10.16 # instead of the real version. version_str = subprocess.run( [ sys.executable, "-sS", "-c", "import platform; print(platform.mac_ver()[0])", ], check=True, env={"SYSTEM_VERSION_COMPAT": "0"}, stdout=subprocess.PIPE, text=True, ).stdout version = cast( "AppleVersion", tuple(map(int, version_str.split(".")[:2])) ) if arch is None: arch = _mac_arch(cpu_arch) if (10, 0) <= version < (11, 0): # Prior to Mac OS 11, each yearly release of Mac OS bumped the # "minor" version number. The major version was always 10. major_version = 10 for minor_version in range(version[1], -1, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}" if version >= (11, 0): # Starting with Mac OS 11, each yearly release bumps the major version # number. The minor versions are now the midyear updates. minor_version = 0 for major_version in range(version[0], 10, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}" # Mac OS 11 on x86_64 is compatible with binaries from previous releases. # Arm64 support was introduced in 11.0, so no Arm binaries from previous # releases exist. # # However, the "universal2" binary format can have a # macOS version earlier than 11.0 when the x86_64 part of the binary supports # that version of macOS. major_version = 10 if arch == "x86_64": for minor_version in range(16, 3, -1): compat_version = major_version, minor_version binary_formats = _mac_binary_formats(compat_version, arch) for binary_format in binary_formats: yield f"macosx_{major_version}_{minor_version}_{binary_format}" else: for minor_version in range(16, 3, -1): compat_version = major_version, minor_version binary_format = "universal2" yield f"macosx_{major_version}_{minor_version}_{binary_format}" def ios_platforms( version: AppleVersion | None = None, multiarch: str | None = None ) -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for iOS. :param tuple version: A two-item tuple representing the version of iOS. Defaults to the current system's version. :param str multiarch: The CPU architecture+ABI to be used. This should be in the format by ``sys.implementation._multiarch`` (e.g., ``arm64_iphoneos`` or ``x86_64_iphonesimulator``). Defaults to the current system's multiarch value. .. note:: Behavior of this method is undefined if invoked on non-iOS platforms without providing explicit version and multiarch arguments. .. versionadded:: 24.2 """ if version is None: # if iOS is the current platform, ios_ver *must* be defined. However, # it won't exist for CPython versions before 3.13, which causes a mypy # error. _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] version = cast("AppleVersion", tuple(map(int, release.split(".")[:2]))) if multiarch is None: multiarch = sys.implementation._multiarch multiarch = multiarch.replace("-", "_") ios_platform_template = "ios_{major}_{minor}_{multiarch}" # Consider any iOS major.minor version from the version requested, down to # 12.0. 12.0 is the first iOS version that is known to have enough features # to support CPython. Consider every possible minor release up to X.9. There # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra # candidates that won't ever match doesn't really hurt, and it saves us from # having to keep an explicit list of known iOS versions in the code. Return # the results descending order of version number. # If the requested major version is less than 12, there won't be any matches. if version[0] < 12: return # Consider the actual X.Y version that was requested. yield ios_platform_template.format( major=version[0], minor=version[1], multiarch=multiarch ) # Consider every minor version from X.0 to the minor version prior to the # version requested by the platform. for minor in range(version[1] - 1, -1, -1): yield ios_platform_template.format( major=version[0], minor=minor, multiarch=multiarch ) for major in range(version[0] - 1, 11, -1): for minor in range(9, -1, -1): yield ios_platform_template.format( major=major, minor=minor, multiarch=multiarch ) def android_platforms( api_level: int | None = None, abi: str | None = None ) -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on non-Android platforms, the ``api_level`` and ``abi`` arguments are required. :param int api_level: The maximum `API level `__ 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. .. versionadded:: 25.0 """ if platform.system() != "Android" and (api_level is None or abi is None): raise TypeError( "on non-Android platforms, the api_level and abi arguments are required" ) if api_level is None: # Python 3.13 was the first version to return platform.system() == "Android", # and also the first version to define platform.android_ver(). api_level = platform.android_ver().api_level # type: ignore[attr-defined] if abi is None: abi = sysconfig.get_platform().split("-")[-1] abi = _normalize_string(abi) # 16 is the minimum API level known to have enough features to support CPython # without major patching. Yield every API level from the maximum down to the # minimum, inclusive. min_api_level = 16 for ver in range(api_level, min_api_level - 1, -1): yield f"android_{ver}_{abi}" def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: linux = _normalize_string(sysconfig.get_platform()) if not linux.startswith("linux_"): # we should never be here, just yield the sysconfig one and return yield linux return if is_32bit: if linux == "linux_x86_64": linux = "linux_i686" elif linux == "linux_aarch64": linux = "linux_armv8l" _, arch = linux.split("_", 1) archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) for arch in archs: yield f"linux_{arch}" yield from _manylinux.platform_tags(archs) yield from _musllinux.platform_tags(archs) def _emscripten_platforms() -> Iterator[str]: pyemscripten_platform_version = sysconfig.get_config_var( "PYEMSCRIPTEN_PLATFORM_VERSION" ) if pyemscripten_platform_version: yield f"pyemscripten_{pyemscripten_platform_version}_wasm32" yield from _generic_platforms() def _generic_platforms() -> Iterator[str]: yield _normalize_string(sysconfig.get_platform()) def platform_tags() -> Iterator[str]: """ Yields the :attr:`~Tag.platform` tags for the running interpreter. .. versionadded:: 21.1 """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "iOS": return ios_platforms() elif platform.system() == "Android": return android_platforms() elif platform.system() == "Linux": return _linux_platforms() elif platform.system() == "Emscripten": return _emscripten_platforms() else: return _generic_platforms() def interpreter_name() -> str: """ Returns the name of the running interpreter. Some implementations have a reserved, two-letter abbreviation which will be returned when appropriate. This typically acts as the prefix to the :attr:`~Tag.interpreter` tag. .. versionadded:: 20.0 """ name = sys.implementation.name return INTERPRETER_SHORT_NAMES.get(name) or name def interpreter_version(*, warn: bool = False) -> str: """ Returns the running interpreter's version. This typically acts as the suffix to the :attr:`~Tag.interpreter` tag. :param bool warn: Whether warnings should be logged. Defaults to ``False``. .. versionadded:: 20.0 """ version = _get_config_var("py_version_nodot", warn=warn) return str(version) if version else _version_nodot(sys.version_info[:2]) def _version_nodot(version: PythonVersion) -> str: return "".join(map(str, version)) def sys_tags(*, warn: bool = False) -> Iterator[Tag]: """ Yields the sequence of tag triples that the running interpreter supports. The iterable is ordered so that the best-matching tag is first in the sequence. The exact preferential order to tags is interpreter-specific, but in general the tag importance is in the order of: 1. Interpreter 2. Platform 3. ABI This order is due to the fact that an ABI is inherently tied to the platform, but platform-specific code is not necessarily tied to the ABI. The interpreter is the most important tag as it dictates basic support for any wheel. The function returns an iterable in order to allow for the possible short-circuiting of tag generation if the entire sequence is not necessary and tag calculation happens to be expensive. :param bool warn: Whether warnings should be logged. Defaults to ``False``. .. versionchanged:: 21.3 Added the `pp3-none-any` tag (:issue:`311`). .. versionchanged:: 26.1 Added the `abi3t` tag (:issue:`1099`). .. versionchanged:: 26.3 Native ``linux_*`` platform tags are now ordered before ``manylinux`` and ``musllinux`` tags (:issue:`160`). """ interp_name = interpreter_name() if interp_name == "cp": yield from cpython_tags(warn=warn) else: yield from generic_tags(warn=warn) if interp_name == "pp": interp = "pp3" elif interp_name == "cp": interp = "cp" + interpreter_version(warn=warn) else: interp = None yield from compatible_tags(interpreter=interp) def create_compatible_tags_selector( tags: Iterable[Tag], ) -> Callable[[Iterable[tuple[_T, AbstractSet[Tag]]]], Iterator[_T]]: """Create a callable to select things compatible with supported tags. This function accepts an ordered sequence of tags, with the preferred tags first. The returned callable accepts an iterable of tuples (thing, set[Tag]), and returns an iterator of things, with the things with the best matching tags first. Example to select compatible wheel filenames: >>> from packaging import tags >>> from packaging.utils import parse_wheel_filename >>> selector = tags.create_compatible_tags_selector(tags.sys_tags()) >>> filenames = ["foo-1.0-py3-none-any.whl", "foo-1.0-py2-none-any.whl"] >>> list(selector([ ... (filename, parse_wheel_filename(filename)[-1]) for filename in filenames ... ])) ['foo-1.0-py3-none-any.whl'] .. versionadded:: 26.1 """ tag_ranks: dict[Tag, int] = {} for rank, tag in enumerate(tags): tag_ranks.setdefault(tag, rank) # ignore duplicate tags, keep first supported_tags = tag_ranks.keys() def selector( tagged_things: Iterable[tuple[_T, AbstractSet[Tag]]], ) -> Iterator[_T]: ranked_things: list[tuple[_T, int]] = [] for thing, thing_tags in tagged_things: supported_thing_tags = thing_tags & supported_tags if supported_thing_tags: thing_rank = min(tag_ranks[t] for t in supported_thing_tags) ranked_things.append((thing, thing_rank)) return iter( thing for thing, _ in sorted(ranked_things, key=operator.itemgetter(1)) ) return selector ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4537523 packaging-26.3/src/packaging/utils.py0000644000000000000000000002766715234171317014571 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, Union, cast from .tags import InvalidTag, 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]] """ A wheel build tag: an empty tuple, or a ``(build number, build tag suffix)`` pair. .. versionadded:: 20.9 """ NormalizedName = NewType("NormalizedName", str) """ A :class:`typing.NewType` of :class:`str`, representing a normalized name. .. versionadded:: 20.4 """ class InvalidName(ValueError): """ An invalid distribution name; users should refer to the packaging user guide. .. versionadded:: 23.2 """ class InvalidWheelFilename(ValueError): """ An invalid wheel filename was found, users should refer to PEP 427. .. versionadded:: 20.9 """ class InvalidSdistFilename(ValueError): """ An invalid sdist filename was found, users should refer to the packaging user guide. .. versionadded:: 20.9 """ # Core metadata spec for `Name` _validate_regex = re.compile( r"[a-z0-9]|[a-z0-9][a-z0-9._-]*[a-z0-9]", re.IGNORECASE | re.ASCII ) _normalized_regex = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*", re.ASCII) # PEP 427: The build number must start with a digit. _build_tag_regex = re.compile(r"(\d+)(.*)", re.ASCII) # PEP 427: Valid characters for an escaped project name in a wheel filename. # Requires at least one character so an empty project name is rejected. _wheel_name_regex = re.compile(r"^[\w._]+\Z", re.UNICODE) def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: """ This function takes a valid Python package or extra name, and returns the normalized form of it. The return type is typed as :class:`NormalizedName`. This allows type checkers to help require that a string has passed through this function before use. If **validate** is true, then the function will check if **name** is a valid distribution name before normalizing. :param str name: The name to normalize. :param bool validate: Check whether the name is a valid distribution name. :raises InvalidName: If **validate** is true and the name is not an acceptable distribution name. >>> from packaging.utils import canonicalize_name >>> canonicalize_name("Django") 'django' >>> canonicalize_name("oslo.concurrency") 'oslo-concurrency' >>> canonicalize_name("requests") 'requests' .. versionadded:: 16.2 .. versionchanged:: 20.4 The return type was changed to :class:`NormalizedName`. .. versionchanged:: 23.2 Added the *validate* keyword parameter. """ if validate and not _validate_regex.fullmatch(name): raise InvalidName(f"name is invalid: {name!r}") # Ensure all ``.`` and ``_`` are ``-`` # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 # Much faster than re, and even faster than str.translate value = name.lower().replace("_", "-").replace(".", "-") # Condense repeats (faster than regex) while "--" in value: value = value.replace("--", "-") return cast("NormalizedName", value) def is_normalized_name(name: str) -> bool: """ Check if a name is a normalized project name (i.e. a valid name that :func:`canonicalize_name` would roundtrip to the same value). The roundtrip only characterizes normalized names for *valid* names. A name must start and end with an ASCII letter or digit, which :func:`canonicalize_name` does not enforce: it leaves a leading or trailing hyphen in place, so such a name roundtrips without being normalized. :param str name: The name to check. >>> from packaging.utils import canonicalize_name, is_normalized_name >>> is_normalized_name("requests") True >>> is_normalized_name("Django") False >>> canonicalize_name("_not_legal") '-not-legal' >>> is_normalized_name("-not-legal") # roundtrips, but not a valid name False .. versionadded:: 23.2 """ return _normalized_regex.fullmatch(name) is not None def canonicalize_version( version: Version | str, *, strip_trailing_zero: bool = True ) -> str: """Return a canonical form of a version as a string. This function takes a string representing a package version (or a :class:`~packaging.version.Version` instance), and returns the normalized form of it. By default, it strips trailing zeros from the release segment. >>> from packaging.utils import canonicalize_version >>> canonicalize_version('1.0.1') '1.0.1' Per PEP 625, versions may have multiple canonical forms, differing only by trailing zeros. >>> canonicalize_version('1.0.0') '1' >>> canonicalize_version('1.0.0', strip_trailing_zero=False) '1.0.0' Invalid versions are returned unaltered. >>> canonicalize_version('foo bar baz') 'foo bar baz' >>> canonicalize_version('1.4.0.0.0') '1.4' .. versionadded:: 17.1 .. versionchanged:: 21.0 The return type was narrowed to :class:`str`. .. versionchanged:: 22.0 Added the *strip_trailing_zero* keyword parameter. """ if isinstance(version, str): try: version = Version(version) except InvalidVersion: return str(version) return str(_TrimmedRelease(version) if strip_trailing_zero else version) def parse_wheel_filename( filename: str, *, validate_order: bool = False, ) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: """ This function takes the filename of a wheel file, and parses it, returning a tuple of name, version, build number, and tags. The name part of the tuple is normalized and typed as :class:`NormalizedName`. The version portion is an instance of :class:`~packaging.version.Version`. The build number is ``()`` if there is no build number in the wheel filename, otherwise a two-item tuple of an integer for the leading digits and a string for the rest of the build number. The tags portion is a frozen set of :class:`~packaging.tags.Tag` instances (as the tag string format allows multiple tags to be combined into a single string). If **validate_order** is true, compressed tag set components are checked to be in sorted order as required by PEP 425. :param str filename: The name of the wheel file. :param bool validate_order: Check whether compressed tag set components are in sorted order. :raises InvalidWheelFilename: If the filename in question does not follow the :ref:`wheel specification `. >>> from packaging.utils import parse_wheel_filename >>> from packaging.tags import Tag >>> from packaging.version import Version >>> name, ver, build, tags = parse_wheel_filename("foo-1.0-py3-none-any.whl") >>> name 'foo' >>> ver == Version('1.0') True >>> tags == {Tag("py3", "none", "any")} True >>> not build True .. versionadded:: 20.9 .. versionchanged:: 23.2 Raises :class:`InvalidWheelFilename` when the version component is invalid. .. versionadded:: 26.1 The *validate_order* parameter. .. versionchanged:: 26.3 Raises :class:`InvalidWheelFilename` when an interpreter component is not an identifier, a tag set component is empty, or the project name is empty. """ if not filename.endswith(".whl"): raise InvalidWheelFilename( f"Invalid wheel filename (extension must be '.whl'): {filename!r}" ) filename = filename[:-4] dashes = filename.count("-") if dashes not in (4, 5): raise InvalidWheelFilename( f"Invalid wheel filename (wrong number of parts): {filename!r}" ) parts = filename.split("-", dashes - 2) name_part = parts[0] # See PEP 427 for the rules on escaping the project name. if "__" in name_part or _wheel_name_regex.match(name_part) is None: raise InvalidWheelFilename(f"Invalid project name: {filename!r}") name = canonicalize_name(name_part) try: version = Version(parts[1]) except InvalidVersion as e: raise InvalidWheelFilename( f"Invalid wheel filename (invalid version): {filename!r}" ) from e if dashes == 5: build_part = parts[2] build_match = _build_tag_regex.match(build_part) if build_match is None: raise InvalidWheelFilename( f"Invalid build number: {build_part} in {filename!r}" ) build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2))) else: build = () tag_str = parts[-1] try: tags = parse_tag(tag_str, validate_order=validate_order) except UnsortedTagsError: raise InvalidWheelFilename( f"Invalid wheel filename (compressed tag set components must be in " f"sorted order per PEP 425): {filename!r}" ) from None except InvalidTag: raise InvalidWheelFilename( f"Invalid wheel filename (invalid tag component): {filename!r}" ) from None return (name, version, build, tags) def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: """ This function takes the filename of a sdist file (as specified in the `Source distribution format`_ documentation), and parses it, returning a tuple of the normalized name and version as represented by an instance of :class:`~packaging.version.Version`. :param str filename: The name of the sdist file. :raises InvalidSdistFilename: If the filename does not end with an sdist extension (``.zip`` or ``.tar.gz``), if it does not contain a dash separating the name and the version of the distribution, if the project name is empty, or if the version portion is not a valid version. >>> from packaging.utils import parse_sdist_filename >>> from packaging.version import Version >>> name, ver = parse_sdist_filename("foo-1.0.tar.gz") >>> name 'foo' >>> ver == Version('1.0') True .. versionadded:: 20.9 .. versionchanged:: 21.0 Added support for ``.zip`` source distributions. .. versionchanged:: 23.2 Raises :class:`InvalidSdistFilename` when the version component is invalid. .. versionchanged:: 26.3 Raises :class:`InvalidSdistFilename` on an empty project name. .. _Source distribution format: https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-name """ if filename.endswith(".tar.gz"): file_stem = filename[: -len(".tar.gz")] elif filename.endswith(".zip"): file_stem = filename[: -len(".zip")] else: raise InvalidSdistFilename( f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" f" {filename!r}" ) # We are requiring a PEP 440 version, which cannot contain dashes, # so we split on the last dash. name_part, sep, version_part = file_stem.rpartition("-") if not sep: raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") if not name_part: raise InvalidSdistFilename( f"Invalid sdist filename (empty project name): {filename!r}" ) name = canonicalize_name(name_part) try: version = Version(version_part) except InvalidVersion as e: raise InvalidSdistFilename( f"Invalid sdist filename (invalid version): {filename!r}" ) from e return (name, version) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4537523 packaging-26.3/src/packaging/version.py0000644000000000000000000011420015234171317015072 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, 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
        # The letter must be a string before it can be normalized.
        if (
            isinstance(letter, str)
            and (normalized := normalize_pre(letter)) in {"a", "b", "rc"}
            and isinstance(number, int)
            and number >= 0
        ):
            # type checkers can't infer the Literal type here on letter
            return (normalized, number)  # type: ignore[return-value]
    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
    raise InvalidVersion(msg)


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


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


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


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


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

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

    >>> v1 = Version("1.0a5")
    >>> v2 = Version("1.0")
    >>> v1
    
    >>> 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.
        """
        try:
            is_simple = _SIMPLE_VERSION_INDICATORS.issuperset(version)
        except TypeError:
            raise InvalidVersion(f"Invalid version: {version!r}") from None

        if is_simple:
            try:
                self._release = tuple(map(int, version.split(".")))
            except AttributeError:
                raise InvalidVersion(f"Invalid version: {version!r}") from None
            except ValueError:
                # Empty parts (from "1..2", ".1", etc.) are invalid versions.
                # Any other ValueError (e.g. int str-digits limit) should
                # propagate to the caller.
                if "" in version.split("."):
                    raise InvalidVersion(f"Invalid version: {version!r}") from None
                # TODO: remove "no cover" when Python 3.9 is dropped.
                raise  # pragma: no cover

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

        # Validate the version and parse it into pieces
        try:
            match = self._regex.fullmatch(version)
        except TypeError:
            raise InvalidVersion(f"Invalid version: {version!r}") from None
        if not match:
            raise InvalidVersion(f"Invalid version: {version!r}")
        self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
        self._release = tuple(map(int, match.group("release").split(".")))
        # We can type ignore the assignments below because the regex guarantees
        # the correct strings
        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))  # type: ignore[assignment]
        self._post = _parse_letter_version(  # type: ignore[assignment]
            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
        )
        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))  # type: ignore[assignment]
        self._local = _parse_local_version(match.group("local"))

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

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

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

        >>> Version.from_parts(release=(1,2,3))
        
        >>> Version.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

        .. versionadded:: 20.0
        """
        return self.release[0] if len(self.release) >= 1 else 0

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

        >>> Version("1.2.3").minor
        2
        >>> Version("1").minor
        0

        .. versionadded:: 20.0
        """
        return self.release[1] if len(self.release) >= 2 else 0

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

        >>> Version("1.2.3").micro
        3
        >>> Version("1").micro
        0

        .. versionadded:: 20.0
        """
        return self.release[2] if len(self.release) >= 3 else 0


class _TrimmedRelease(Version):
    __slots__ = ()

    def __init__(self, version: str | Version) -> None:
        if isinstance(version, Version):
            self._epoch = version._epoch
            self._release = version._release
            self._dev = version._dev
            self._pre = version._pre
            self._post = version._post
            self._local = version._local
            self._key_cache = version._key_cache
            self._hash_cache = version._hash_cache
            return
        super().__init__(version)  # pragma: no cover

    @property
    def release(self) -> tuple[int, ...]:
        """
        Release segment without any trailing zeros.

        >>> _TrimmedRelease('1.0.0').release
        (1,)
        >>> _TrimmedRelease('0.0').release
        (0,)
        """
        # This leaves one 0.
        rel = super().release
        len_release = len(rel)
        i = len_release
        while i > 1 and rel[i - 1] == 0:
            i -= 1
        return rel if i == len_release else rel[:i]


def _parse_letter_version(
    letter: str | None, number: str | bytes | SupportsInt | None
) -> tuple[str, int] | None:
    if letter:
        # We normalize any letters to their lower case form
        letter = letter.lower()

        # We consider some words to be alternate spellings of other words and
        # in those cases we want to normalize the spellings to our preferred
        # spelling.
        letter = _LETTER_NORMALIZATION.get(letter, letter)

        # We consider there to be an implicit 0 in a pre-release if there is
        # not a numeral associated with it.
        return letter, int(number or 0)

    if number:
        # We assume if we are given a number, but we are not given a letter
        # then this is using the implicit post release syntax (e.g. 1.0-1)
        return "post", int(number)

    return None


_local_version_separators = re.compile(r"[\._-]")


def _parse_local_version(local: str | None) -> LocalType | None:
    """
    Takes a string like ``"abc.1.twelve"`` and turns it into
    ``("abc", 1, "twelve")``.
    """
    if local is not None:
        return tuple(
            part.lower() if not part.isdigit() else int(part)
            for part in _local_version_separators.split(local)
        )
    return None


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

    if local is None:
        return epoch, trimmed, suffix

    cmp_local: CmpLocalType = tuple(
        (seg, "") if isinstance(seg, int) else (_LOCAL_STR_RANK, seg) for seg in local
    )
    return epoch, trimmed, suffix, cmp_local
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4551332
packaging-26.3/tests/__init__.py0000644000000000000000000000026415234171317013577 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.
././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1785787087.455471
packaging-26.3/tests/conftest.py0000644000000000000000000000145215234171317013665 0ustar00from __future__ import annotations

import sysconfig
import typing

import pytest

from packaging.markers import _cached_default_environment

if typing.TYPE_CHECKING:
    from collections.abc import Generator


@pytest.fixture(autouse=True)
def _clear_default_environment_cache() -> Generator[None, None, None]:
    # default_environment() is cached, so tests that patch platform/sys must run
    # against a fresh cache and must not leak their patched values to later tests.
    _cached_default_environment.cache_clear()
    yield
    _cached_default_environment.cache_clear()


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)
././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1785787087.455471
packaging-26.3/tests/manylinux/build.sh0000755000000000000000000000340215234171317015145 0ustar00#!/bin/bash

set -x
set -e

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

export DEBIAN_FRONTEND=noninteractive
cd /home/hello-world/
apt-get update
apt-get install -y --no-install-recommends gcc libc6-dev
if [ "$1" == "incontainer" ]; then
	ARCH=$(dpkg --print-architecture)
	CFLAGS=""
else
	ARCH=$1
	dpkg --add-architecture ${ARCH}
	apt-get install -y --no-install-recommends gcc-multilib libc6-dev-${ARCH}
	CFLAGS="-mx32"
fi
NAME=hello-world-$(uname -m)-${ARCH}
gcc -Os -s ${CFLAGS} -o ${NAME}-full hello-world.c
head -c $2 ${NAME}-full > ${NAME}
rm -f ${NAME}-full
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-armv7l-armel0000755000000000000000000000006415234171317020172 0ustar00ELF(4€4 	(././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-armv7l-armhf0000755000000000000000000000006415234171317020167 0ustar00ELF(4ˆ4 	(././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-invalid-class0000755000000000000000000000006415234171317020415 0ustar00ELF 4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-invalid-data0000755000000000000000000000006415234171317020221 0ustar00ELF 4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-invalid-magic0000755000000000000000000000006415234171317020370 0ustar00ELF 4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-s390x-s390x0000644000000000000000000000010015234171317017422 0ustar00ELFP@p@8	@././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-too-short0000644000000000000000000000005015234171317017612 0ustar00ELF 401././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-x86_64-amd640000644000000000000000000000010015234171317017517 0ustar00ELF>p@H1@8@././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-x86_64-i3860000755000000000000000000000006415234171317017311 0ustar00ELF 4014 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/manylinux/hello-world-x86_64-x320000755000000000000000000000006415234171317017234 0ustar00ELF>p4<14 (././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4556031
packaging-26.3/tests/metadata/everything.metadata0000644000000000000000000000347115234171317017137 0ustar00Metadata-Version: 2.6
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=1785787087.4559999
packaging-26.3/tests/musllinux/glibc-x86_640000755000000000000000000000200015234171317015456 0ustar00ELF>€@ˆ9@8
@@@@ØØ  õõ   XX¸-¸=¸=X`È-È=È=ðð888  XXXDDSåtd888  Påtd   DDQåtdRåtd¸-¸=¸=HH/lib64/ld-linux-x86-64.so.2GNUÀGNU°KïWz³£Ù7£Styx”ºyÊ�GNU�ÑeÎmQ '././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4559999
packaging-26.3/tests/musllinux/musl-aarch640000755000000000000000000000200015234171317015650 0ustar00ELF·@@€#@8@ @@@ÀÀŒŒ¨
¨
¨
`˜¸
¸
¸
ÀÀPåtd°°°44QåtdRåtd¨
¨
¨
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=1785787087.4559999
packaging-26.3/tests/musllinux/musl-i3860000755000000000000000000000200015234171317015111 0ustar00ELF¥4ä=4 
(! 444@@ttt``íí   ¸¸ü.ü>ü>(/??ÀÀPåtd   $$QåtdRåtdü.ü>ü>/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=1785787087.4559999
packaging-26.3/tests/musllinux/musl-x86_640000755000000000000000000000200015234171317015356 0ustar00ELF>s@A@8
@! @@@00ppp  YY   ¤¤.>>ø`0.0>0>€€Påtd   $$QåtdRåtd.>>ðð/lib/ld-musl-x86_64.so.1€�@	ÑeÎm¹�ñëÓïK c } #™ "Q_initprintf_fini__cxa_finalize__libc_start_mainlibc.musl-x86_64.so.1__der././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4559999
packaging-26.3/tests/property/__init__.py0000644000000000000000000000000015234171317015447 0ustar00././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/strategies.py0000644000000000000000000002632415234171317016103 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 TYPE_CHECKING

from hypothesis import settings
from hypothesis import strategies as st

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

if TYPE_CHECKING:
    from packaging.ranges import VersionRange


def eq_versions_only(a: VersionRange, b: VersionRange) -> bool:
    """Compare two ranges by bounds and ``===`` literals only, ignoring the
    arbitrary-string flag and both pre-release slots.

    Complement preserves ``_admit_arbitrary`` (only the universal range
    admits non-version strings, never algebra), so ``r | ~r`` is never
    structurally equal to ``VersionRange.full()`` when neither ``r`` nor
    ``~r`` is empty. The configured override mirrors ``SpecifierSet.__and__``
    rather than pure Boolean algebra, and the opt-in region (``_pre_region``)
    is part of equality, so ``==`` distinguishes ranges that accept the same
    versions. Use this helper when the property is "same set of versions
    accepted".
    """
    return a._bounds == b._bounds and a._admit == b._admit and a._reject == b._reject


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, 2, 3]))
    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, allow_epoch: bool = False
) -> Version:
    """Generate a final release version (no pre/post/dev/local).

    With ``allow_epoch=True`` the release may carry a non-zero epoch, so a
    zero release becomes a non-zero-epoch zero family (e.g. ``1!0``).
    """
    num_segments = draw(st.integers(min_value=min_segments, max_value=4))
    release = tuple(draw(small_ints) for _ in range(num_segments))
    epoch = draw(st.sampled_from([None, 1, 2])) if allow_epoch else None
    prefix = f"{epoch}!" if epoch else ""
    return Version(prefix + ".".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,
    *,
    vary_prereleases: bool = False,
) -> SpecifierSet:
    """Random SpecifierSet over ``>= <= > < == !=`` and ``major.minor``.

    Narrow on purpose. Tests that need wildcards, locals, pre/post/dev
    on the RHS, epochs, or ``===`` should use :func:`rich_specifier_sets`.

    With ``vary_prereleases=True`` the configured pre-release policy is
    drawn from ``(None, True, False)``; otherwise it is left as ``None``
    (autodetect).
    """
    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}")

    prereleases = (
        draw(st.sampled_from([None, True, False])) if vary_prereleases else None
    )

    return SpecifierSet(",".join(parts), prereleases=prereleases)


_ordered_ops = st.sampled_from([">=", "<=", ">", "<"])
_equality_ops = st.sampled_from(["==", "!="])


@st.composite
def pep440_specifier_strings(
    draw: st.DrawFn,
    *,
    include_arbitrary: bool = False,
) -> str:
    """One specifier string covering the full PEP 440 surface.

    Includes pre/post/dev/local-bearing RHS versions, epochs, multi-
    segment release tuples, ``==V.*`` / ``!=V.*`` wildcards, and
    optionally ``===L``.
    """
    shape = draw(st.sampled_from(["ordered", "equality", "wildcard", "compatible"]))
    if include_arbitrary and draw(st.booleans()):
        shape = "arbitrary"

    if shape == "ordered":
        # ``>= <= > <`` reject ``+local`` on the RHS.
        return f"{draw(_ordered_ops)}{draw(pep440_versions(include_local=False))}"

    if shape == "equality":
        return f"{draw(_equality_ops)}{draw(pep440_versions())}"

    if shape == "wildcard":
        # ``==V.*`` / ``!=V.*`` take a release-only RHS; epochs reach the
        # epoch-zero family floor (``==1!0.*``).
        return f"{draw(_equality_ops)}{draw(release_versions(allow_epoch=True))}.*"

    if shape == "compatible":
        return f"~={draw(multi_segment_versions())}"

    # ``===L`` with a parseable literal. Unparsable literals like
    # ``===wat`` are skipped: De Morgan can fail when an unparsable
    # ``===`` interacts with a non-full rangelike, since the bound
    # universe is parseable Versions but the literal universe is
    # all strings.
    return f"==={draw(pep440_versions())}"


@st.composite
def rich_specifier_sets(
    draw: st.DrawFn,
    *,
    include_arbitrary: bool = False,
    vary_prereleases: bool = False,
) -> SpecifierSet:
    """1-3 specifiers from :func:`pep440_specifier_strings`, joined.

    With ``vary_prereleases=True`` the configured pre-release policy is drawn
    from ``(None, True, False)``; otherwise it is left as ``None`` (autodetect).
    """
    num = draw(st.integers(min_value=1, max_value=3))
    parts = [
        draw(pep440_specifier_strings(include_arbitrary=include_arbitrary))
        for _ in range(num)
    ]
    prereleases = (
        draw(st.sampled_from([None, True, False])) if vary_prereleases else None
    )
    return SpecifierSet(",".join(parts), prereleases=prereleases)


@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))


# Bases for adjacency chains, one per family (final, post, dev, floor, epoch).
_ADJACENCY_BASES = [
    Version(v)
    for v in (
        "0",
        "1.0",
        "1.0.post0",
        "3.8",
        "1!0",
        "0.dev0",
        "1.0.dev0",
        "1!0.dev0",
        # Non-floor release-dev bases a ``!=W.*`` lead can abut (W just below).
        "2.dev0",
        "3.dev0",
    )
]

# Leads: a lower bound, a release-family wildcard the run can sit inside, or a
# ``!=W.*`` wildcard exclusion the dev run can abut (driving wildcard-then-dev-run).
_ADJACENCY_LEADS = [
    "",
    ">=0.dev0",
    ">=1.0",
    ">=1.0.post0",
    "==1.0.*",
    "==1!0.*",
    "==3.8.*",
    "==0.*",
    "!=0.*",
    "!=1.*",
    "!=2.*",
]


def _next_adjacent(version: Version) -> Version:
    """The immediate successor of *version* and its local family.

    Independent of the production ``least_version_above`` so the strategy does
    not validate the encoder against itself: a dev release steps its dev; any
    other release steps to its next post at ``.dev0`` (``.post0.dev0`` for a
    final release, ``.post(N+1).dev0`` for a ``.postN`` release).
    """
    if version.dev is not None:
        return version.__replace__(dev=version.dev + 1, local=None)
    next_post = (version.post + 1) if version.post is not None else 0
    return version.__replace__(post=next_post, dev=0, local=None)


@st.composite
def adjacency_exclusion_sets(draw: st.DrawFn) -> SpecifierSet:
    """An optional lower/wildcard lead plus a run of adjacent exclusions.

    Excluding a version and several of its immediate successors removes a
    contiguous block whose canonical bounds are a single merged gap. When the
    lead and base line up, this drives the ``to_specifier_set`` ``!=`` chain,
    dev-run, wildcard-then-dev-run, and epoch floor-run recovery paths that the
    independent specifier strategies never reach by chance.
    """
    base = draw(st.sampled_from(_ADJACENCY_BASES))
    points = [base]
    for _ in range(draw(st.integers(min_value=0, max_value=4))):
        points.append(_next_adjacent(points[-1]))

    lead = draw(st.sampled_from(_ADJACENCY_LEADS))
    parts = ([lead] if lead else []) + [f"!={point}" for point in points]
    prereleases = draw(st.sampled_from([None, True, False]))
    return SpecifierSet(",".join(parts), prereleases=prereleases)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/test_ranges_cross_epoch.py0000644000000000000000000000640415234171317020633 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.

"""Property tests for ``VersionRange`` algebra across distinct epochs.

PEP 440 epochs partition the version order into disjoint cohorts; an
``==1.0`` predicate in epoch 0 never overlaps an ``==1.0`` predicate in
epoch 1. The lattice laws still hold across cohorts, and round-tripping
through :meth:`to_specifier_set` must preserve the epoch on every side.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from hypothesis import given

from .strategies import (
    SETTINGS,
    VERSION_POOL,
    pep440_versions,
    rich_specifier_sets,
)

if TYPE_CHECKING:
    from packaging.ranges import VersionRange
    from packaging.specifiers import SpecifierSet
    from packaging.version import Version

pytestmark = pytest.mark.property

# Cross-epoch + dev/MIN_VERSION boundary probes for the membership oracle.
_EPOCH_PROBES = [
    "0.5",
    "1.0",
    "1.0a1",
    "0.dev0",
    "1.dev0",
    "1.dev1",
    "1.dev2",
    "1!0.5",
    "1!1.0",
    "1!0.dev0",
    "2!0.5",
    "2!1.0",
    "3!1.0",
]


def _mem_eq(a: VersionRange, b: VersionRange) -> bool:
    """``a`` and ``b`` accept the same versions across the probe sample."""
    probes = [str(v) for v in VERSION_POOL] + _EPOCH_PROBES
    return all((p in a) == (p in b) for p in probes)


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_de_morgan_holds_cross_epoch(a: SpecifierSet, b: SpecifierSet) -> None:
    """De Morgan holds for ranges that may straddle different epochs.

    The minimal engine canonicalizes empty/MIN_VERSION regions, so the two
    sides can differ in bound representation; compare on the version set.
    """
    ra, rb = a.to_range(), b.to_range()
    assert _mem_eq((ra & rb).complement(), ra.complement() | rb.complement())
    assert _mem_eq((ra | rb).complement(), ra.complement() & rb.complement())


@given(
    a=rich_specifier_sets(),
    b=rich_specifier_sets(),
    v=pep440_versions(),
)
@SETTINGS
def test_membership_consistent_across_epochs(
    a: SpecifierSet, b: SpecifierSet, v: Version
) -> None:
    """``v in (a & b)`` iff ``v in a`` and ``v in b`` regardless of epochs."""
    ra, rb = a.to_range(), b.to_range()
    assert (v in (ra & rb)) == ((v in ra) and (v in rb))
    assert (v in (ra | rb)) == ((v in ra) or (v in rb))


@given(spec_set=rich_specifier_sets())
@SETTINGS
def test_single_set_round_trip_preserves_epoch(spec_set: SpecifierSet) -> None:
    """``to_specifier_set`` round-trips epochs when the single-set form exists.

    When the conversion returns a single set, feeding it back through
    ``to_range`` must accept exactly the same versions; in particular any
    cross-epoch boundary in the source survives.
    """
    r = spec_set.to_range()
    converted = r.to_specifier_set()
    if converted is None:
        return
    recovered = converted.to_range()
    # Membership on a cross-epoch probe set must round-trip.
    probes = [
        "0.5",
        "1.0",
        "1.0a1",
        "1!0.5",
        "1!1.0",
        "2!0.5",
        "2!1.0",
        "3!1.0",
    ]
    for probe in probes:
        assert (probe in r) == (probe in recovered)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/test_ranges_pep440_extended.py0000644000000000000000000002210415234171317021213 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.

"""Set-algebra invariants re-run on the full PEP 440 specifier surface.

Uses :func:`tests.property.strategies.rich_specifier_sets`, which
adds wildcards, ``~=``, locals, pre/post/dev RHS, epochs, multi-
segment release tuples, and optionally ``===``.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from hypothesis import given

from packaging.ranges import VersionRange

from .strategies import (
    SETTINGS,
    VERSION_POOL,
    rich_specifier_sets,
)

if TYPE_CHECKING:
    from packaging.ranges import VersionRange as _VersionRange
    from packaging.specifiers import SpecifierSet

pytestmark = pytest.mark.property

# Extra boundary probes for the membership oracle. The minimal engine
# canonicalizes empty and ``MIN_VERSION`` regions (e.g. ``(1.dev1+, 1.dev2)``
# collapses to ``(empty)``, ``0.dev0`` lower bounds collapse to ``-inf``), so
# complement-bearing laws can differ in bound representation while accepting
# the same versions. These probes plus ``VERSION_POOL`` distinguish any
# genuine version-set difference.
_BOUNDARY_PROBES = [
    "0.dev0",
    "0.dev1",
    "1.dev0",
    "1.dev1",
    "1.dev2",
    "0rc0.dev0",
    "0rc0.dev1",
    "2.dev0",
    "1!0.dev0",
]


_ARBITRARY_PROBES = ["garbage", "unparsable", "not-a-version", "wat"]


def _version_eq(a: _VersionRange, b: _VersionRange) -> bool:
    """``a`` and ``b`` accept the same *versions* and ``===`` literals.

    Probes cover ``VERSION_POOL``, dev/MIN_VERSION boundary versions, and
    every ``===`` literal admitted or rejected by either operand, but not
    free non-version strings: the ``_admit_arbitrary`` slot attaches only to
    the genuine universal range, so ``r | ~r`` covers every version yet never
    admits arbitrary strings the way ``full()`` does. Genuine differences in
    bounds or literal slots are caught; benign empty/MIN_VERSION bound
    canonicalization and the ``_admit_arbitrary`` asymmetry are not.
    """
    literals = a._admit | a._reject | b._admit | b._reject
    probes = [str(v) for v in VERSION_POOL] + _BOUNDARY_PROBES + list(literals)
    return all((p in a) == (p in b) for p in probes)


def _mem_eq(a: _VersionRange, b: _VersionRange) -> bool:
    """``a`` and ``b`` accept the same items, including non-version strings.

    Extends :func:`_version_eq` with free non-version probes, so it also
    distinguishes the ``_admit_arbitrary`` slot. Use for laws that do not
    compare against ``full()``.
    """
    if not _version_eq(a, b):
        return False
    return all((p in a) == (p in b) for p in _ARBITRARY_PROBES)


@given(spec_set=rich_specifier_sets())
@SETTINGS
def test_double_complement_identity_rich(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    # Involution holds on the version set. The minimal engine canonicalizes
    # a ``MIN_VERSION`` (``0.dev0``) lower bound to ``-inf`` (no version is
    # below it), so ``~~r`` can differ from ``r`` only in bound
    # representation, never in which versions it accepts (e.g. ``==0.*``);
    # compare on the version subset.
    assert _mem_eq(r.complement().complement(), r)


@given(spec_set=rich_specifier_sets())
@SETTINGS
def test_complement_partitions_rich(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    c = r.complement()
    assert _mem_eq(r.intersection(c), VersionRange.empty())
    assert _version_eq(r.union(c), VersionRange.full())


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_de_morgan_intersect_rich(a: SpecifierSet, b: SpecifierSet) -> None:
    ra = a.to_range()
    rb = b.to_range()
    # The minimal engine canonicalizes empty/MIN_VERSION regions, so the two
    # sides can differ in bound representation; compare on the version set.
    assert _mem_eq(
        ra.intersection(rb).complement(),
        ra.complement().union(rb.complement()),
    )


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_de_morgan_union_rich(a: SpecifierSet, b: SpecifierSet) -> None:
    ra = a.to_range()
    rb = b.to_range()
    assert _mem_eq(
        ra.union(rb).complement(),
        ra.complement().intersection(rb.complement()),
    )


@given(spec_set=rich_specifier_sets())
@SETTINGS
def test_idempotence_rich(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    assert r.union(r) == r
    assert r.intersection(r) == r


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_intersect_commutative_rich(a: SpecifierSet, b: SpecifierSet) -> None:
    ra = a.to_range()
    rb = b.to_range()
    assert ra.intersection(rb) == rb.intersection(ra)


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_union_commutative_rich(a: SpecifierSet, b: SpecifierSet) -> None:
    ra = a.to_range()
    rb = b.to_range()
    assert ra.union(rb) == rb.union(ra)


@given(a=rich_specifier_sets(), b=rich_specifier_sets(), c=rich_specifier_sets())
@SETTINGS
def test_intersect_associative_rich(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    ra = a.to_range()
    rb = b.to_range()
    rc = c.to_range()
    assert ra.intersection(rb).intersection(rc) == ra.intersection(rb.intersection(rc))


@given(a=rich_specifier_sets(), b=rich_specifier_sets(), c=rich_specifier_sets())
@SETTINGS
def test_union_associative_rich(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    ra = a.to_range()
    rb = b.to_range()
    rc = c.to_range()
    assert ra.union(rb).union(rc) == ra.union(rb.union(rc))


@given(a=rich_specifier_sets(), b=rich_specifier_sets(), c=rich_specifier_sets())
@SETTINGS
def test_intersect_distributes_over_union_rich(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    ra = a.to_range()
    rb = b.to_range()
    rc = c.to_range()
    assert ra.intersection(rb.union(rc)) == ra.intersection(rb).union(
        ra.intersection(rc)
    )


@given(spec_set=rich_specifier_sets())
@SETTINGS
def test_membership_consistent_with_complement_rich(
    spec_set: SpecifierSet,
) -> None:
    r = spec_set.to_range()
    c = r.complement()
    for v in VERSION_POOL:
        assert (v in c) == (v not in r)


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_membership_consistent_with_intersect_rich(
    a: SpecifierSet, b: SpecifierSet
) -> None:
    ra = a.to_range()
    rb = b.to_range()
    inter = ra.intersection(rb)
    for v in VERSION_POOL:
        assert (v in inter) == ((v in ra) and (v in rb))


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_membership_consistent_with_union_rich(
    a: SpecifierSet, b: SpecifierSet
) -> None:
    ra = a.to_range()
    rb = b.to_range()
    union = ra.union(rb)
    for v in VERSION_POOL:
        assert (v in union) == ((v in ra) or (v in rb))


@given(spec_set=rich_specifier_sets(include_arbitrary=True))
@SETTINGS
def test_double_complement_with_arbitrary(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    # Involution holds on the accepted set. The minimal engine canonicalizes
    # a ``MIN_VERSION`` (``0.dev0``) lower bound to ``-inf`` (no version is
    # below it), so ``~~r`` can differ from ``r`` only in bound
    # representation, never in which items it accepts; compare on the
    # probe sample (versions plus ``===`` literals).
    assert _mem_eq(r.complement().complement(), r)


@given(spec_set=rich_specifier_sets(include_arbitrary=True))
@SETTINGS
def test_complement_partitions_with_arbitrary(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    c = r.complement()
    assert _mem_eq(r.intersection(c), VersionRange.empty())
    assert _version_eq(r.union(c), VersionRange.full())


@given(
    a=rich_specifier_sets(include_arbitrary=True),
    b=rich_specifier_sets(include_arbitrary=True),
)
@SETTINGS
def test_de_morgan_intersect_with_arbitrary(a: SpecifierSet, b: SpecifierSet) -> None:
    ra = a.to_range()
    rb = b.to_range()
    # The minimal engine canonicalizes empty/MIN_VERSION regions, so the two
    # sides can differ in bound representation; compare on the probe sample.
    assert _mem_eq(
        ra.intersection(rb).complement(),
        ra.complement().union(rb.complement()),
    )


@given(
    a=rich_specifier_sets(include_arbitrary=True),
    b=rich_specifier_sets(include_arbitrary=True),
)
@SETTINGS
def test_de_morgan_union_with_arbitrary(a: SpecifierSet, b: SpecifierSet) -> None:
    ra = a.to_range()
    rb = b.to_range()
    assert _mem_eq(
        ra.union(rb).complement(),
        ra.complement().intersection(rb.complement()),
    )


@given(spec_set=rich_specifier_sets(include_arbitrary=True))
@SETTINGS
def test_idempotence_with_arbitrary(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    assert r.union(r) == r
    assert r.intersection(r) == r


@given(spec_set=rich_specifier_sets(include_arbitrary=True))
@SETTINGS
def test_membership_consistent_with_complement_arbitrary(
    spec_set: SpecifierSet,
) -> None:
    r = spec_set.to_range()
    c = r.complement()
    for v in VERSION_POOL:
        assert (v in c) == (v not in r)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/test_ranges_pubgrub.py0000644000000000000000000003601015234171317017766 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.

"""Property tests verifying ``VersionRange`` satisfies PubGrub's invariants.

Each test class quotes the relevant paragraph verbatim from one of:

* `solver.md`_, the Dart pub specification (`Definitions Term`_,
  `Definitions Incompatibility`_).
* `Pubgrub blog post`_, Natalie Weizenbaum, 2018.

Unicode set-theoretic operators in the quotations are preserved as
written; the per-file ``noqa`` overrides silence ruff's ambiguous-glyph
warning for those quotations only.

.. _solver.md: https://github.com/dart-lang/pub/blob/master/doc/solver.md
.. _Definitions Term:
   https://github.com/dart-lang/pub/blob/master/doc/solver.md#term
.. _Definitions Incompatibility:
   https://github.com/dart-lang/pub/blob/master/doc/solver.md#incompatibility
.. _Pubgrub blog post: https://nex3.medium.com/pubgrub-2fb6470504f
"""

# ruff: noqa: RUF002, RUF003, E501
# RUF002 / RUF003: ambiguous Unicode in docstrings and comments, the
#         spec quotations preserve set-theoretic operators verbatim.
# E501: spec quotations are reproduced as written; wrapping them would
#       harm searchability against the upstream documents.

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from hypothesis import given

from packaging.ranges import VersionRange

from .strategies import (
    SETTINGS,
    VERSION_POOL,
    pep440_versions,
    rich_specifier_sets,
    specifier_sets,
)

if TYPE_CHECKING:
    from packaging.specifiers import SpecifierSet
    from packaging.version import Version

pytestmark = pytest.mark.property


def _to_range(spec_set: SpecifierSet) -> VersionRange:
    """Lift a non-``===`` SpecifierSet into a VersionRange."""
    return spec_set.to_range()


def _term_set(range_: VersionRange, *, positive: bool) -> VersionRange:
    """Set view of a PubGrub term: ``R`` if positive, ``~R`` if negative."""
    return range_ if positive else range_.complement()


def _is_subset(a: VersionRange, b: VersionRange) -> bool:
    """``A ⊆ B`` iff ``A & B == A``."""
    return (a & b) == a


def _is_disjoint(a: VersionRange, b: VersionRange) -> bool:
    """``A ∩ B == ∅``."""
    return (a & b).is_empty


class TestQuoteTermAsStatement:
    """solver.md § Term, paragraph 1:

    > "The fundamental unit on which Pubgrub operates is a Term, which
    > represents a statement about a package that may be true or false
    > for a given selection of package versions. For example, foo
    > ^1.0.0 is a term that's true if foo 1.2.3 is selected and false
    > if foo 2.3.4 is selected. Conversely, not foo ^1.0.0 is false if
    > foo 1.2.3 is selected and true if foo 2.3.4 is selected or if no
    > version of foo is selected at all."
    """

    @given(spec_set=specifier_sets())
    @SETTINGS
    def test_positive_and_negative_polarities_disagree_pointwise(
        self, spec_set: SpecifierSet
    ) -> None:
        """``v in R`` iff ``v not in ~R`` for every PEP 440 version."""
        r = _to_range(spec_set)
        positive = _term_set(r, positive=True)
        negative = _term_set(r, positive=False)
        for v in VERSION_POOL:
            assert (v in positive) is not (v in negative)


class TestQuoteTermsDenoteSets:
    """solver.md § Term, paragraph 4:

    > "Terms can be viewed as denoting sets of allowed versions, with
    > negative terms denoting the complement of the corresponding
    > positive term. Set relations and operations can be defined
    > accordingly."
    """

    @given(spec_set=specifier_sets())
    @SETTINGS
    def test_double_negation_returns_original_term(
        self, spec_set: SpecifierSet
    ) -> None:
        """``not not T == T``."""
        r = _to_range(spec_set)
        assert _term_set(_term_set(r, positive=False), positive=False) == r


class TestQuoteSetOperationExamples:
    """solver.md § Term, paragraph 5:

    > "* foo ^1.0.0 ∪ foo ^2.0.0 is foo >=1.0.0 <3.0.0.
    > * foo >=1.0.0 ∩ not foo >=2.0.0 is foo ^1.0.0.
    > * foo ^1.0.0 \\ foo ^1.5.0 is foo >=1.0.0 <1.5.0."
    """

    @given(a=specifier_sets(), b=specifier_sets())
    @SETTINGS
    def test_set_difference_equals_intersection_with_complement(
        self, a: SpecifierSet, b: SpecifierSet
    ) -> None:
        """``A \\ B`` (versions in A but not B) equals both ``A - B`` and ``A ∩ ~B``."""
        ra, rb = _to_range(a), _to_range(b)
        difference = ra & rb.complement()
        operator_difference = ra - rb
        for v in VERSION_POOL:
            in_a_not_b = v in ra and v not in rb
            assert (v in difference) == in_a_not_b
            assert (v in operator_difference) == in_a_not_b

    @given(spec_set=rich_specifier_sets(include_arbitrary=True))
    @SETTINGS
    def test_difference_with_empty_is_identity(self, spec_set: SpecifierSet) -> None:
        """``A \\ ∅ == A``, including the arbitrary-string and ``===`` admissions
        that subtracting through ``A ∩ ~∅`` used to drop."""
        ra = spec_set.to_range()
        assert ra - VersionRange.empty() == ra

    @given(spec_set=rich_specifier_sets(include_arbitrary=True))
    @SETTINGS
    def test_difference_with_self_is_empty(self, spec_set: SpecifierSet) -> None:
        """``A \\ A`` admits nothing, literals and arbitrary strings included."""
        ra = spec_set.to_range()
        assert (ra - ra).is_empty

    @given(a=specifier_sets(), b=specifier_sets())
    @SETTINGS
    def test_intersection_with_negation_excludes_negated_range(
        self, a: SpecifierSet, b: SpecifierSet
    ) -> None:
        """``v in A ∩ not B`` iff ``v in A`` and ``v not in B``."""
        ra, rb = _to_range(a), _to_range(b)
        result = ra & rb.complement()
        for v in VERSION_POOL:
            assert (v in result) == ((v in ra) and (v not in rb))


class TestQuoteSatisfiesAndContradictsIdentities:
    """solver.md § Term, paragraph 6:

    > "This turns out to be useful for computing satisfaction and
    > contradiction. Given a term t and a set of terms S, we have the
    > following identities:
    > * S satisfies t if and only if ⋂S ⊆ t.
    > * S contradicts t if and only if â‹‚S is disjoint with t."
    """

    @given(s=specifier_sets(), t=specifier_sets())
    @SETTINGS
    def test_subset_implies_pointwise_satisfaction(
        self, s: SpecifierSet, t: SpecifierSet
    ) -> None:
        """Structural ``⋂S ⊆ T`` implies every pooled version satisfying
        ``S`` also satisfies ``T``. Only this direction is sound: the
        finite pool makes the pointwise converse spuriously True."""
        rs, rt = _to_range(s), _to_range(t)
        if _is_subset(rs, rt):
            assert all((v not in rs) or (v in rt) for v in VERSION_POOL)

    @given(s=specifier_sets(), t=specifier_sets())
    @SETTINGS
    def test_disjoint_implies_pointwise_contradiction(
        self, s: SpecifierSet, t: SpecifierSet
    ) -> None:
        """Structural ``⋂S ∩ T == ∅`` implies no pooled version satisfies
        both ``S`` and ``T``. The pointwise converse is unsound on a
        finite pool, so only the forward direction is asserted."""
        rs, rt = _to_range(s), _to_range(t)
        if _is_disjoint(rs, rt):
            assert all((v not in rs) or (v not in rt) for v in VERSION_POOL)

    @given(s=specifier_sets(), t=specifier_sets())
    @SETTINGS
    def test_satisfies_iff_subset_negative(
        self, s: SpecifierSet, t: SpecifierSet
    ) -> None:
        """``S`` satisfies negative term ``not T`` iff ``⋂S ⊆ ~T``."""
        rs, rt = _to_range(s), _to_range(t)
        neg_t = _term_set(rt, positive=False)
        assert _is_subset(rs, neg_t) == _is_disjoint(rs, rt)

    @given(s=specifier_sets(), t=specifier_sets())
    @SETTINGS
    def test_contradicts_iff_disjoint_negative(
        self, s: SpecifierSet, t: SpecifierSet
    ) -> None:
        """``S`` contradicts negative term ``not T`` iff ``⋂S ⊆ T``."""
        rs, rt = _to_range(s), _to_range(t)
        neg_t = _term_set(rt, positive=False)
        assert _is_disjoint(rs, neg_t) == _is_subset(rs, rt)


class TestQuoteTrichotomy:
    """solver.md § Term, paragraph 2:

    > "We say that a set of terms S 'satisfies' a term t if t must be
    > true whenever every term in S is true. Conversely, S
    > 'contradicts' t if t must be false whenever every term in S is
    > true. If neither of these is true, we say that S is
    > 'inconclusive' for t. As a shorthand, we say that a term v
    > satisfies or contradicts t if {v} satisfies or contradicts it."
    """

    @given(s=specifier_sets(), t=specifier_sets())
    @SETTINGS
    def test_satisfies_and_contradicts_mutually_exclusive_on_non_empty(
        self, s: SpecifierSet, t: SpecifierSet
    ) -> None:
        """For non-empty ``â‹‚S``, ``S`` cannot both satisfy and contradict ``t``."""
        rs, rt = _to_range(s), _to_range(t)
        if rs.is_empty:
            return
        satisfies = _is_subset(rs, rt)
        contradicts = _is_disjoint(rs, rt)
        assert not (satisfies and contradicts)

    @given(s=specifier_sets(), t=specifier_sets())
    @SETTINGS
    def test_empty_intersection_is_both_satisfies_and_contradicts(
        self, s: SpecifierSet, t: SpecifierSet
    ) -> None:
        """An unsatisfiable ``S`` (``⋂S == ∅``) is vacuously both."""
        rs, rt = _to_range(s), _to_range(t)
        if not rs.is_empty:
            return
        assert _is_subset(rs, rt)
        assert _is_disjoint(rs, rt)

    @given(spec_set=specifier_sets())
    @SETTINGS
    def test_singleton_shorthand(self, spec_set: SpecifierSet) -> None:
        """``{v}`` satisfies ``t`` iff ``v in t``; trichotomy collapses on singletons."""
        rt = _to_range(spec_set)
        for v in VERSION_POOL:
            singleton = VersionRange.singleton(v)
            satisfies = _is_subset(singleton, rt)
            contradicts = _is_disjoint(singleton, rt)
            assert satisfies == (v in rt)
            assert contradicts == (v not in rt)
            assert satisfies != contradicts


class TestQuoteIncompatibilityNormalisation:
    """solver.md § Incompatibility, paragraph 2:

    > "Incompatibilities are normalized so that at most one term refers
    > to any given package name. For example, {foo >=1.0.0, foo
    > <2.0.0} is normalized to {foo ^1.0.0}. Derived incompatibilities
    > with more than one term are also normalized to remove positive
    > terms referring to the root package, since these terms will
    > always be satisfied."
    """

    @given(a=specifier_sets(), b=specifier_sets(), c=specifier_sets())
    @SETTINGS
    def test_three_term_merge_is_order_independent(
        self, a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
    ) -> None:
        """Merging ``{R1, R2, R3}`` over the same package is order-free."""
        ra, rb, rc = _to_range(a), _to_range(b), _to_range(c)
        m1 = ra & rb & rc
        m2 = ra & rc & rb
        m3 = rb & ra & rc
        m4 = rb & rc & ra
        m5 = rc & ra & rb
        m6 = rc & rb & ra
        assert m1 == m2 == m3 == m4 == m5 == m6


class TestQuoteBlogPostSatisfaction:
    """nex3.medium.com/pubgrub, § "So What Does PubGrub Do?":

    > "A term is satisfied if it matches the version of the package
    > that's selected. menu ≥1.1.0 is satisfied if menu 1.2.0 is
    > selected, and not dropdown ≥2.0.0 is satisfied if dropdown 1.8.0
    > is selected (or if no version of dropdown is selected at all)."
    """

    @given(spec_set=specifier_sets(), v=pep440_versions())
    @SETTINGS
    def test_concrete_version_satisfies_negative_term_iff_outside_range(
        self, spec_set: SpecifierSet, v: Version
    ) -> None:
        """Negative ``not T`` satisfied by ``v`` iff ``v not in T``."""
        rt = _to_range(spec_set)
        negative_set = _term_set(rt, positive=False)
        assert (v in negative_set) == (v not in rt)


class TestQuoteConcreteExamples:
    """solver.md § Term, paragraph 3:

    > "* {foo >=1.0.0, foo <2.0.0} satisfies foo ^1.0.0,
    > * foo ^1.5.0 contradicts not foo ^1.0.0,
    > * and foo ^1.0.0 is inconclusive for foo ^1.5.0."
    """

    @given(spec_set=specifier_sets())
    @SETTINGS
    def test_self_subset_satisfies_self(self, spec_set: SpecifierSet) -> None:
        """``R`` satisfies ``R``."""
        r = _to_range(spec_set)
        assert _is_subset(r, r)

    @given(a=specifier_sets(), b=specifier_sets())
    @SETTINGS
    def test_subset_implies_contradicts_negation(
        self, a: SpecifierSet, b: SpecifierSet
    ) -> None:
        """``A ⊆ B`` implies ``A & ~B == ∅``."""
        ra, rb = _to_range(a), _to_range(b)
        if not _is_subset(ra, rb):
            return
        assert _is_disjoint(ra, rb.complement())

    @given(a=specifier_sets(), b=specifier_sets())
    @SETTINGS
    def test_strict_superset_is_inconclusive_for_subset(
        self, a: SpecifierSet, b: SpecifierSet
    ) -> None:
        """``B ⊊ A`` ⇒ ``A`` neither satisfies nor contradicts ``B``."""
        ra, rb = _to_range(a), _to_range(b)
        if rb.is_empty or not _is_subset(rb, ra) or ra == rb:
            return
        assert not _is_subset(ra, rb)
        assert not _is_disjoint(ra, rb)


class TestQuoteSetSatisfiesIncompatibility:
    """solver.md § Incompatibility, paragraph 3:

    > "We say that a set of terms S satisfies an incompatibility I if
    > S satisfies every term in I. We say that S contradicts I if S
    > contradicts at least one term in I. If S satisfies all but one
    > of I's terms and is inconclusive for the remaining term, we say
    > S 'almost satisfies' I and we call the remaining term the
    > 'unsatisfied term'."
    """

    @given(s=specifier_sets(), t1=specifier_sets(), t2=specifier_sets())
    @SETTINGS
    def test_satisfies_two_term_incompatibility_iff_subset_of_intersection(
        self, s: SpecifierSet, t1: SpecifierSet, t2: SpecifierSet
    ) -> None:
        """``S satisfies {t1, t2}`` iff ``⋂S ⊆ t1 ∩ t2``."""
        rs, r1, r2 = _to_range(s), _to_range(t1), _to_range(t2)
        sat_universal = _is_subset(rs, r1) and _is_subset(rs, r2)
        sat_via_intersection = _is_subset(rs, r1 & r2)
        assert sat_universal == sat_via_intersection

    @given(s=specifier_sets(), t1=specifier_sets(), t2=specifier_sets())
    @SETTINGS
    def test_contradicts_two_term_incompatibility_iff_disjoint_with_either(
        self, s: SpecifierSet, t1: SpecifierSet, t2: SpecifierSet
    ) -> None:
        """``S contradicts {t1, t2}`` iff ``⋂S ∩ t1 == ∅`` OR ``⋂S ∩ t2 == ∅``."""
        rs, r1, r2 = _to_range(s), _to_range(t1), _to_range(t2)
        cont_existential = _is_disjoint(rs, r1) or _is_disjoint(rs, r2)
        # Per-term subset-of-complement form. Strictly stronger than
        # ``⋂S ⊆ (~t1 ∪ ~t2)`` (the pointwise existential).
        cont_existential_alt = _is_subset(rs, r1.complement()) or _is_subset(
            rs, r2.complement()
        )
        assert cont_existential == cont_existential_alt
        # Incompatibility is a set of terms, so the disjunction is
        # order-free.
        cont_reversed = _is_disjoint(rs, r2) or _is_disjoint(rs, r1)
        assert cont_existential == cont_reversed
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/test_ranges_set_algebra.py0000644000000000000000000004070415234171317020575 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.

"""Property tests for ``VersionRange`` Boolean lattice laws.

Identity, idempotence, commutativity, associativity, distributivity,
double-complement, De Morgan, and consistency with ``__contains__``.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from hypothesis import given

from packaging._ranges import intersect_ranges
from packaging.ranges import VersionRange
from packaging.specifiers import SpecifierSet

from .strategies import (
    SETTINGS,
    VERSION_POOL,
    eq_versions_only,
    pep440_versions,
    rich_specifier_sets,
    specifier_sets,
)

if TYPE_CHECKING:
    from packaging.version import Version

pytestmark = pytest.mark.property


def _to_range(spec_set: SpecifierSet) -> VersionRange:
    """Lift a non-``===`` SpecifierSet into a VersionRange."""
    return spec_set.to_range()


@given(spec_set=specifier_sets())
@SETTINGS
def test_intersect_with_unbounded_is_identity(spec_set: SpecifierSet) -> None:
    r = _to_range(spec_set)
    u = VersionRange.full()
    assert r.intersection(u) == r
    assert u.intersection(r) == r


@given(spec_set=specifier_sets())
@SETTINGS
def test_union_with_empty_is_identity(spec_set: SpecifierSet) -> None:
    r = _to_range(spec_set)
    e = VersionRange.empty()
    assert r.union(e) == r
    assert e.union(r) == r


@given(spec_set=specifier_sets())
@SETTINGS
def test_intersect_with_empty_is_empty(spec_set: SpecifierSet) -> None:
    r = _to_range(spec_set)
    e = VersionRange.empty()
    assert r.intersection(e) == e
    assert e.intersection(r) == e


@given(spec_set=specifier_sets())
@SETTINGS
def test_union_with_unbounded_is_unbounded(spec_set: SpecifierSet) -> None:
    r = _to_range(spec_set)
    u = VersionRange.full()
    assert r.union(u) == u
    assert u.union(r) == u


@given(spec_set=specifier_sets())
@SETTINGS
def test_idempotence(spec_set: SpecifierSet) -> None:
    r = _to_range(spec_set)
    assert r.union(r) == r
    assert r.intersection(r) == r


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_union_commutative(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = _to_range(a), _to_range(b)
    assert ra.union(rb) == rb.union(ra)


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_intersect_commutative(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = _to_range(a), _to_range(b)
    assert ra.intersection(rb) == rb.intersection(ra)


@given(a=specifier_sets(), b=specifier_sets(), c=specifier_sets())
@SETTINGS
def test_union_associative(a: SpecifierSet, b: SpecifierSet, c: SpecifierSet) -> None:
    ra, rb, rc = _to_range(a), _to_range(b), _to_range(c)
    assert ra.union(rb).union(rc) == ra.union(rb.union(rc))


@given(a=specifier_sets(), b=specifier_sets(), c=specifier_sets())
@SETTINGS
def test_intersect_associative(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    ra, rb, rc = _to_range(a), _to_range(b), _to_range(c)
    assert ra.intersection(rb).intersection(rc) == ra.intersection(rb.intersection(rc))


@given(spec_set=specifier_sets())
@SETTINGS
def test_double_complement_identity(spec_set: SpecifierSet) -> None:
    r = _to_range(spec_set)
    # Complement preserves every membership slot, so involution holds
    # structurally.
    assert r.complement().complement() == r


@given(spec_set=specifier_sets())
@SETTINGS
def test_complement_partitions(spec_set: SpecifierSet) -> None:
    r = _to_range(spec_set)
    c = r.complement()
    # r and ~r are disjoint and together cover every version. Compare on
    # the version subset: ``_admit_arbitrary`` only attaches to the
    # genuine universal range, so ``r | ~r`` never carries it when
    # neither side is empty.
    assert r.intersection(c).is_empty
    assert eq_versions_only(r.union(c), VersionRange.full())


@given(spec_set=specifier_sets())
@SETTINGS
def test_filter_nonemptiness_ignores_region(spec_set: SpecifierSet) -> None:
    # The region changes which versions come out first, never whether any do.
    r = _to_range(spec_set)
    stripped = ~~r
    assert bool(list(r.filter(VERSION_POOL))) == bool(
        list(stripped.filter(VERSION_POOL))
    )


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_de_morgan_intersect(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = _to_range(a), _to_range(b)
    # ``specifier_sets`` never produces the universal set, so both sides
    # stay in the PEP 440 universe and De Morgan holds structurally.
    assert (ra.intersection(rb)).complement() == ra.complement().union(rb.complement())


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_de_morgan_union(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = _to_range(a), _to_range(b)
    assert (ra.union(rb)).complement() == ra.complement().intersection(rb.complement())


@given(a=specifier_sets(), b=specifier_sets(), c=specifier_sets())
@SETTINGS
def test_intersect_distributes_over_union(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    ra, rb, rc = _to_range(a), _to_range(b), _to_range(c)
    lhs = ra.intersection(rb.union(rc))
    rhs = ra.intersection(rb).union(ra.intersection(rc))
    assert lhs == rhs


@given(a=specifier_sets(), b=specifier_sets(), c=specifier_sets())
@SETTINGS
def test_union_distributes_over_intersect(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    ra, rb, rc = _to_range(a), _to_range(b), _to_range(c)
    lhs = ra.union(rb.intersection(rc))
    rhs = ra.union(rb).intersection(ra.union(rc))
    assert lhs == rhs


@given(a=rich_specifier_sets(), b=rich_specifier_sets(), c=rich_specifier_sets())
@SETTINGS
def test_lattice_laws_hold_with_pre_release_regions(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    """The surviving lattice laws hold structurally when operands name pre-releases.

    ``specifier_sets`` builds only ``major.minor`` bounds, so the laws above
    never carry a non-empty opt-in region. ``rich_specifier_sets`` draws
    pre-release-naming specifiers, so this runs the clipped-region merge in
    ``_merged_region`` through commutativity, associativity, idempotence, double
    complement, De Morgan, and the ``& over |`` distributive law.

    Double complement is involutive on the version set but not the opt-in region
    (an exclusion grants no opt-in, so complement drops it), so it is checked
    with ``eq_versions_only``. ``| over &`` (L10) is not asserted: it fails once
    the region is clipped (see the negative locks in ``test_ranges.py``).
    """
    ra, rb, rc = a.to_range(), b.to_range(), c.to_range()
    assert ra | rb == rb | ra
    assert ra & rb == rb & ra
    assert (ra | rb) | rc == ra | (rb | rc)
    assert (ra & rb) & rc == ra & (rb & rc)
    assert ra | ra == ra
    assert ra & ra == ra
    assert eq_versions_only(~~ra, ra)
    assert ~(ra & rb) == ~ra | ~rb
    assert ~(ra | rb) == ~ra & ~rb
    assert ra.intersection(rb.union(rc)) == ra.intersection(rb).union(
        ra.intersection(rc)
    )


@given(a=rich_specifier_sets(), b=rich_specifier_sets(), c=rich_specifier_sets())
@SETTINGS
def test_region_stays_within_bounds(
    a: SpecifierSet, b: SpecifierSet, c: SpecifierSet
) -> None:
    """The opt-in region is a subset of the bounds across the op closure.

    This is the clip invariant: clipping the region against the bounds is a
    no-op precisely when the region already sits inside them.
    """
    ra, rb, rc = a.to_range(), b.to_range(), c.to_range()
    composites = [
        ra,
        ~ra,
        ra | rb,
        ra & rb,
        ra - rb,
        ra | (rb & rc),
        (ra | rb) & rc,
        (ra - rb) | rc,
    ]
    for r in composites:
        assert tuple(intersect_ranges(r._pre_region, r._bounds)) == r._pre_region


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_difference_equals_intersect_complement(
    a: SpecifierSet, b: SpecifierSet
) -> None:
    """``a - b == a & ~b`` over pre-release-naming pairs.

    ``rich_specifier_sets`` draws pre/post/dev/local/epoch RHS versions (no
    ``===`` and no configured policy), so the two agree on bounds and region.
    They would diverge over ``===`` literals and the arbitrary-string flag, which
    this strategy does not draw; a configured-policy mismatch (where difference
    raises like intersection) is covered by the unit tests in ``test_ranges.py``.
    """
    ra, rb = a.to_range(), b.to_range()
    intersect_complement = ra & ~rb
    assert ra - rb == intersect_complement
    assert list((ra - rb).filter(VERSION_POOL)) == list(
        intersect_complement.filter(VERSION_POOL)
    )


@given(spec_set=specifier_sets())
@SETTINGS
def test_operator_aliases(spec_set: SpecifierSet) -> None:
    """Operators mirror the named methods."""
    r = _to_range(spec_set)
    other = _to_range(SpecifierSet(">=1.0,<2.0"))
    assert (r & other) == r.intersection(other)
    assert (r | other) == r.union(other)
    assert (~r) == r.complement()


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_membership_consistent_with_intersect(a: SpecifierSet, b: SpecifierSet) -> None:
    """``v in (a & b)`` iff ``v in a`` AND ``v in b`` for every version."""
    ra, rb = _to_range(a), _to_range(b)
    intersection = ra.intersection(rb)
    for v in VERSION_POOL:
        assert (v in intersection) == ((v in ra) and (v in rb))


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_membership_consistent_with_union(a: SpecifierSet, b: SpecifierSet) -> None:
    """``v in (a | b)`` iff ``v in a`` OR ``v in b`` for every version."""
    ra, rb = _to_range(a), _to_range(b)
    union = ra.union(rb)
    for v in VERSION_POOL:
        assert (v in union) == ((v in ra) or (v in rb))


@given(spec_set=specifier_sets())
@SETTINGS
def test_membership_consistent_with_complement(spec_set: SpecifierSet) -> None:
    """``v in ~r`` iff ``v not in r`` for every version."""
    r = _to_range(spec_set)
    c = r.complement()
    for v in VERSION_POOL:
        assert (v in c) == (v not in r)


@given(spec_set=specifier_sets())
@SETTINGS
def test_exact_singleton_membership(spec_set: SpecifierSet) -> None:
    """``VersionRange.singleton(v)`` contains only ``v`` and no other version."""
    r = _to_range(spec_set)
    for v in VERSION_POOL:
        exact = VersionRange.singleton(v)
        assert v in exact
        # ``v`` is in (r & exact) iff v in r.
        assert (v in r.intersection(exact)) == (v in r)


@given(spec_set=specifier_sets())
@SETTINGS
def test_hash_equality_consistency(spec_set: SpecifierSet) -> None:
    """Equal ranges have equal hashes; usable as dict/set keys."""
    r1 = _to_range(spec_set)
    r2 = _to_range(spec_set)
    assert r1 == r2
    assert hash(r1) == hash(r2)


@given(spec_set=specifier_sets())
@SETTINGS
def test_complement_is_empty_iff_unbounded(spec_set: SpecifierSet) -> None:
    """``~r`` is empty exactly when ``r`` covers every version.

    Compares on the version subset only: a ``>=0.dev0``-derived range
    reaches FULL_RANGE bounds but does not admit arbitrary strings, so its
    complement is empty even though it is not structurally equal to
    ``VersionRange.full()``.
    """
    r = _to_range(spec_set)
    if r.complement().is_empty:
        assert eq_versions_only(r, VersionRange.full())
    if eq_versions_only(r, VersionRange.full()):
        assert r.complement().is_empty


@given(versions=specifier_sets(), v=pep440_versions())
@SETTINGS
def test_exact_equals_singleton_intersection(
    versions: SpecifierSet, v: Version
) -> None:
    """``r & exact(v)`` is non-empty iff v is in r, and equals exact(v) when so."""
    r = _to_range(versions)
    e = VersionRange.singleton(v)
    inter = r.intersection(e)
    if v in r:
        assert inter == e
    else:
        assert inter.is_empty


@given(spec_set=rich_specifier_sets())
@SETTINGS
def test_full_range_is_identity_for_filter(spec_set: SpecifierSet) -> None:
    """``full()`` is the identity for ``&`` w.r.t. filtering.

    Pre-release eligibility rides on the opt-in region (``_pre_region``), which
    ``__contains__`` ignores; only ``filter`` reads it. Folding
    ``full() & r1 & r2 & ...`` must never erase a range's region.
    """
    r = spec_set.to_range()
    full = VersionRange.full()
    expected = list(r.filter(VERSION_POOL))
    assert list((r & full).filter(VERSION_POOL)) == expected
    assert list((full & r).filter(VERSION_POOL)) == expected


@given(a=rich_specifier_sets(), b=rich_specifier_sets())
@SETTINGS
def test_intersection_filter_matches_merged_set(
    a: SpecifierSet, b: SpecifierSet
) -> None:
    """``to_range`` is a homomorphism w.r.t. intersection.

    A set built directly and one built by combining its specifiers carry the
    same opt-in region. The check is structural, not just today's filter output,
    because only equal raw regions stay equal (and filter identically) under a
    later widening union.
    """
    composed = a.to_range() & b.to_range()
    merged = (a & b).to_range()
    assert composed == merged
    assert list(composed.filter(VERSION_POOL)) == list(merged.filter(VERSION_POOL))

    wide = SpecifierSet(">=0").to_range()
    assert list((composed | wide).filter(VERSION_POOL)) == list(
        (merged | wide).filter(VERSION_POOL)
    )


@given(spec_set=rich_specifier_sets(include_arbitrary=True))
@SETTINGS
def test_to_range_filter_and_contains_mirror_specifier_set(
    spec_set: SpecifierSet,
) -> None:
    """``filter`` and ``__contains__`` on the range mirror the originating set.

    Closes the gap that the bounds-only fast path in ``SpecifierSet.filter``
    might diverge from ``VersionRange.filter`` on the ``prereleases=None``
    default, or that ``v in to_range()`` might drift from ``v in spec_set``.
    """
    r = spec_set.to_range()
    pool = [str(v) for v in VERSION_POOL] + ["unparsable", "garbage"]
    for prereleases in (None, True, False):
        assert list(r.filter(pool, prereleases=prereleases)) == list(
            spec_set.filter(pool, prereleases=prereleases)
        )
    for item in pool:
        assert (item in r) == (item in spec_set)


@given(spec_set=specifier_sets(vary_prereleases=True))
@SETTINGS
def test_configured_policy_mirrors_specifier_set(spec_set: SpecifierSet) -> None:
    """A configured ``prereleases`` policy filters and contains the same on the
    range as on the originating set.

    ``rich_specifier_sets`` (used above) always autodetects, so the
    ``prereleases = configured`` branch of ``filter`` and a configured
    ``contains`` go uncovered there; ``vary_prereleases`` draws explicit
    True/False/None policies to exercise them.
    """
    r = spec_set.to_range()
    assert list(r.filter(VERSION_POOL)) == list(spec_set.filter(VERSION_POOL))
    for v in VERSION_POOL:
        assert r.contains(v) == (v in spec_set)


@given(spec_set=rich_specifier_sets(include_arbitrary=True))
@SETTINGS
def test_unsatisfiable_implies_no_pool_match(spec_set: SpecifierSet) -> None:
    """A set flagged unsatisfiable can satisfy nothing under the same policy.

    Pinned to ``prereleases=False`` to exercise the prerelease-only branch
    that ``is_unsatisfiable`` consults; the implication is sound for any
    policy.
    """
    pinned = SpecifierSet(str(spec_set), prereleases=False)
    if pinned.is_unsatisfiable():
        assert not any(pinned.contains(v) for v in VERSION_POOL)


# Omitted: test_prerelease_only_implies_all_matches_are_prereleases relied on
# the dropped ``VersionRange.is_prerelease_only`` property.


@given(spec_set=specifier_sets(vary_prereleases=True))
@SETTINGS
def test_identity_laws_under_each_policy(spec_set: SpecifierSet) -> None:
    """``full``/``empty`` stamped with the same policy obey the four identities.

    Stamps ``full()``/``empty()`` with the same configured policy as the
    drawn range so ``_check_policy_compat`` accepts the pair, then asserts
    the four lattice identities under the version-only oracle (the
    universal-range arbitrary-string slot does not survive intersection).
    """
    r = spec_set.to_range()
    p = r._prereleases_configured
    full = VersionRange.full(prereleases=p)
    empty = VersionRange.empty(prereleases=p)
    assert eq_versions_only(r & full, r)
    assert eq_versions_only(r | empty, r)
    assert r & empty == empty
    assert eq_versions_only(r | full, full)


@given(spec_set=specifier_sets(vary_prereleases=True))
@SETTINGS
def test_idempotence_under_each_policy(spec_set: SpecifierSet) -> None:
    """``r & r == r`` and ``r | r == r`` for every configured policy."""
    r = spec_set.to_range()
    assert r & r == r
    assert r | r == r
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/test_ranges_set_relations.py0000644000000000000000000000766515234171317021211 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.

"""Property tests for ``is_subset`` / ``is_superset`` / ``is_disjoint``.

Each relation is pinned to its set-algebra definition (the oracle the methods
optimize): ``is_disjoint`` to ``(a & b).is_empty`` and ``is_subset`` to
``(a & ~b).is_empty``. The plain strategy exercises the bounds-only fast path;
the ``===`` strategy forces the algebra fallback, so the same oracle guards
both code paths. Pointwise-membership and symmetry are also checked.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from hypothesis import given

from packaging.ranges import VersionRange

from .strategies import (
    SETTINGS,
    VERSION_POOL,
    rich_specifier_sets,
    specifier_sets,
)

if TYPE_CHECKING:
    from packaging.specifiers import SpecifierSet

pytestmark = pytest.mark.property


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_disjoint_matches_algebra_plain(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = a.to_range(), b.to_range()
    assert ra.is_disjoint(rb) == (ra & rb).is_empty


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_subset_matches_algebra_plain(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = a.to_range(), b.to_range()
    assert ra.is_subset(rb) == (ra & ~rb).is_empty


@given(
    a=rich_specifier_sets(include_arbitrary=True),
    b=rich_specifier_sets(include_arbitrary=True),
)
@SETTINGS
def test_disjoint_matches_algebra_rich(a: SpecifierSet, b: SpecifierSet) -> None:
    """``===`` ranges defer to the algebra; ``_is_plain`` must gate them out."""
    ra, rb = a.to_range(), b.to_range()
    assert ra.is_disjoint(rb) == (ra & rb).is_empty


@given(
    a=rich_specifier_sets(include_arbitrary=True),
    b=rich_specifier_sets(include_arbitrary=True),
)
@SETTINGS
def test_subset_matches_algebra_rich(a: SpecifierSet, b: SpecifierSet) -> None:
    """``===`` ranges defer to the algebra; ``_is_plain`` must gate them out."""
    ra, rb = a.to_range(), b.to_range()
    assert ra.is_subset(rb) == (ra & ~rb).is_empty


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_superset_is_subset_mirror(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = a.to_range(), b.to_range()
    assert ra.is_superset(rb) == rb.is_subset(ra)


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_disjoint_symmetric(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = a.to_range(), b.to_range()
    assert ra.is_disjoint(rb) == rb.is_disjoint(ra)


@given(spec_set=specifier_sets())
@SETTINGS
def test_subset_and_superset_reflexive(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    assert r.is_subset(r)
    assert r.is_superset(r)


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_intersection_is_subset_and_pointwise(a: SpecifierSet, b: SpecifierSet) -> None:
    """``a & b`` is a subset of each operand, with consistent membership.

    Two independently drawn ranges are rarely a subset pair, so the
    intersection (always contained in each operand) drives the True branch
    in every example. Pointwise membership over the pool must agree.
    """
    ra, rb = a.to_range(), b.to_range()
    inter = ra & rb
    assert inter.is_subset(ra)
    assert inter.is_subset(rb)
    assert all(v in ra and v in rb for v in VERSION_POOL if v in inter)


@given(a=specifier_sets(), b=specifier_sets())
@SETTINGS
def test_disjoint_implies_no_shared_member(a: SpecifierSet, b: SpecifierSet) -> None:
    ra, rb = a.to_range(), b.to_range()
    if ra.is_disjoint(rb):
        assert not any(v in ra and v in rb for v in VERSION_POOL)


@given(spec_set=specifier_sets())
@SETTINGS
def test_empty_is_subset_and_disjoint(spec_set: SpecifierSet) -> None:
    r = spec_set.to_range()
    assert VersionRange.empty().is_subset(r)
    assert VersionRange.empty().is_disjoint(r)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/test_ranges_to_specifier_set.py0000644000000000000000000002527315234171317021657 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.

"""Property tests for ``VersionRange.to_specifier_set`` round-tripping.

The conversion is partial (not every range is specifier-expressible).
When it succeeds, the round trip equals the source: structurally, or (under a
``prereleases=False`` policy) on the releases the policy leaves observable.
``None`` is allowed; silent semantic drift is not.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest
from hypothesis import example, given

from packaging.specifiers import SpecifierSet

from .strategies import (
    SETTINGS,
    VERSION_POOL,
    adjacency_exclusion_sets,
    pep440_specifier_strings,
    rich_specifier_sets,
    specifier_sets,
)

if TYPE_CHECKING:
    from packaging.ranges import VersionRange

pytestmark = pytest.mark.property


_FILTER_PROBES = [
    "0.5a1",
    "1.0",
    "1.0a1",
    "1.0.dev0",
    "1.0.post1",
    "1.5a1",
    "1.5",
    "2.0",
    "1!1.0",
    "0",
]


def _equivalent_round_trip(source: VersionRange, recovered: VersionRange) -> bool:
    """A successful round trip matches the same versions as the source.

    Whether the encoder keeps or drops the synthetic ``.dev0`` markers, the
    recovered set's range equals the source, so equality is exact, except in two
    cases. A range that is empty under its policy has no unique structural form
    (e.g. ``===0.dev0`` with ``prereleases=False`` recovers as the canonical
    ``<0``): any empty recovery is equivalent. And under ``prereleases=False``
    the encoder may return a release-equivalent set with tighter bounds (``<3.14``
    for ``(-inf, 3.14)``), which the policy makes indistinguishable.
    """
    if source.is_empty and recovered.is_empty:
        return True
    if source == recovered:
        return True
    return source._prereleases_configured is False and source._same_releases(recovered)


@given(spec_set=specifier_sets(vary_prereleases=True))
@SETTINGS
def test_specifier_derived_ranges_always_have_a_specifier_set(
    spec_set: SpecifierSet,
) -> None:
    """Specifier-derived ranges re-encode (incl. ``<0`` for empty).

    The strategy stays well under the exclusion cap, so every drawn range has a
    single-set form; only a set spelling out hundreds of contiguous exclusions
    reaches the cap and returns ``None`` (see
    ``test_specifier_set_exclusion_cap_returns_none`` in tests/test_ranges.py).
    """
    r = spec_set.to_range()
    converted = r.to_specifier_set()
    assert converted is not None, (
        f"specifier-derived range {r!r} should always re-encode "
        f"(input was {spec_set!r})"
    )
    assert _equivalent_round_trip(r, converted.to_range())


@example(spec_set=SpecifierSet(">=3.8.dev0,<3.14", prereleases=True))
@example(spec_set=SpecifierSet(">3.8.post1"))
@example(spec_set=SpecifierSet("!=0.dev0"))
@example(spec_set=SpecifierSet("==1!0.*,<=1!0"))
@example(spec_set=SpecifierSet("!=1!0.dev0,==1!0.*"))
# Canonicalization folds these so two adjacent exclusions share one gap, a
# ``=1.0,!=1.0,!=1.0.post0.dev0"))
@example(spec_set=SpecifierSet("==1.0.*,!=1.0.dev0,!=1.0.dev1"))
@example(spec_set=SpecifierSet("==1!0.*,!=1!0.dev0,!=1!0.dev1"))
@example(spec_set=SpecifierSet("!=2.*,!=3.dev0,!=3.dev1"))
@given(
    spec_set=rich_specifier_sets(include_arbitrary=True, vary_prereleases=True),
)
@SETTINGS
def test_rich_specifier_derived_ranges_always_have_a_specifier_set(
    spec_set: SpecifierSet,
) -> None:
    """The full version-bearing PEP 440 surface re-encodes too.

    The narrow :func:`specifier_sets` strategy only emits ``major.minor`` bounds,
    so it never produced the ``.dev0`` / post-release / wildcard / epoch /
    parseable ``===`` shapes whose recovery this exercises. Every specifier-derived
    range the rich strategy builds has a single-set form, and the round trip is
    structurally exact. A lone arbitrary (non-version) ``===`` string re-encodes
    too, recovering as ``===string``; see ``test_arbitrary_literal_recovers_bare``
    in tests/test_ranges.py.
    """
    r = spec_set.to_range()
    converted = r.to_specifier_set()
    assert converted is not None, (
        f"specifier-derived range {r!r} should always re-encode "
        f"(input was {spec_set!r})"
    )
    assert _equivalent_round_trip(r, converted.to_range())


@given(spec_set=adjacency_exclusion_sets())
@SETTINGS
def test_adjacency_collapse_ranges_always_re_encode(spec_set: SpecifierSet) -> None:
    """A version excluded with a run of its immediate successors merges into one
    gap; the specifier-derived range still re-encodes and round-trips.

    The independent strategies draw exclusions at random, so they essentially
    never produce a contiguous successor run. This exercises the ``!=`` chain,
    dev-run, wildcard-then-dev-run, and epoch floor-run recovery paths when the
    drawn lead and base line up.
    """
    r = spec_set.to_range()
    converted = r.to_specifier_set()
    assert converted is not None, (
        f"adjacency-collapse range {r!r} should always re-encode "
        f"(input was {spec_set!r})"
    )
    assert _equivalent_round_trip(r, converted.to_range())


def _conflicting_configured(a: SpecifierSet, b: SpecifierSet) -> bool:
    """``VersionRange`` requires matching configured pre-release policies."""
    return a._prereleases != b._prereleases


@given(a=specifier_sets(vary_prereleases=True), b=specifier_sets(vary_prereleases=True))
@SETTINGS
def test_intersection_round_trips_when_not_none(
    a: SpecifierSet, b: SpecifierSet
) -> None:
    """SpecifierSet is closed under intersection."""
    if _conflicting_configured(a, b):
        return
    ra = a.to_range()
    rb = b.to_range()
    inter = ra & rb
    converted = inter.to_specifier_set()
    assert converted is not None
    assert _equivalent_round_trip(inter, converted.to_range())


@example(spec_set=SpecifierSet(">=2.3,<=2.7"))
@given(spec_set=specifier_sets(vary_prereleases=True))
@SETTINGS
def test_complement_round_trips_or_returns_none(spec_set: SpecifierSet) -> None:
    """The complement of a specifier-derived range is often not
    specifier-expressible (e.g. ``~(>=1,<2)`` is two disjoint intervals).
    Exercises the partial-conversion contract: ``to_specifier_set`` either
    returns ``None`` or round-trips equivalently (structural under
    autodetect / True, filter-equivalent under explicit False)."""
    r = spec_set.to_range().complement()
    converted = r.to_specifier_set()
    if converted is not None:
        assert _equivalent_round_trip(r, converted.to_range())


@given(spec_string=pep440_specifier_strings(include_arbitrary=True))
@SETTINGS
def test_single_specifier_round_trips_when_encodable(spec_string: str) -> None:
    """Single-specifier ranges round-trip exactly when
    ``to_specifier_set`` returns a set.

    The narrow round-trip tests above lift through ``to_range``, which folds
    via ``intersect_ranges`` and silently canonicalizes the non-canonical
    leading interval some single specifiers (e.g. ``!=0.dev0``) produce.
    This property exercises the single-specifier entry point. Every single
    specifier has ``_admit_arbitrary=False``, and the encoder preserves it,
    so full equality holds.
    """
    r = SpecifierSet(spec_string).to_range()
    converted = r.to_specifier_set()
    if converted is not None:
        assert converted.to_range() == r


@given(
    a=rich_specifier_sets(include_arbitrary=True),
    b=rich_specifier_sets(include_arbitrary=True),
)
@SETTINGS
def test_rich_algebra_round_trips_when_encodable(
    a: SpecifierSet, b: SpecifierSet
) -> None:
    """Ranges built by set algebra over the rich strategy round-trip on
    the version subset when ``to_specifier_set`` returns a set.

    The narrow round-trip strategy never reaches the encoder paths that
    handle ``!=V`` / ``!=V+local`` / ``!=V.*`` gaps, the ``==V+local``
    singleton, or multi-group unions; this property does. Pre-release
    policy tags can differ between the algebra result and its encoded
    round trip (the encoder collapses configured-None vs autodetect), and
    a ``MIN_VERSION`` lower bound canonicalizes to ``-inf``; both leave the
    accepted version set unchanged, so compare on the version subset.

    The complement variant ``~ra`` is split out into
    :func:`test_rich_algebra_complement_round_trips_when_encodable`.
    """
    ra, rb = a.to_range(), b.to_range()
    for r in (ra, ra & rb, ra | rb):
        converted = r.to_specifier_set()
        if converted is not None:
            recovered = converted.to_range()
            for v in VERSION_POOL:
                assert (v in recovered) == (v in r)


@example(spec_set=SpecifierSet(">=1.0,<=5.0"))
@given(spec_set=rich_specifier_sets(include_arbitrary=True))
@SETTINGS
def test_rich_algebra_complement_round_trips_when_encodable(
    spec_set: SpecifierSet,
) -> None:
    """``~r`` round-trips on the version subset when ``to_specifier_set``
    returns a set. Same contract as
    :func:`test_rich_algebra_round_trips_when_encodable` for the complement
    operand the original property covered in its ``~ra`` loop iteration."""
    r = spec_set.to_range().complement()
    converted = r.to_specifier_set()
    if converted is not None:
        recovered = converted.to_range()
        for v in VERSION_POOL:
            assert (v in recovered) == (v in r)


@given(spec_string=pep440_specifier_strings(include_arbitrary=True))
@SETTINGS
def test_round_trip_never_filter_drifts(spec_string: str) -> None:
    """When ``to_specifier_set`` returns a set, it filters identically.

    Guards the no-drift contract end-to-end: any time the encoder is willing
    to emit a single set, the recovered set must accept the same versions
    as the source range across a representative probe set. The
    ``recovered.to_range() == self`` round trip in ``to_specifier_set`` is what
    enforces this; the property is the observable contract.
    """
    r = SpecifierSet(spec_string).to_range()
    for variant in (r, ~r):
        converted = variant.to_specifier_set()
        if converted is None:
            continue
        assert list(variant.filter(_FILTER_PROBES)) == list(
            converted.filter(_FILTER_PROBES)
        )
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4562237
packaging-26.3/tests/property/test_specifier_comparison.py0000644000000000000000000007644515234171317021204 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=1785787087.4562237
packaging-26.3/tests/property/test_specifier_extended.py0000644000000000000000000001127315234171317020616 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=1785787087.4562237
packaging-26.3/tests/property/test_specifier_implied.py0000644000000000000000000007422115234171317020443 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=1785787087.4567523
packaging-26.3/tests/property/test_version_format.py0000644000000000000000000006503715234171317020031 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=1785787087.4567523
packaging-26.3/tests/property/test_version_normalization.py0000644000000000000000000006010715234171317021420 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=1785787087.4567523
packaging-26.3/tests/property/test_version_ordering.py0000644000000000000000000004105515234171317020344 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=1785787087.4567523
packaging-26.3/tests/property/test_version_releases.py0000644000000000000000000010456315234171317020342 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=1785787087.4567523
packaging-26.3/tests/pylock/pylock.spec-example.toml0000644000000000000000000000532415234171317017551 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=1785787087.4567523
packaging-26.3/tests/test_dependency_groups.py0000644000000000000000000004151715234171317016622 0ustar00from __future__ import annotations

import pickle
import re
import unittest.mock
from typing import TYPE_CHECKING, 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 InvalidRequirement, Requirement

if TYPE_CHECKING:
    import sys

    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_pickle_roundtrip() -> None:
    exc = CyclicDependencyGroup("group1", "group2", "group1")
    copy = pickle.loads(pickle.dumps(exc))
    assert copy.requested_group == exc.requested_group
    assert copy.group == exc.group
    assert copy.include_group == exc.include_group
    assert str(copy) == str(exc)


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


@pytest.mark.parametrize(
    ("item", "exc_type", "match"),
    [
        ({}, InvalidDependencyGroupObject, "Invalid dependency group item:"),
        ({"include-group": 5}, TypeError, "include-group value is not a string"),
    ],
)
def test_malformed_group_entries_are_not_cached_on_resolver_instance(
    item: object,
    exc_type: type[BaseException],
    match: str,
) -> None:
    groups: Any = {"test": [item]}
    resolver = DependencyGroupResolver(groups)

    for _ in range(2):
        with pytest.raises(
            ExceptionGroup, match=r"\[dependency-groups\] data for 'test' was malformed"
        ) as excinfo:
            resolver.lookup("test")
        assert _group_contains(excinfo, exc_type, match=match)


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_collects_invalid_requirement_with_sibling_errors() -> None:
    # A malformed PEP 508 requirement string used to raise InvalidRequirement
    # raw, which both escaped the aggregated "...was malformed" error group and
    # dropped any sibling errors already collected from the same group. It should
    # now be collected like every other failure so co-occurring errors are all
    # reported together.
    groups: Any = {
        "all": [
            {},  # invalid object -> collected before the bad requirement string
            "this is not a valid requirement!!!",
        ],
    }

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

    # the malformed requirement is aggregated rather than raised raw...
    assert _group_contains(excinfo, InvalidRequirement)
    # ...and the sibling error collected earlier in the same group is not dropped
    assert _group_contains(excinfo, InvalidDependencyGroupObject)


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=1785787087.4567523
packaging-26.3/tests/test_direct_url.py0000644000000000000000000002406015234171317015233 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": {},
            }
        )


@pytest.mark.parametrize(
    "url",
    [
        "FILE:///home/myproject",
        "File:///home/myproject",
        "file:/home/myproject",
        "file://localhost/home/myproject",
    ],
)
def test_dir_info_url_file_absolute_case_insensitive(url: str) -> None:
    """Per RFC 3986 §3.1, URL schemes are case-insensitive; all variants of
    absolute file URLs must be accepted when dir_info is present."""
    DirectUrl.from_dict({"url": url, "dir_info": {}})


@pytest.mark.parametrize(
    "url",
    [
        "file:relative",
        "file:./relative",
        "file:",
        "file://relative",
        "file://localhost",
    ],
)
def test_dir_info_url_requires_absolute_file_url(url: str) -> None:
    with pytest.raises(
        DirectUrlValidationError,
        match=r"File URL must be absolute when dir_info is present",
    ):
        DirectUrl.from_dict({"url": url, "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"),
        ("https://user:pa@ss@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_strip_url_with_at_in_password() -> None:
    direct_url = DirectUrl(
        url="https://user:pa@ss@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=1785787087.4567523
packaging-26.3/tests/test_elffile.py0000644000000000000000000000636515234171317014515 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.AArch64,
            "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=1785787087.4567523
packaging-26.3/tests/test_errors.py0000644000000000000000000000711415234171317014414 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=1785787087.4567523
packaging-26.3/tests/test_licenses.py0000644000000000000000000000204015234171317014676 0ustar00import pytest

from packaging.licenses import (
    InvalidLicenseExpression,
    canonicalize_license_expression,
)
from 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()


def test_licenseref_plus_suffix_is_invalid() -> None:
    with pytest.raises(InvalidLicenseExpression, match="Invalid licenseref"):
        canonicalize_license_expression("LicenseRef-Foo+")


@pytest.mark.parametrize(
    "license_expression",
    [
        "MIT WITH Classpath-exception-2.0 WITH GCC-exception-3.1",
        "(MIT) WITH Classpath-exception-2.0",
        "(MIT OR Apache-2.0) WITH Classpath-exception-2.0",
        "LicenseRef-",
    ],
)
def test_invalid_spdx_with_or_licenseref_forms(license_expression: str) -> None:
    with pytest.raises(InvalidLicenseExpression):
        canonicalize_license_expression(license_expression)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4567523
packaging-26.3/tests/test_manylinux.py0000644000000000000000000001564515234171317015134 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,
    _get_manylinux_module,
    _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()
    _get_manylinux_module.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" or _glibc_version_string() is None,
    reason="requires a glibc-based 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=1785787087.4577525
packaging-26.3/tests/test_markers.py0000644000000000000000000010353015234171317014543 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,
    UndefinedEnvironmentName,
    _cached_default_environment,
    _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 | int | list[str] | None) -> 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()

    @pytest.mark.parametrize(
        ("value", "expected"),
        [
            ("plain", '"plain"'),
            ('a"b', "'a\"b'"),
            ("a'b", '"a\'b"'),
        ],
    )
    def test_value_serialize_chooses_quote_delimiter(
        self, value: str, expected: str
    ) -> None:
        assert Value(value).serialize() == expected

    def test_value_serialize_rejects_both_quote_delimiters(self) -> None:
        with pytest.raises(
            ValueError,
            match="Cannot serialize marker value containing both quote characters",
        ):
            Value("a\"b'c").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_arbitrary_equality_on_non_version_key_is_undefined(self) -> None:
        # ``===`` has no entry in ``_operators`` and the version-specifier path
        # only runs for ``MARKERS_REQUIRING_VERSION`` keys, so evaluating ``===``
        # against a non-version key raises ``UndefinedComparison``. This pins the
        # post-#939 behavior (``packaging`` <= 25.0 evaluated it as plain string
        # equality); see #1239.
        for marker in ("os_name === 'posix'", "sys_platform === 'linux'"):
            with pytest.raises(UndefinedComparison):
                Marker(marker).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("line_break", ["\n", "\r", "\r\n"])
    def test_parses_invalid_trailing_line_break(self, line_break: str) -> None:
        with pytest.raises(InvalidMarker):
            Marker('python_version >= "3"' + line_break)

    @pytest.mark.parametrize("whitespace", [" ", "\t", " \t"])
    def test_parses_trailing_horizontal_whitespace(self, whitespace: str) -> None:
        assert Marker('python_version >= "3"' + whitespace) == Marker(
            'python_version >= "3"'
        )

    @pytest.mark.parametrize(
        ("marker_string", "expected"),
        [
            (
                'os_name == "C:\\"',
                "packaging.markers.InvalidMarker: Invalid quoted string\n"
                '    os_name == "C:\\"\n'
                "               ~~~~~^",
            ),
            (
                r'os_name == "\x"',
                "packaging.markers.InvalidMarker: Invalid quoted string\n"
                r'    os_name == "\x"'
                "\n"
                "               ~~~~^",
            ),
        ],
    )
    def test_parses_invalid_malformed_quoted_string(
        self, marker_string: str, expected: str
    ) -> None:
        with pytest.raises(InvalidMarker) as ctx:
            Marker(marker_string)
        assert ctx.exconly() == expected

    @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"'),
            (
                '\'a" == os_name or python_version >= "0" or "b\' == os_name',
                '\'a" == os_name or python_version >= "0" or "b\' == os_name',
            ),
            # 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_extra_compared_to_variable_not_normalized(self) -> None:
        # A variable-vs-variable atom must not be rewritten into a string
        # literal, even when one side is ``extra``.
        assert str(Marker("extra == os_name")) == "extra == os_name"
        assert str(Marker("os_name == extra")) == "os_name == extra"

    def test_nested_extra_str_normalization(self) -> None:
        marker = Marker(
            '(extra == "Foo_Bar" or extra == "Baz") and python_version >= "3"'
        )

        assert (
            str(marker)
            == '(extra == "foo-bar" or extra == "baz") and python_version >= "3"'
        )
        assert marker.evaluate({"extra": "foo-bar", "python_version": "3.12"})

    @pytest.mark.parametrize("variable", ["extras", "dependency_groups"])
    def test_membership_value_str_normalization(self, variable: str) -> None:
        # PEP 685 (extras) / PEP 735 (dependency_groups): the set-membership literal
        # is normalized at parse time, so __str__/__eq__/__hash__ stay consistent with
        # evaluate() (which already canonicalizes both operands for these keys).
        raw = Marker(f'"S_P__A_M" in {variable}')
        normalized = Marker(f'"s-p-a-m" in {variable}')

        assert str(raw) == f'"s-p-a-m" in {variable}'
        assert raw == normalized
        assert hash(raw) == hash(normalized)

    @pytest.mark.parametrize("variable", ["extras", "dependency_groups"])
    def test_membership_value_str_normalization_negated(self, variable: str) -> None:
        raw = Marker(f'"Foo_Bar" not in {variable}')

        assert str(raw) == f'"foo-bar" not in {variable}'
        assert raw == Marker(f'"foo-bar" not in {variable}')
        assert hash(raw) == hash(Marker(f'"foo-bar" not in {variable}'))

    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()

    def test_evaluate_does_not_mutate_cached_environment(self) -> None:
        # An evaluate() call that overrides values (and adds "extra") must not
        # leak those overrides into the cached environment used by later calls.
        marker = Marker("os_name == 'magic'")
        assert marker.evaluate({"os_name": "magic"})

        cached = _cached_default_environment()
        assert cached["os_name"] == os.name
        assert "extra" not in cached

        # A second evaluate with no overrides must not see the first call's
        # overrides, confirming the cache was copied rather than mutated.
        assert not marker.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")

    def test_missing_environment_key_raises_undefined_environment_name(self) -> None:
        marker = Marker('"foo" in extras')
        with pytest.raises(UndefinedEnvironmentName) as ctx:
            marker.evaluate()
        assert ctx.value.args == ("extras",)
        # UndefinedEnvironmentName subclasses KeyError, so the historical
        # bare ``except KeyError`` for a missing environment key still works.
        assert issubclass(UndefinedEnvironmentName, KeyError)
        with pytest.raises(KeyError):
            marker.evaluate()

    @pytest.mark.parametrize("variable", ["extras", "dependency_groups"])
    @pytest.mark.parametrize("op", ["==", "!=", ">=", "<="])
    def test_set_valued_marker_on_lhs_raises_undefined_comparison(
        self, variable: str, op: str
    ) -> None:
        """Set-valued markers are only defined in the membership form, so using
        one on the left-hand side of a comparison raises ``UndefinedComparison``."""
        marker = Marker(f"{variable} {op} 'foo'")
        with pytest.raises(UndefinedComparison):
            marker.evaluate(context="lock_file")

    @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_str_preserves_nested_group_precedence() -> None:
    # A nested group must keep its parentheses so str(Marker(...)) round-trips.
    m = Marker(
        'python_version < "3.10" and '
        '((sys_platform == "linux" or sys_platform == "darwin"))'
    )
    reparsed = Marker(str(m))
    for env in (
        {"python_version": "3.12", "sys_platform": "darwin"},
        {"python_version": "3.12", "sys_platform": "linux"},
        {"python_version": "3.9", "sys_platform": "darwin"},
    ):
        assert reparsed.evaluate(env) == m.evaluate(env)


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=1785787087.4577525
packaging-26.3/tests/test_metadata.py0000644000000000000000000016006515234171317014665 0ustar00from __future__ import annotations

import email
import inspect
import pathlib
import pickle
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


def _invalid_metadata_exceptions(
    exceptions: tuple[Exception, ...] | list[Exception],
) -> list[metadata.InvalidMetadata]:
    assert all(isinstance(exc, metadata.InvalidMetadata) for exc in exceptions)
    return typing.cast("list[metadata.InvalidMetadata]", list(exceptions))


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

    @pytest.mark.parametrize("encode", [False, True])
    def test_description_multipart_payload(self, encode: bool) -> None:
        # A multipart body makes get_payload() return a non-str; it must route
        # to unparsed rather than trip the old assert.
        metadata_text = (
            "Metadata-Version: 2.1\n"
            "Name: example\n"
            'Content-Type: multipart/mixed; boundary="BOUND"\n'
            "\n"
            "--BOUND\n"
            "Content-Type: text/plain\n"
            "\n"
            "the description\n"
            "--BOUND--\n"
        )
        given: str | bytes = metadata_text.encode("utf8") if encode else metadata_text
        raw, unparsed = metadata.parse_email(given)
        assert raw["name"] == "example"
        assert "description" not in raw
        assert "description" in unparsed

    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.6"
        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 TestInvalidMetadata:
    def test_pickle_roundtrip(self) -> None:
        exc = metadata.InvalidMetadata("version", "'1.0.a' is invalid")
        copy = pickle.loads(pickle.dumps(exc))
        assert copy.field == exc.field
        assert str(copy) == str(exc)


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.6",
    "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.6"
        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.6\nImport-Name:\n", validate=False
        )
        assert meta.import_names == []

    def test_from_email_validate_returns_valid_metadata(self) -> None:
        meta = metadata.Metadata.from_email(
            "Metadata-Version: 2.6\nName: packaging\nVersion: 1.0\n",
            validate=True,
        )

        assert meta.name == "packaging"
        assert str(meta.version) == "1.0"

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

        exceptions = exc_info.value.exceptions
        assert len(exceptions) == 4
        invalid_metadata = _invalid_metadata_exceptions(exceptions)
        assert {exc.field for exc in invalid_metadata} == {
            "hello",
            "metadata-version",
            "name",
            "version",
        }

    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_description_content_type_lowercase_charset(self) -> None:
        meta = metadata.Metadata.from_email(
            "Metadata-Version: 2.6\n"
            "Name: packaging\n"
            "Version: 1.0\n"
            "Description-Content-Type: text/plain; charset=utf-8\n"
        )

        assert meta.description_content_type == "text/plain; charset=utf-8"

    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_from_email_empty_metadata_uses_from_email_error_message(self) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email("", validate=True)

        assert exc_info.value.message == "invalid or unparsed metadata"
        invalid_metadata = _invalid_metadata_exceptions(exc_info.value.exceptions)
        assert {exc.field for exc in invalid_metadata} == {
            "metadata-version",
            "name",
            "version",
        }

    def test_from_email_collects_unparsed_field_with_valid_raw_metadata(self) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email(
                "Metadata-Version: 2.6\n"
                "Name: packaging\n"
                "Version: 1.0\n"
                "Unknown-Field: value\n"
            )

        (exc,) = exc_info.value.exceptions
        assert isinstance(exc, metadata.InvalidMetadata)
        assert exc.field == "unknown-field"
        assert exc_info.value.__context__ is None

    def test_from_email_collects_unparsed_and_invalid_fields(self) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email(
                "Metadata-Version: 2.6\n"
                "Name: packaging\n"
                "Name: packaging-copy\n"
                "Version: invalid version\n"
            )

        exceptions = exc_info.value.exceptions
        assert len(exceptions) == 2
        invalid_metadata = _invalid_metadata_exceptions(exceptions)
        assert {exc.field for exc in invalid_metadata} == {"name", "version"}
        assert exc_info.value.__context__ is None

    def test_from_email_collects_required_fields_after_unparsed_known_header(
        self,
    ) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email(
                "Name: packaging\nName: packaging-copy\nUnknown-Field: value\n"
            )

        exceptions = exc_info.value.exceptions
        assert len(exceptions) == 4
        invalid_metadata = _invalid_metadata_exceptions(exceptions)
        assert {exc.field for exc in invalid_metadata} == {
            "name",
            "unknown-field",
            "metadata-version",
            "version",
        }

    def test_from_email_collects_unknown_and_invalid_fields(self) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email(
                "Metadata-Version: 2.6\n"
                "Name: packaging\n"
                "Unknown-Field: value\n"
                "Version: invalid version\n"
            )

        exceptions = exc_info.value.exceptions
        assert len(exceptions) == 2
        invalid_metadata = _invalid_metadata_exceptions(exceptions)
        assert {exc.field for exc in invalid_metadata} == {
            "unknown-field",
            "version",
        }
        assert exc_info.value.__context__ is None

    def test_from_email_keeps_non_metadata_validation_errors(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # Synthetic scenario: from_raw only ever groups InvalidMetadata today,
        # so this covers the defensive isinstance check in from_email.
        def from_raw(
            raw: metadata.RawMetadata, *, validate: bool = True
        ) -> metadata.Metadata:
            del raw, validate
            raise ExceptionGroup("invalid metadata", [RuntimeError("boom")])

        monkeypatch.setattr(metadata.Metadata, "from_raw", from_raw)

        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email(
                "Metadata-Version: 2.6\nName: packaging\nVersion: 1.0\n"
            )

        (exc,) = exc_info.value.exceptions
        assert isinstance(exc, RuntimeError)
        assert str(exc) == "boom"

    @pytest.mark.parametrize(
        ("data", "field"),
        [
            (
                "Metadata-Version: 2.6\n"
                "Metadata-Version: 2.5\n"
                "Name: packaging\n"
                "Version: 1.0\n",
                "metadata-version",
            ),
            (
                "Metadata-Version: 2.6\n"
                "Name: packaging\n"
                "Name: packaging-copy\n"
                "Version: 1.0\n",
                "name",
            ),
            (
                "Metadata-Version: 2.6\nName: packaging\nVersion: 1.0\nVersion: 2.0\n",
                "version",
            ),
        ],
    )
    def test_from_email_deduplicates_unparsed_required_fields(
        self,
        data: str,
        field: str,
    ) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email(data)

        (exc,) = exc_info.value.exceptions
        assert isinstance(exc, metadata.InvalidMetadata)
        assert exc.field == field

    @pytest.mark.parametrize(
        "description_content_type",
        [
            "text/plain\n folded",
            'text/plain; charset="unterminated',
            "text/plain; {b}",
            "text/plain; a}b",
            "text/plain; x*",
        ],
    )
    def test_from_email_wraps_description_content_type_parse_errors(
        self,
        description_content_type: str,
    ) -> None:
        with pytest.raises(ExceptionGroup) as exc_info:
            metadata.Metadata.from_email(
                "Metadata-Version: 2.6\n"
                "Name: packaging\n"
                "Version: 1.0\n"
                f"Description-Content-Type: {description_content_type}\n"
            )

        (exc,) = exc_info.value.exceptions
        assert isinstance(exc, metadata.InvalidMetadata)
        assert exc.field == "description-content-type"
        assert repr(description_content_type) in str(exc)
        assert "is not a valid content type" in str(exc)

    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", "2.4", "2.5", "2.6"]
    )
    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_invalid_version_with_placeholder_text(self) -> None:
        # A user value containing the literal text "{field}" must survive
        # unchanged in the error message.
        meta = metadata.Metadata.from_raw({"version": "{field}"}, validate=False)
        with pytest.raises(metadata.InvalidMetadata) as exc_info:
            meta.version  # noqa: B018
        assert str(exc_info.value) == "'{field}' is invalid for 'version'"

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

        assert meta.summary == summary

    @pytest.mark.parametrize(
        "summary", ["Hello\n    Again", "Hello\rAgain", "Hello\u2028Again"]
    )
    def test_invalid_summary(self, summary: str) -> None:
        meta = metadata.Metadata.from_raw({"summary": summary}, 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/plain; charset=utf-8",
            "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/markdown; variant=gfm",
            "text/markdown; variant=commonmark",
            "text/plain; {b}",
            "text/plain; a}b",
            "text/plain; x*",
        ],
    )
    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_description_content_type_without_defects(self) -> None:
        meta = metadata.Metadata.from_raw(
            {"description_content_type": "application/octet-stream"}, 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

    def test_pep808_dynamic_with_static_values(self) -> None:
        """PEP 808 allows list/table fields to have static values
        while their key is also listed in ``Dynamic``."""
        raw: RawMetadata = {
            "metadata_version": "2.6",
            "name": "packaging",
            "version": "1.0.0",
            "classifiers": ["Development Status :: 4 - Beta"],
            "requires_dist": ["pytest"],
            "provides_extra": ["test"],
            "license_files": ["LICENSE"],
            "project_urls": {"homepage": "example.com"},
            "import_names": ["packaging"],
            "import_namespaces": ["pkg.ns"],
            "dynamic": [
                "classifier",
                "requires-dist",
                "provides-extra",
                "license-file",
                "project-url",
                "import-name",
                "import-namespace",
            ],
        }

        meta = metadata.Metadata.from_raw(raw, validate=True)
        assert meta.classifiers == ["Development Status :: 4 - Beta"]
        assert meta.requires_dist == [requirements.Requirement("pytest")]
        assert meta.provides_extra == [utils.canonicalize_name("test")]
        assert meta.license_files == ["LICENSE"]
        assert meta.project_urls == {"homepage": "example.com"}
        assert meta.import_names == ["packaging"]
        assert meta.import_namespaces == ["pkg.ns"]
        assert meta.dynamic == [
            "classifier",
            "requires-dist",
            "provides-extra",
            "license-file",
            "project-url",
            "import-name",
            "import-namespace",
        ]

        rfc822 = meta.as_rfc822()
        assert ("classifier", "Development Status :: 4 - Beta") in rfc822.items()
        assert ("requires-dist", "pytest") in rfc822.items()
        assert ("provides-extra", "test") in rfc822.items()
        assert ("license-file", "LICENSE") in rfc822.items()
        assert ("project-url", "homepage, example.com") in rfc822.items()
        assert ("import-name", "packaging") in rfc822.items()
        assert ("import-namespace", "pkg.ns") in rfc822.items()
        assert ("dynamic", "classifier") in rfc822.items()
        assert ("dynamic", "requires-dist") in rfc822.items()
        assert ("dynamic", "provides-extra") in rfc822.items()
        assert ("dynamic", "license-file") in rfc822.items()
        assert ("dynamic", "project-url") in rfc822.items()
        assert ("dynamic", "import-name") in rfc822.items()
        assert ("dynamic", "import-namespace") in rfc822.items()

    @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",
            "LicenseRef-Foo+",
            "LicenseRef-",
            "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",
            "mit WITH Classpath-exception-2.0 WITH GCC-exception-3.1",
            "(mit) WITH Classpath-exception-2.0",
            "(mit OR Apache-2.0) WITH Classpath-exception-2.0",
        ],
    )
    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.6\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_write_metadata_with_carriage_return(self) -> None:
        # A bare "\r" made the email generator raise HeaderWriteError.
        meta = metadata.Metadata.from_raw(
            {
                "version": "1.2.3",
                "name": "packaging",
                "author": "Hello\rWorld",
                "metadata_version": "2.3",
            }
        )
        written = meta.as_rfc822().as_string()
        assert (
            written == "metadata-version: 2.3\nname: packaging\nversion: 1.2.3"
            "\nauthor: Hello\n        World\n\n"
        )

    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.6",
                "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.6"),
            ("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.6",
                "name": "full_metadata",
                "version": "3.2.1",
                "import_names": [],
            }
        )

        core_metadata = meta.as_rfc822()
        assert core_metadata.items() == [
            ("metadata-version", "2.6"),
            ("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, str | None]], 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
        ]

    @pytest.mark.parametrize(
        "boundary",
        ["\r", "\r\n", "\v", "\f", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029"],
    )
    def test_headers_fold_every_line_boundary(self, boundary: str) -> None:
        message = metadata.RFC822Message()
        message["ItemA"] = f"ValueA{boundary}Requires-Dist: injected"

        assert str(message) == "ItemA: ValueA\n       Requires-Dist: injected\n\n"
        assert email.message_from_string(str(message)).items() == [
            ("ItemA", "ValueA\n       Requires-Dist: injected")
        ]

    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=1785787087.4577525
packaging-26.3/tests/test_musllinux.py0000644000000000000000000000552715234171317015146 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=1785787087.4577525
packaging-26.3/tests/test_pylock.py0000644000000000000000000006270115234171317014404 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_bool_rejected_for_int() -> None:
    # TOML distinguishes booleans from integers, so a boolean must be rejected
    # where an integer is expected even though bool is a subclass of int.
    data = {
        "lock-version": "1.0",
        "created-by": "pip",
        "packages": [
            {
                "name": "example",
                "wheels": [
                    {
                        "name": "example-1.0-py3-none-any.whl",
                        "path": "./example-1.0-py3-none-any.whl",
                        "hashes": {"sha256": "f" * 40},
                        "size": True,
                    }
                ],
            }
        ],
    }
    with pytest.raises(PylockValidationError) as exc_info:
        Pylock.from_dict(data)
    assert str(exc_info.value) == (
        "Unexpected type bool (expected int) in 'packages[0].wheels[0].size'"
    )


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",
        ),
        (
            # percent-encoded url file name is decoded
            PackageWheel(
                url="https://example.com/example-2.12.1%2Bcu130-py3-none-any.whl",
                hashes={},
            ),
            "example-2.12.1+cu130-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=1785787087.4577525
packaging-26.3/tests/test_pylock_select.py0000644000000000000000000003510215234171317015736 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, default_environment
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())


def test_empty_tags_selects_sdist_instead_of_host_compatible_wheel() -> None:
    pylock = _pylock_with_wheel_and_sdist()

    selected = list(
        pylock.select(
            tags=[],
            environment=_py312_linux.environment,
        )
    )

    assert len(selected) == 1
    assert isinstance(selected[0][1], PackageSdist)


def test_empty_tags_rejects_wheel_only_lock() -> None:
    pylock = _pylock_with_wheel_and_sdist(include_sdist=False)

    with pytest.raises(
        PylockSelectError, match=r"No wheel found matching .* and no sdist available"
    ):
        list(
            pylock.select(
                tags=[],
                environment=_py312_linux.environment,
            )
        )


def _pylock_with_wheel_and_sdist(
    *, wheel_python_tag: str | None = "py3", include_sdist: bool = True
) -> Pylock:
    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"},
                    )
                    if include_sdist
                    else None
                ),
                wheels=(
                    [
                        PackageWheel(
                            path=f"./foo-1.0-{wheel_python_tag}-none-any.whl",
                            hashes={"sha256": "abc123"},
                        )
                    ]
                    if wheel_python_tag is not None
                    else []
                ),
            ),
        ],
    )
    pylock.validate()
    return pylock


@pytest.mark.parametrize(
    ("wheel_python_tag", "include_sdist", "prefer_sdist", "expected_type", "called"),
    [
        ("py3", True, False, PackageWheel, True),
        ("py3", True, True, PackageSdist, True),
        ("py5", True, True, PackageSdist, True),
        ("py3", False, True, PackageWheel, False),
        (None, True, False, PackageSdist, True),
    ],
    ids=[
        "compatible-wheel-predicate-false",
        "sdist-predicate-true",
        "sdist-predicate-true-incompatible-wheel",
        "compatible-wheel-no-sdist",
        "sdist-only-predicate-false",
    ],
)
def test_prefer_sdist_predicate(
    wheel_python_tag: str | None,
    include_sdist: bool,
    prefer_sdist: bool,
    expected_type: type[object],
    called: bool,
) -> None:
    names: list[NormalizedName] = []

    def predicate(name: NormalizedName) -> bool:
        names.append(name)
        return prefer_sdist

    selected = list(
        _pylock_with_wheel_and_sdist(
            wheel_python_tag=wheel_python_tag,
            include_sdist=include_sdist,
        ).select(
            tags=_py312_linux.tags,
            environment=_py312_linux.environment,
            prefer_sdist_predicate=predicate,
        )
    )

    assert len(selected) == 1
    assert isinstance(selected[0][1], expected_type)
    assert names == (["foo"] if called else [])


@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


def test_python_prerelease() -> None:
    """Python pre-release versions are not PEP 440 compliant.
    Test that Pylock.requires_python supports that.
    """
    pylock = Pylock(
        lock_version=Version("1.0"),
        created_by="repro",
        requires_python=SpecifierSet(">=3.12"),
        packages=[
            Package(
                name=cast("NormalizedName", "pkga"),
                requires_python=SpecifierSet(">=3.12"),
                directory=PackageDirectory(path="./pkga"),
            )
        ],
    )
    env = default_environment()
    env["python_full_version"] = "3.15.0a8+"
    list(pylock.select(environment=env))
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4577525
packaging-26.3/tests/test_ranges.py0000644000000000000000000027000015234171317014353 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._ranges import BoundaryKind, BoundaryVersion
from packaging.ranges import _MAX_EXCLUSION_RUN, VersionRange
from packaging.specifiers import Specifier, SpecifierSet
from packaging.version import InvalidVersion, Version


def vr(spec: str, prereleases: bool | None = None) -> VersionRange:
    return SpecifierSet(spec, prereleases=prereleases).to_range()


class TestConstruction:
    def test_cannot_construct_directly(self) -> None:
        with pytest.raises(TypeError, match="cannot create"):
            VersionRange()

    def test_full(self) -> None:
        r = VersionRange.full()
        assert Version("1.0") in r
        assert "wat" in r
        assert not r.is_empty

    def test_full_no_arbitrary(self) -> None:
        r = VersionRange.full(admit_arbitrary=False)
        assert Version("1.0") in r
        assert "wat" not in r

    def test_empty(self) -> None:
        r = VersionRange.empty()
        assert r.is_empty
        assert Version("1.0") not in r
        assert "wat" not in r

    def test_empty_with_prereleases(self) -> None:
        r = VersionRange.empty(prereleases=True)
        assert r.is_empty
        assert r._prereleases_configured is True

    def test_full_with_prereleases(self) -> None:
        r = VersionRange.full(prereleases=False)
        assert r._prereleases_configured is False

    def test_singleton(self) -> None:
        r = VersionRange.singleton("1.2.3")
        assert Version("1.2.3") in r
        assert Version("1.2.4") not in r

    def test_singleton_is_strict(self) -> None:
        # ``==1.0`` matches 1.0+local; the strict singleton does not.
        assert Version("1.0+local") not in VersionRange.singleton("1.0")
        assert Version("1.0+local") in vr("==1.0")

    def test_singleton_accepts_version(self) -> None:
        assert Version("1.0") in VersionRange.singleton(Version("1.0"))

    def test_singleton_with_prereleases(self) -> None:
        r = VersionRange.singleton("1.0", prereleases=True)
        assert r._prereleases_configured is True

    def test_singleton_invalid(self) -> None:
        with pytest.raises(InvalidVersion):
            VersionRange.singleton("not a version")

    def test_singleton_floor_is_canonical_and_strict(self) -> None:
        # ``0.dev0`` is the minimum version, so the strict singleton collapses
        # its floor to the one canonical form ``(-inf, 0.dev0]`` while keeping
        # strict-equality semantics (locals and higher versions excluded).
        r = VersionRange.singleton("0.dev0")
        assert Version("0.dev0") in r
        assert Version("0.dev0+local") not in r
        assert Version("0") not in r
        # Floor collapsed: the lower bound is unbounded (-inf), not [0.dev0.
        assert r._bounds[0][0].version is None

    def test_singleton_above_floor_stays_strict(self) -> None:
        # ``0`` sorts above ``0.dev0`` (the floor), so its singleton must not
        # collapse: ``(-inf, 0]`` would wrongly admit ``0.dev0``.
        r = VersionRange.singleton("0")
        assert Version("0.dev0") not in r
        assert Version("0") in r


class TestToRange:
    def test_any(self) -> None:
        r = SpecifierSet().to_range()
        assert Version("1.0") in r
        assert Version("999.0") in r

    def test_unsatisfiable(self) -> None:
        assert SpecifierSet(">=2.0,<1.0").to_range().is_empty

    @pytest.mark.parametrize(
        ("spec", "inside", "outside"),
        [
            (">=1.0", "1.0", "0.9"),
            (">1.0", "1.1", "1.0"),
            ("<=1.0", "1.0", "1.1"),
            ("<1.0", "0.9", "1.0"),
            ("==1.0", "1.0", "1.1"),
            ("!=1.5", "1.4", "1.5"),
            ("~=1.4.2", "1.4.5", "1.5"),
            ("==1.2.*", "1.2.9", "1.3"),
        ],
    )
    def test_operators(self, spec: str, inside: str, outside: str) -> None:
        r = vr(spec)
        assert Version(inside) in r
        assert Version(outside) not in r

    def test_lte_includes_local_excludes_post(self) -> None:
        r = vr("<=1.0")
        assert Version("1.0") in r
        assert Version("1.0+local") in r
        assert Version("1.0.post1") not in r

    def test_gt_excludes_post(self) -> None:
        r = vr(">1.0")
        assert Version("1.0") not in r
        assert Version("1.0.post1") not in r
        assert Version("1.0.1") in r

    def test_arbitrary_equality_literal_range(self) -> None:
        # The nab carve-out contract: the literal string matches, no Version.
        r = vr("===1.0.special")
        assert "1.0.special" in r
        assert Version("1.0") not in r

    def test_arbitrary_equality_valid_version_literal(self) -> None:
        r = vr("===1.0")
        assert Version("1.0") in r
        assert Version("1.0.0") not in r  # arbitrary string, not version, match

    def test_arbitrary_combined_with_bounds(self) -> None:
        # ``===1.0,>=2.0``: only candidate "1.0" cannot satisfy >=2.0.
        assert vr("===1.0,>=2.0").is_empty

    def test_prerelease_autodetect(self) -> None:
        # Autodetected admission is stored as a region (the spec's own bounds);
        # a non-pre-release spec leaves the region empty.
        assert vr(">=1.0a1")._pre_region == vr(">=1.0a1")._bounds
        assert vr(">=1.0a1")._pre_region
        assert vr(">=1.0")._pre_region == ()

    def test_explicit_prereleases(self) -> None:
        r = vr(">=1.0", prereleases=False)
        assert r._prereleases_configured is False


class TestSetAlgebra:
    def test_intersection(self) -> None:
        assert vr(">=1.0") & vr("<2.0") == vr(">=1.0,<2.0")
        assert vr(">=1.0").intersection(vr("<2.0")) == vr(">=1.0,<2.0")

    def test_union(self) -> None:
        u = VersionRange.singleton("1.0") | VersionRange.singleton("2.0")
        assert Version("1.0") in u
        assert Version("2.0") in u
        assert Version("1.5") not in u
        assert VersionRange.singleton("1.0").union(VersionRange.singleton("2.0")) == u

    def test_complement(self) -> None:
        r = vr(">=1.0")
        assert Version("0.5") in r.complement()
        assert Version("1.5") not in r.complement()
        assert r.complement().complement() == r
        assert (~r) == r.complement()

    def test_complement_full_is_empty(self) -> None:
        assert (~VersionRange.full(admit_arbitrary=False)).is_empty

    def test_floor_singleton_obeys_structural_laws(self) -> None:
        # The ``0.dev0`` floor singleton used to keep a non-canonical
        # ``[0.dev0, ...)`` lower through set algebra, breaking these laws
        # structurally (the version set was always correct).
        s = VersionRange.singleton("0.dev0")
        assert s.complement().complement() == s
        assert s.union(s.complement()) == VersionRange.full(admit_arbitrary=False)
        assert s.union(s) == s

    def test_union_with_empty_preserves(self) -> None:
        r = vr(">=1.0")
        assert (r | VersionRange.empty()) == r

    def test_intersection_with_full_preserves_arbitrary(self) -> None:
        r = vr(">=1.0")
        assert (r & VersionRange.full()) == r

    def test_union_full_collapses(self) -> None:
        # ``r | full()`` collapses to the canonical universal range.
        r = VersionRange.singleton("1.0")
        collapsed = r | VersionRange.full()
        assert collapsed == VersionRange.full()

    def test_union_full_keeps_explicit_policy(self) -> None:
        r = VersionRange.singleton("1.0", prereleases=True)
        collapsed = r | VersionRange.full(prereleases=True)
        assert collapsed._prereleases_configured is True

    def test_union_full_preserves_autodetected_prerelease_policy(self) -> None:
        r = vr(">=1.0a1")
        assert list(r.filter(["1.3", "1.5a1"])) == ["1.3", "1.5a1"]

        # Both orders keep the autodetected opt-in as a region (here r's own
        # bounds), so only the pre-releases r named are admitted, not every
        # pre-release.
        assert (r | VersionRange.full())._pre_region == r._bounds
        assert (VersionRange.full() | r)._pre_region == r._bounds

        assert list((r | VersionRange.full()).filter(["1.3", "1.5a1"])) == [
            "1.3",
            "1.5a1",
        ]
        assert list((VersionRange.full() | r).filter(["1.3", "1.5a1"])) == [
            "1.3",
            "1.5a1",
        ]

        # The opt-in region is [1.0a1, +inf): a pre-release that sorts below it
        # is not force-admitted by the union.
        assert list((r | VersionRange.full()).filter(["0.5a1", "1.0"])) == ["1.0"]

    def test_arbitrary_flag_distinguishes_full(self) -> None:
        # nab contract: SpecifierSet("")-full differs from algebra-built full.
        flagged_full = SpecifierSet("").to_range()
        exact = VersionRange.singleton(Version("1.0"))
        plain_full = exact | ~exact
        assert plain_full != flagged_full
        assert (flagged_full & ~plain_full).is_empty

    def test_intersection_two_arbitrary(self) -> None:
        assert (vr("===a") & vr("===b")).is_empty
        assert "a" in (vr("===a") & vr("===a"))

    def test_union_two_arbitrary(self) -> None:
        u = vr("===a") | vr("===b")
        assert "a" in u
        assert "b" in u

    def test_full_intersect_arbitrary_keeps_literal(self) -> None:
        r = VersionRange.full() & vr("===wat")
        assert "wat" in r
        assert Version("1.0") not in r

    def test_complement_of_arbitrary_range(self) -> None:
        # nab complements root ranges built from ``===`` requirements.
        r = vr("===custom")
        assert not (~r).is_empty

    def test_empty_does_not_revive_arbitrary_admission(self) -> None:
        # ``~full()`` is empty yet keeps an inert arbitrary flag so that
        # ``~~full() == full()``. That flag must not revive and admit arbitrary
        # strings once a later operation widens the bounds back to full.
        full = VersionRange.full()
        plain = VersionRange.full(admit_arbitrary=False)
        assert ~~full == full  # the inert flag round-trips through complement
        assert (full & ~full) == VersionRange.empty()
        # The empty operand must not revive the flag from either side of a union,
        # nor through a difference that later complements back to full bounds.
        assert not (~full | plain).contains("wat")
        assert not (plain | ~full).contains("wat")
        assert (full & ~full) - full == VersionRange.empty()
        assert not (full - plain).complement().contains("wat")

    def test_difference_by_empty_keeps_arbitrary_admission(self) -> None:
        # ``~full()`` admits nothing (empty bounds, no literal, no region), so the
        # difference short-circuit returns self untouched, keeping full's
        # arbitrary admission (``full() - ~full() == full()``).
        full = VersionRange.full()
        assert (full - ~full) == full
        assert (full - ~full).contains("wat")

    def test_union_of_empty_ranges_keeps_arbitrary_flag(self) -> None:
        # A union whose result stays empty-bounds has no widening to revive
        # admission through, so ``~full()`` keeps its inert flag and union is
        # idempotent. Intersection always drops the flag at empty bounds, so
        # neither ``r & r`` nor ``r & full()`` is ``r``.
        r = ~VersionRange.full()
        assert r | r == r
        assert r | VersionRange.empty() == r
        assert (~(r | r)).contains("wat")
        assert r & r == VersionRange.empty()
        assert r & VersionRange.full() == VersionRange.empty()

    def test_difference_shrink_forgets_arbitrary_admission(self) -> None:
        # A difference that shrinks the bounds forgets the arbitrary flag, so
        # a later widening union cannot revive an admission neither operand
        # had, and ``full() - r`` agrees with ``full() & ~r``. A difference
        # that removes no versions keeps it, so ``a - b == a`` whenever ``b``
        # is disjoint from ``a``, empty-bounds minuends included.
        full = VersionRange.full()
        shrunk = full - vr(">=1.0")
        assert not shrunk.contains("wat")
        assert not (shrunk | vr(">=0.5")).contains("wat")
        assert (shrunk | vr(">=0.5")) == VersionRange.full(admit_arbitrary=False)
        assert shrunk == full & ~vr(">=1.0")
        assert (~full - vr(">=1.0")) == ~full

    def test_policy_mismatch_raises(self) -> None:
        with pytest.raises(ValueError, match="different"):
            vr(">=1.0", prereleases=True) & vr("<2.0", prereleases=False)

    def test_operator_wrong_type(self) -> None:
        assert vr(">=1.0").__and__("x") is NotImplemented
        assert vr(">=1.0").__or__("x") is NotImplemented
        assert vr(">=1.0").__sub__("x") is NotImplemented

    def test_intersection_wrong_type_raises(self) -> None:
        with pytest.raises(TypeError, match="expected VersionRange"):
            vr(">=1.0").intersection("x")  # type: ignore[arg-type]

    def test_difference_wrong_type_raises(self) -> None:
        with pytest.raises(TypeError, match="expected VersionRange"):
            vr(">=1.0").difference("x")  # type: ignore[arg-type]

    def test_difference(self) -> None:
        d = vr(">=1.0") - vr(">=2.0")
        assert Version("1.5") in d
        assert Version("1.0") in d
        assert Version("2.0") not in d
        assert d == vr(">=1.0") & ~vr(">=2.0")

    def test_difference_method_matches_operator(self) -> None:
        assert vr(">=1.0").difference(vr(">=2.0")) == vr(">=1.0") - vr(">=2.0")

    def test_difference_with_empty_is_self(self) -> None:
        r = vr(">=1.0,<2.0")
        assert (r - VersionRange.empty()) == r

    def test_difference_with_full_is_empty(self) -> None:
        assert (vr(">=1.0") - VersionRange.full()).is_empty

    def test_difference_keeps_minuend_prerelease_policy(self) -> None:
        # ``>=1.0`` admits no pre-releases; subtracting a pre-release-naming
        # range must not grant pre-release admission.
        no_pre = vr(">=1.0") - vr(">=2.0b1")
        assert list(no_pre.filter(["2.0b1", "1.5a1", "1.0"])) == ["1.0"]
        # A pre-release-admitting minuend keeps admitting its pre-releases.
        keep = vr(">=2.0b1") - vr(">=3.0")
        assert list(keep.filter(["2.5", "2.0b1"])) == ["2.5", "2.0b1"]

    def test_difference_requires_matching_policy(self) -> None:
        # difference matches ``self & ~other``, which requires a shared
        # configured policy, so a mismatch raises like intersection and union.
        with pytest.raises(ValueError, match="different"):
            vr(">=1.0") - vr(">=2.0", prereleases=True)

    def test_difference_punches_hole(self) -> None:
        # Subtracting an interior range leaves two intervals.
        d = vr(">=1.0") - vr(">=2.0,<3.0")
        assert Version("1.5") in d
        assert Version("2.5") not in d
        assert Version("3.5") in d

    def test_difference_with_literals(self) -> None:
        # ``===`` literal ranges route through the literal-combining branch.
        assert Version("1.0") in (vr("===1.0") - vr("===2.0"))
        assert Version("2.0") not in (vr("===1.0") - vr("===2.0"))
        assert Version("1.0") in (vr("===1.0") - vr(">=2.0"))

    def test_difference_with_empty_preserves_arbitrary(self) -> None:
        # Regression: difference once routed through ``other.complement()``,
        # which dropped the minuend's arbitrary-string admission even when
        # nothing was subtracted. ``a - empty`` must round-trip the full range.
        full = VersionRange.full()
        assert (full - VersionRange.empty()) == full
        assert "wat" in (full - VersionRange.empty())

    def test_difference_with_empty_preserves_literals(self) -> None:
        # The same regression for ``===`` admission: a literal range minus the
        # empty range keeps its literal.
        wat = vr("===wat")
        assert (wat - VersionRange.empty()) == wat
        assert "wat" in (wat - VersionRange.empty())

    def test_difference_excludes_only_named_literal(self) -> None:
        # full() minus a ``===`` literal keeps every version and every other
        # arbitrary string, dropping only the excluded literal.
        d = VersionRange.full() - vr("===wat")
        assert "wat" not in d
        assert "custom" in d
        assert Version("1.0") in d

    def test_difference_with_self_is_empty(self) -> None:
        # ``a - a`` is empty for arbitrary-admitting and ``===`` ranges too.
        assert (vr("===wat") - vr("===wat")).is_empty
        assert (VersionRange.full() - VersionRange.full()).is_empty

    def test_difference_minuend_with_reject_literal(self) -> None:
        # Complementing a ``===`` range leaves a reject literal on the minuend;
        # difference keeps honoring it through the literal-combining branch.
        minuend = ~vr("===1.0")
        d = minuend - vr("===2.0")
        assert Version("3.0") in d
        assert Version("1.0") not in d
        assert Version("2.0") not in d


class TestPrereleaseRegion:
    """The autodetected pre-release opt-in is stored as a range (``_pre_region``),
    clipped to the bounds, so it stays attached to the versions it came from
    across set algebra and never reaches past them."""

    def test_union_keeps_opt_in_scoped_to_originating_range(self) -> None:
        # ``>=1.0 | >=2.0b1``: the opt-in came only from the ``>=2.0b1`` side, so
        # a pre-release below 2.0b1 is not force-admitted, while pre-releases at
        # or above it are.
        u = vr(">=1.0") | vr(">=2.0b1")
        assert list(u.filter(["1.0", "1.5b1", "2.0b1", "2.5", "2.5b1"])) == [
            "1.0",
            "2.0b1",
            "2.5",
            "2.5b1",
        ]
        assert u._pre_region == vr(">=2.0b1")._bounds

    def test_narrowing_permanently_sheds_out_of_bounds_opt_in(self) -> None:
        # The region is clipped to the bounds, so a narrowing intersection drops
        # the opt-in that fell outside; a later widening cannot bring it back.
        inter = vr(">=1.0a1") & vr("<1.5")
        assert inter._pre_region == inter._bounds  # clipped to [1.0a1, 1.5)
        assert list(inter.filter(["1.2a1", "2.0a1", "2.5"])) == ["1.2a1"]
        # 2.0a1 is back in bounds but no longer in the region, so it is buffered
        # and then suppressed by the in-bounds final 2.5.
        wide = inter | vr("<3.0")
        assert list(wide.filter(["1.2a1", "2.0a1", "2.5"])) == ["1.2a1", "2.5"]

    def test_difference_of_two_region_bearing_ranges(self) -> None:
        # Both operands carry an opt-in region; a - b still equals a & ~b.
        a, b = vr(">=1.0a1,<5.0"), vr(">=2.0b1")
        cand = ["1.0a1", "1.5b1", "2.0b1", "2.5b1", "4.0"]
        assert (a - b) == (a & ~b)
        assert list((a - b).filter(cand)) == list((a & ~b).filter(cand))

    def test_intersection_with_complement_equals_difference(self) -> None:
        # ``a & ~b`` grants none of b's opt-in (complement drops it) just as
        # ``a - b`` does, so the two agree even when b names a pre-release.
        a, b = vr(">=1.0"), vr(">=2.0b1")
        cand = ["1.0", "1.5b1", "2.0b1", "2.5", "2.5b1"]
        assert (a & ~b) == (a - b)
        assert list((a & ~b).filter(cand)) == list((a - b).filter(cand))
        assert list((a & ~b).filter(cand)) == ["1.0"]

    def test_full_intersection_keeps_operand_opt_in(self) -> None:
        # ``full() & req`` must preserve req's own opt-in region.
        req = vr(">=2.0b1")
        assert (VersionRange.full() & req)._pre_region == req._bounds
        assert list((VersionRange.full() & req).filter(["2.0b1", "2.5"])) == [
            "2.0b1",
            "2.5",
        ]

    def test_union_filter_buffers_as_one_set(self) -> None:
        # The union is a single range: an in-range final makes PEP 440 buffer
        # away a non-opted pre-release, even though one operand alone (with no
        # final) would have emitted it. The opted-in pre-release still shows.
        u = vr(">=1.0,<1.8") | vr(">=1.5b1,<2.0")
        assert list(u.filter(["1.2a1", "1.7b1", "1.9"])) == ["1.7b1", "1.9"]

    def test_union_filter_emits_buffered_prerelease_when_no_final(self) -> None:
        # Region narrower than bounds: a pre-release in bounds but outside the
        # opt-in region is buffered, then emitted because no in-bounds final
        # appears (the PEP 440 "only available" fallback). An in-bounds final
        # then suppresses the buffer.
        u = vr(">=1.0") | vr(">=2.0b1")  # bounds [1.0, inf), region [2.0b1, inf)
        assert list(u.filter(["1.5b1", "1.2a1"])) == ["1.5b1", "1.2a1"]
        assert list(u.filter(["1.5b1", "1.2a1", "1.3"])) == ["1.3"]

    def test_double_complement_drops_region_keeps_versions(self) -> None:
        # A complement is an exclusion and carries no opt-in, so a double
        # complement covers the same versions as the original yet force-admits
        # none of its pre-releases.
        r = vr(">=2.0b1")
        assert (~~r)._bounds == r._bounds
        assert (~~r)._pre_region == ()
        cand = ["1.5b1", "2.0b1", "2.5", "2.5b1"]
        assert list(r.filter(cand)) == ["2.0b1", "2.5", "2.5b1"]
        assert list((~~r).filter(cand)) == ["2.5"]

    def test_difference_minuend_with_literal_and_region(self) -> None:
        # A minuend carrying both a ``===`` literal and an autodetected opt-in
        # region keeps the literal (self-admits-and-not-other) and the region.
        minuend = vr("===wat") | vr(">=2.0b1")
        d = minuend - vr(">=3.0")
        assert "wat" in d
        assert list(d.filter(["2.0b1", "2.5b1", "2.9", "3.0"])) == [
            "2.0b1",
            "2.5b1",
            "2.9",
        ]

    def test_difference_minuend_with_configured_policy(self) -> None:
        # A configured policy governs globally and carries no opt-in region, so a
        # difference between two configured operands keeps no region. Both must
        # share the policy, as intersection and union require.
        d = vr(">=1.0", prereleases=False) - vr(">=2.0b1", prereleases=False)
        assert d._pre_region == ()
        assert list(d.filter(["1.5b1", "1.0"])) == ["1.0"]

    def test_difference_equals_intersect_complement_when_b_complement_derived(
        self,
    ) -> None:
        # ``a - b == a & ~b`` even when ``b`` is complement-derived: a complement
        # carries no opt-in region, so both spellings admit none of ~b's in-bounds
        # pre-releases. (Two region-bearing operands are covered above.)
        a = vr("<5.0")
        b = vr(">=2.0b1").complement()
        left, right = a & ~b, a - b
        assert left._pre_region == right._pre_region
        assert left == right
        cand = ["2.5b1", "3.0", "2.0b1", "4.0"]
        assert list(left.filter(cand)) == list(right.filter(cand))

    def test_construction_region_matches_algebra(self) -> None:
        # A multi-specifier set built directly carries the same opt-in region as
        # one built by combining its specifiers: clipping refolds under
        # intersection, so the two stay equal under a later widening.
        direct = vr(">=1.0a1,<3.0")
        composed = vr(">=1.0a1") & vr("<3.0")
        assert direct._pre_region == composed._pre_region
        assert direct == composed
        pool = ["1.0a1", "2.0b1", "2.9", "3.0b1", "4.5"]
        wide = vr(">=2.0,<5.0")
        assert list((direct | wide).filter(pool)) == list(
            (composed | wide).filter(pool)
        )

        # Same congruence on the ``===`` (arbitrary) build path.
        direct_arb = vr("===2.0,>=1.0a1")
        composed_arb = vr("===2.0") & vr(">=1.0a1")
        assert direct_arb._pre_region == composed_arb._pre_region
        assert direct_arb == composed_arb

    def test_named_literal_prerelease_is_force_admitted(self) -> None:
        # A ``===`` literal naming a pre-release force-admits it under the default
        # policy even when a final release in the union would otherwise buffer it
        # away. contains agrees, and an explicit prereleases=False still drops it.
        u = vr("===1.0a1") | vr(">=3.0")
        assert list(u.filter(["1.0a1", "3.0"])) == ["1.0a1", "3.0"]
        assert u.contains("1.0a1")
        assert list(u.filter(["1.0a1", "3.0"], prereleases=False)) == ["3.0"]

    def test_difference_by_empty_preserves_empty_self(self) -> None:
        # ``a - empty()`` returns a unchanged even when a is itself empty but
        # carries provenance: ``~full()`` keeps its arbitrary flag for involution,
        # so subtracting a nothing-admitting set must not drop it.
        nf = ~VersionRange.full()
        assert (nf - VersionRange.empty()) == nf
        assert (nf - nf) == nf  # ~full() admits nothing, so this is a no-op too

    def test_difference_excludes_other_by_bounds(self) -> None:
        # difference treats other as a bounds-only exclusion: with a shared
        # configured policy it excises the versions in other's bounds and agrees
        # with a & ~b there.
        a = SpecifierSet(">=1.0", prereleases=False).to_range()
        b = SpecifierSet(">=1.5,<2.0", prereleases=False).to_range()
        assert (a - b) == (a & ~b)
        assert "1.2" in (a - b)
        assert "1.6" not in (a - b)

    def test_empty_bounds_intersection_equals_empty(self) -> None:
        # A region is clipped to the bounds, so an intersection with empty bounds
        # can carry none: it equals empty() and cannot re-admit anything after a
        # re-widening union.
        empty_region = vr(">=2.0a1") & vr("<1.0")
        assert empty_region.is_empty
        assert empty_region._pre_region == ()
        assert empty_region == VersionRange.empty()
        assert hash(empty_region) == hash(VersionRange.empty())
        assert list((empty_region | vr(">=0")).filter(["2.0a1", "3.0"])) == ["3.0"]

    def test_multi_interval_region_force_admits(self) -> None:
        # Disjoint multi-interval bounds with a two-interval opt-in region
        # exercise the multi-range path of filter_by_ranges: a pre-release inside
        # the region is force-admitted in either interval.
        r = vr(">=1.0a1,<2.0") | vr(">=3.0a1,<4.0")
        assert len(r._bounds) == 2
        assert list(r.filter(["1.5a1", "3.5a1", "3.5"])) == ["1.5a1", "3.5a1", "3.5"]

    def test_region_upper_bound_clips_force_admit(self) -> None:
        # The region has a finite upper bound (~=1.0a1 gives [1.0a1, 2.dev0)), so a
        # pre-release in bounds but ABOVE the region is not force-admitted. After
        # widening with >=2.5, 2.6a1 is in bounds yet above the region, so it is
        # buffered and then suppressed by the in-bounds final 2.7.
        r = vr("~=1.0a1") | vr(">=2.5")
        assert list(r.filter(["1.5a1", "2.6a1", "2.7"])) == ["1.5a1", "2.7"]

    def test_disjoint_region_does_not_force_admit_gap(self) -> None:
        # A disjoint two-interval region whose bounds span the gap: a pre-release
        # in the region gap (but in bounds) is buffered, not force-admitted, and
        # an in-bounds final then suppresses it. The filler ``>=2.0,<5.0`` widens
        # the bounds over the gap without adding to the region.
        r = (vr("<2.0a5") | vr(">=5.0a1")) | vr(">=2.0,<5.0")
        assert len(r._pre_region) == 2
        assert list(r.filter(["1.0a1", "3.0a1", "6.0a1", "3.0"])) == [
            "1.0a1",
            "6.0a1",
            "3.0",
        ]

    def test_force_admit_does_not_suppress_buffer(self) -> None:
        # A region-admitted pre-release is not a final, so it does not suppress a
        # separate buffered (out-of-region) pre-release when no final appears.
        u = vr(">=1.0") | vr(">=2.0b1")  # region [2.0b1, inf)
        assert list(u.filter(["2.5b1", "1.5b1"])) == ["2.5b1", "1.5b1"]

    def test_region_force_admit_through_key(self) -> None:
        # The region force-admit fires when filtering with a key callable too.
        u = vr(">=1.0") | vr(">=2.0b1")
        items = [{"v": "2.0b1"}, {"v": "1.5b1"}, {"v": "2.5"}]
        assert list(u.filter(items, key=lambda d: d["v"])) == [
            {"v": "2.0b1"},
            {"v": "2.5"},
        ]

    def test_difference_keeps_minuend_region_clipped(self) -> None:
        # difference keeps the minuend's opt-in region (not the subtrahend's) and
        # clips it to the result bounds.
        a = vr(">=2.0b1")  # region [2.0b1, +inf)
        b = vr(">=5.0")  # no region
        d = a - b
        assert d._pre_region == d._bounds  # clipped to [2.0b1, 5.0)
        assert list(d.filter(["2.0b1", "2.5b1", "4.9", "5.0"])) == [
            "2.0b1",
            "2.5b1",
            "4.9",
        ]

    def test_difference_by_empty_bounds_range(self) -> None:
        # An empty-bounds range carries no region under clipping, so subtracting
        # it is a no-op that still equals a & ~b (~empty == full).
        a = vr(">=0,<10.0")
        b = vr(">=2.0a1") & vr("<1.0")  # empty bounds, no region
        assert b.is_empty
        assert not b._bounds
        assert b._pre_region == ()
        cand = ["2.0a1", "2.5a1", "5.0"]
        assert (a - b) == (a & ~b) == a
        assert list((a - b).filter(cand)) == list((a & ~b).filter(cand))

    def test_configured_policy_with_prerelease_spec_mirrors_specifier_set(self) -> None:
        # A configured policy on a pre-release-naming set drops the opt-in region
        # (the policy governs); filter and contains still mirror the set.
        pool = ["1.0a1", "1.5", "2.0b1", "2.5"]
        cases = [
            (">=1.0a1", False),
            (">=1.0a1", True),
            ("~=2.0b1", True),
            ("<=2.0b1", False),
            ("===1.0a1", False),
            ("===1.0a1", True),
        ]
        for spec, pre in cases:
            ss = SpecifierSet(spec, prereleases=pre)
            r = ss.to_range()
            assert r._pre_region == ()
            assert list(r.filter(pool)) == list(ss.filter(pool)), (spec, pre)
            for v in pool:
                assert r.contains(v) == ss.contains(v), (spec, pre, v)


class TestUnionOverflowRegression:
    """Clipping the region to the bounds keeps a union or difference from
    force-admitting a pre-release no operand opted in (the leak that closed the
    PR #1304 attempt)."""

    def test_pr1304_union_example(self) -> None:
        # PR #1304's motivating example: the opt-in came only from ``>=2.0b1``,
        # so 1.5b1 is not force-admitted by the union.
        u = vr(">=1.0") | vr(">=2.0b1")
        assert list(u.filter(["1.0", "1.5b1", "2.0b1", "2.5"])) == [
            "1.0",
            "2.0b1",
            "2.5",
        ]

    def test_union_does_not_admit_out_of_bounds_prerelease(self) -> None:
        # Neither operand admits 3.6b1: ``>=3.5,<4`` has no opt-in and
        # ``>=2.0b1,<3`` opts in only below 3. Before clipping, the raw
        # [2.0b1, +inf) region rode the union past its own <3 cap onto 3.6b1.
        a, b = vr(">=3.5,<4"), vr(">=2.0b1,<3")
        assert list(a.filter(["3.6b1", "3.7"])) == ["3.7"]
        assert list(b.filter(["3.6b1", "3.7"])) == []
        assert list((a | b).filter(["3.6b1", "3.7"])) == ["3.7"]

    def test_difference_does_not_admit_out_of_bounds_prerelease(self) -> None:
        # The same overflow rides difference when the minuend carries it: the
        # [2.0b1, <3) opt-in must not reach 3.95a1 up in the [3.9, 4.0) interval.
        m = vr(">=2.0b1,<3") | vr(">=3.9,<4.0")
        assert list((m - vr(">=2,<3.9")).filter(["3.95a1", "3.97"])) == ["3.97"]


class TestDeliberateNonIdentities:
    """Laws that clip trades away, each with the canonical witness. These are
    negative locks: a future change that restores double complement (and, by
    T2, the union leak) flips them and fails here."""

    def test_absorption_keeps_inner_opt_in(self) -> None:
        # L7/L8: a & (a | b) and a | (a & b) keep b's opt-in inside a's bounds,
        # so they do not collapse back to a.
        a, b = vr(">=1.0"), vr(">=2.0b1")
        cand = ["2.5b1", "3.0"]
        assert a & (a | b) != a
        assert list((a & (a | b)).filter(cand)) == ["2.5b1", "3.0"]
        assert a | (a & b) != a
        assert list((a | (a & b)).filter(cand)) == ["2.5b1", "3.0"]
        assert list(a.filter(cand)) == ["3.0"]

    def test_union_does_not_distribute_over_intersection(self) -> None:
        # L10: a | (b & c) carries less opt-in than (a | b) & (a | c).
        a, b, c = vr(">=1.0"), vr(">=2.0b1,<3"), vr(">=3.5")
        lhs = a | (b & c)
        rhs = (a | b) & (a | c)
        assert lhs != rhs
        assert list(lhs.filter(["2.5b1", "2.6"])) == ["2.6"]
        assert list(rhs.filter(["2.5b1", "2.6"])) == ["2.5b1", "2.6"]

    def test_double_complement_is_erasure_not_identity(self) -> None:
        # L11: ~~b keeps b's versions but drops its opt-in, so it is not b.
        b = vr(">=2.0b1")
        assert ~~b != b
        assert (~~b)._pre_region == ()
        assert b._pre_region

    def test_excluded_middle_and_union_with_full_overshoot(self) -> None:
        # L16/L28: a | ~a and a | full() carry a's opt-in, which full() (with no
        # eager admission) does not, so neither equals full().
        b = vr(">=2.0b1")
        assert b | ~b != VersionRange.full()
        assert b | VersionRange.full() != VersionRange.full()

    def test_double_difference_sheds_opt_in(self) -> None:
        # L24: a - (a - b) drops b's opt-in (each difference is an exclusion),
        # while a & b keeps it.
        a, b = vr(">=1.0"), vr(">=2.0b1")
        assert a - (a - b) != a & b
        assert (a - (a - b))._pre_region == ()
        assert (a & b)._pre_region


class TestSetRelations:
    def test_disjoint_false(self) -> None:
        assert not vr(">=1.0,<2.0").is_disjoint(vr(">=1.5,<2.5"))

    def test_disjoint_higher_range_on_left(self) -> None:
        # The receiver sits entirely above the argument, including when the
        # argument spans several intervals.
        assert vr(">=2.0,<3.0").is_disjoint(vr(">=1.0,<1.5"))
        assert vr(">=5.0,<6.0").is_disjoint(vr(">=1.0,<2.0") | vr(">=3.0,<4.0"))

    def test_disjoint_shared_inclusive_endpoint(self) -> None:
        # ``[1, 2)`` and ``[2, 3)`` touch but share no version.
        assert vr(">=1.0,<2.0").is_disjoint(vr(">=2.0,<3.0"))
        # ``[1, 2]`` and ``[2, 3)`` both admit 2.0.
        assert not vr(">=1.0,<=2.0").is_disjoint(vr(">=2.0,<3.0"))

    def test_subset_true(self) -> None:
        assert vr(">=1.5,<1.8").is_subset(vr(">=1.0,<2.0"))

    def test_subset_false(self) -> None:
        assert not vr(">=1.0,<2.0").is_subset(vr(">=1.5,<1.8"))

    def test_subset_partial_overlap_false(self) -> None:
        assert not vr(">=1.0,<2.0").is_subset(vr(">=1.5,<2.5"))

    def test_subset_reflexive(self) -> None:
        r = vr(">=1.0,<2.0")
        assert r.is_subset(r)

    def test_empty_is_subset_of_everything(self) -> None:
        assert VersionRange.empty().is_subset(vr(">=1.0"))
        assert VersionRange.empty().is_subset(VersionRange.empty())
        assert VersionRange.empty().is_disjoint(vr(">=1.0"))

    def test_nonempty_not_subset_of_empty(self) -> None:
        assert not vr(">=1.0").is_subset(VersionRange.empty())

    def test_everything_is_subset_of_full(self) -> None:
        assert vr(">=1.0,<2.0").is_subset(VersionRange.full())

    def test_mutual_subset_despite_unequal_region(self) -> None:
        # Same bounds, different opt-in region: unequal but mutually subset.
        plain = vr(">=1.0")
        opted = vr(">=1.0") & vr(">0.5a1")
        assert plain != opted
        assert plain.is_subset(opted)
        assert opted.is_subset(plain)
        assert not plain.is_disjoint(opted)

    def test_subset_arbitrary_admission(self) -> None:
        # ``full()`` admits non-version strings, which no bounds cover, so it
        # is not a subset of the version-only full range.
        full = VersionRange.full()
        plain = VersionRange.full(admit_arbitrary=False)
        assert not full.is_subset(plain)
        assert plain.is_subset(full)
        assert full.is_subset(full)
        assert full.is_superset(plain)
        assert not plain.is_superset(full)

    def test_superset_mirrors_subset(self) -> None:
        outer, inner = vr(">=1.0,<2.0"), vr(">=1.5,<1.8")
        assert outer.is_superset(inner)
        assert not inner.is_superset(outer)
        assert outer.is_superset(inner) == inner.is_subset(outer)

    def test_multi_interval_subset(self) -> None:
        # ``!=1.5`` splits ``[1, 2)`` into two pieces, still inside ``[1, 2)``.
        gapped = vr(">=1.0,<2.0,!=1.5")
        whole = vr(">=1.0,<2.0")
        assert gapped.is_subset(whole)
        assert not whole.is_subset(gapped)
        assert not gapped.is_disjoint(whole)

    def test_disjoint_nonempty_excludes_subset(self) -> None:
        a, b = vr(">=1.0,<2.0"), vr(">=3.0,<4.0")
        assert a.is_disjoint(b)
        assert not a.is_subset(b)

    def test_literal_ranges_disjoint(self) -> None:
        assert vr("===a").is_disjoint(vr("===b"))
        assert not vr("===a").is_disjoint(vr("===a"))

    def test_literal_range_subset(self) -> None:
        # is_subset is ``self - other``, so a literal only ``self`` admits keeps
        # it from being a subset. ``self & ~other`` would miss this, since
        # complement is one-way for ``===`` literals.
        a = vr("===a")
        ab = vr("===a") | vr("===b")

        assert a.is_subset(ab)
        assert not ab.is_subset(a)

        assert ab.is_superset(a)
        assert not a.is_superset(ab)

    def test_full_arbitrary_matches_algebra(self) -> None:
        # ``full()`` carries the arbitrary-string flag, so it is not plain and
        # both relations take the non-plain path.
        f, b = VersionRange.full(), vr(">=1.0")

        assert not f.is_subset(b)
        assert b.is_subset(f)

        # Disjointness still mirrors the intersection algebra directly.
        assert f.is_disjoint(b) == (f & b).is_empty

    def test_prerelease_excluding_policy_matches_algebra(self) -> None:
        # ``prereleases=False`` ranges are not plain, so both relations take
        # the algebra fallback; pin concrete non-trivial answers there.
        inner = vr(">=1.2,<1.8", prereleases=False)
        outer = vr(">=1.0,<2.0", prereleases=False)
        far = vr(">=5.0,<6.0", prereleases=False)
        assert inner.is_subset(outer)
        assert not outer.is_subset(inner)
        assert inner.is_disjoint(far)
        assert not inner.is_disjoint(outer)
        for a, b in [(inner, outer), (outer, inner), (inner, far)]:
            assert a.is_subset(b) == (a & ~b).is_empty
            assert a.is_disjoint(b) == (a & b).is_empty

    def test_policy_mismatch_raises(self) -> None:
        with pytest.raises(ValueError, match="different"):
            vr(">=1.0", prereleases=True).is_subset(vr("<2.0", prereleases=False))
        with pytest.raises(ValueError, match="different"):
            vr(">=1.0", prereleases=True).is_disjoint(vr("<2.0", prereleases=False))
        with pytest.raises(ValueError, match="different"):
            vr(">=1.0", prereleases=True).is_superset(vr("<2.0", prereleases=False))

    def test_wrong_type_raises(self) -> None:
        with pytest.raises(TypeError, match="expected VersionRange"):
            vr(">=1.0").is_subset("x")  # type: ignore[arg-type]
        with pytest.raises(TypeError, match="expected VersionRange"):
            vr(">=1.0").is_disjoint("x")  # type: ignore[arg-type]
        with pytest.raises(TypeError, match="expected VersionRange"):
            vr(">=1.0").is_superset("x")  # type: ignore[arg-type]


class TestFilter:
    def test_filter_bounds(self) -> None:
        assert list(vr(">=1.0,<2.0").filter(["0.9", "1.5", "2.0"])) == ["1.5"]

    @pytest.mark.parametrize(
        ("dep", "constraint", "versions", "expected"),
        [
            ("==2.0.0b1", ">=1.0.0,<=3.0.0", ["1.0.0", "2.0.0b1"], ["2.0.0b1"]),
            (
                ">=2.0.0b1",
                ">=1.0.0,<=3.0.0",
                ["1.0.0", "2.0.0b1", "2.0.0b9"],
                ["2.0.0b1", "2.0.0b9"],
            ),
            (
                ">1.0.0,!=2.0.0b1,<2.0.0b5",
                ">=1.0.0,<=3.0.0",
                ["1.0.0", "2.0.0b1", "2.0.0b4", "2.0.0b5"],
                ["2.0.0b4"],
            ),
        ],
    )
    def test_intersected_requirement_keeps_opt_in(
        self, dep: str, constraint: str, versions: list[str], expected: list[str]
    ) -> None:
        # The opt-in survives intersection with a plain range; ``!=`` holes
        # clip it.
        assert list((vr(dep) & vr(constraint)).filter(versions)) == expected

    def test_narrowing_excludes_every_final_flushes_buffer(self) -> None:
        # The fallback is per filter call: narrowed past the last final, the
        # buffer flushes.
        wide = vr(">=1.0.0")
        pool = ["1.0.0", "1.5.0a1", "2.0.0b1"]
        assert list(wide.filter(pool)) == ["1.0.0"]
        narrowed = (
            wide & ~VersionRange.singleton("1.0.0") & ~VersionRange.singleton("2.0.0b1")
        )
        assert list(narrowed.filter(pool)) == ["1.5.0a1"]

    def test_flush_follows_in_place_yields(self) -> None:
        # Flushed pre-releases come after in-place yields: output is not
        # version-sorted.
        u = vr("~=1.0a1") | vr(">=2.5")
        assert list(u.filter(["2.6a1", "1.5a1"])) == ["1.5a1", "2.6a1"]

    def test_filter_prereleases_default_buffers(self) -> None:
        assert list(vr(">=1.0").filter(["1.3", "1.5a1"])) == ["1.3"]
        assert list(vr(">=1.0").filter(["1.5a1"])) == ["1.5a1"]

    def test_filter_prereleases_true(self) -> None:
        assert list(vr(">=1.0").filter(["1.3", "1.5a1"], prereleases=True)) == [
            "1.3",
            "1.5a1",
        ]

    def test_filter_prereleases_false(self) -> None:
        assert list(vr(">=1.0").filter(["1.3", "1.5a1"], prereleases=False)) == ["1.3"]

    def test_filter_autodetect_true(self) -> None:
        assert list(vr(">=1.0a1").filter(["1.0a1", "1.5"])) == ["1.0a1", "1.5"]

    def test_filter_key(self) -> None:
        items = [{"v": "1.0"}, {"v": "2.0"}]
        out = list(vr("<2.0").filter(items, key=lambda x: x["v"]))
        assert out == [{"v": "1.0"}]

    def test_filter_universal(self) -> None:
        assert list(VersionRange.full().filter(["1.3", "1.5a1"])) == ["1.3"]
        assert list(VersionRange.full().filter(["1.5a1"])) == ["1.5a1"]
        assert list(VersionRange.full().filter(["1.3"], prereleases=True)) == ["1.3"]
        assert list(VersionRange.full().filter(["1.5a1"], prereleases=False)) == []
        assert list(VersionRange.full().filter(["junk", "1.0"])) == ["junk", "1.0"]
        assert list(VersionRange.full().filter(["junk"])) == ["junk"]

    def test_filter_admission_modes(self) -> None:
        r = vr("===1.5a1")
        assert list(r.filter(["1.5a1"], prereleases=True)) == ["1.5a1"]
        assert list(r.filter(["1.5a1"], prereleases=False)) == []
        assert list(r.filter(["1.5a1"])) == ["1.5a1"]

    def test_filter_admission_with_final(self) -> None:
        r = VersionRange.full() & vr("===wat")
        # admit literal then a non-matching final
        assert list(r.filter(["wat", "1.0"])) == ["wat"]

    def test_filter_admission_reject(self) -> None:
        r = ~vr("===1.0")
        assert list(r.filter(["1.0", "2.0"])) == ["2.0"]


class TestContains:
    def test_contains_version_and_str(self) -> None:
        r = vr(">=1.0,<2.0")
        assert r.contains("1.5")
        assert r.contains(Version("1.5"))
        assert not r.contains("2.0")

    def test_contains_prereleases_false(self) -> None:
        assert not vr(">=1.0").contains("1.5a1", prereleases=False)
        assert vr(">=1.0").contains("1.5a1", prereleases=True)

    def test_contains_installed(self) -> None:
        r = vr(">=1.0", prereleases=False)
        assert r.contains("1.5a1", installed=True)
        assert r.contains(Version("1.5a1"), installed=True)
        assert r.contains("1.5", installed=True)

    def test_contains_arbitrary_literal(self) -> None:
        r = vr("===wat")
        assert r.contains("wat")
        assert r.contains("WAT")  # case-insensitive
        assert not r.contains("other")

    def test_contains_literal_prerelease_excluded(self) -> None:
        r = vr("===1.0a1", prereleases=False)
        assert not r.contains("1.0a1")

    def test_contains_literal_prerelease_autodetect(self) -> None:
        r = vr("===1.0a1")
        assert r.contains("1.0a1")

    def test_contains_unparsable_non_full(self) -> None:
        assert not vr(">=1.0").contains("wat")

    def test_contains_unparsable_full(self) -> None:
        assert VersionRange.full().contains("wat")

    def test_contains_reject(self) -> None:
        r = ~vr("===1.0")
        assert not r.contains("1.0")
        assert r.contains("2.0")

    def test_contains_typeerror(self) -> None:
        with pytest.raises(TypeError, match="expected str or Version"):
            vr(">=1.0").contains(123)  # type: ignore[arg-type]


class TestEquality:
    def test_eq_and_hash(self) -> None:
        a = vr(">=1.0,<2.0")
        b = vr(">=1.0,<2.0")
        assert a == b
        assert hash(a) == hash(b)
        assert len({a, b}) == 1

    def test_eq_wrong_type(self) -> None:
        assert vr(">=1.0").__eq__("x") is NotImplemented
        assert vr(">=1.0") != "x"

    def test_neq_bounds(self) -> None:
        assert vr(">=1.0") != vr(">=2.0")

    @pytest.mark.parametrize(
        ("spec", "expected"),
        [
            (">=1.0,<2.0", ""),
            ("", ""),
            (">=2.0,<1.0", ""),
        ],
    )
    def test_repr(self, spec: str, expected: str) -> None:
        assert repr(SpecifierSet(spec).to_range()) == expected

    def test_repr_arbitrary_literal(self) -> None:
        assert repr(vr("===wat")) == ""

    def test_repr_reject(self) -> None:
        assert "\\" in repr(~vr("===1.0"))

    def test_repr_pre(self) -> None:
        assert "pre=False" in repr(vr(">=1.0", prereleases=False))

    def test_repr_boundary_kinds(self) -> None:
        assert "AFTER_LOCALS" in repr(vr("==1.0"))
        assert "AFTER_POSTS" in repr(vr(">1.0"))


class TestToSpecifierSet:
    @pytest.mark.parametrize(
        "spec",
        [
            ">=1.0,<2.0",
            "!=1.5",
            "==1.2.*",
            ">=1.0",
            "<2.0",
            ">1.0",
            "<=1.0",
            "~=1.4.2",
            "==1.0",
            "==1.0+local",
            "!=1.5+local",
            "",
            ">=1.0,<2.0,!=1.4,!=1.6",
            # Pre-release-bearing bounds that once failed to re-encode: a
            # ``.dev0`` lower, a post-release boundary, and a dev0 upper.
            ">=3.8.dev0,<3.14",
            ">3.8.post1",
            "<3.8.post1",
            ">=3.8,<3.14.dev0",
            # Family-base lowers recovered as ``>=P,!=P.*`` / ``!=P.*``.
            ">=3,!=3.*",
            ">=3.8,!=3.8.*",
            "!=0.*",
            "!=0.0.*",
            "!=0.dev0",
            # An AFTER_LOCALS(dev0) lower and a wildcard-chain + dev0-point gap.
            "!=3.8.dev0,==3.8.*",
            "!=3.9.dev0,!=3.8.*",
        ],
    )
    def test_roundtrip(self, spec: str) -> None:
        r = vr(spec)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_empty(self) -> None:
        assert str(vr(">=2.0,<1.0").to_specifier_set()) == "<0"

    def test_empty_range_recovers_as_canonical_empty(self) -> None:
        # An empty range carries no opt-in region under clipping, so an empty
        # range that named a pre-release (``>=1.0,<=1.0a1``) recovers as the
        # canonical ``<0`` (the same members: none).
        r = vr(">=1.0,<=1.0a1")
        assert r.is_empty
        assert r._pre_region == ()
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "<0"
        assert recovered.to_range().is_empty

    def test_full_arbitrary(self) -> None:
        assert str(SpecifierSet("").to_range().to_specifier_set()) == ""

    def test_full_no_arbitrary_none(self) -> None:
        # The only full-bounds spelling ``>=0.dev0`` opts pre-releases in
        # (whole-bounds region), but this range has an empty opt-in region, so
        # no candidate round-trips.
        assert VersionRange.full(admit_arbitrary=False).to_specifier_set() is None

    def test_full_bounds_partial_region_none(self) -> None:
        # ``>=1.0a1 | ~>=1.0a1`` widens to full bounds but keeps the opt-in
        # region ``[1.0a1, +inf)``. No single SpecifierSet pairs full bounds with
        # a partial region (a pre-release specifier also bounds the range), so it
        # has no single-set form.
        r = vr(">=1.0a1") | ~vr(">=1.0a1")
        assert r._bounds == VersionRange.full()._bounds
        assert r._pre_region
        assert r._pre_region != r._bounds
        assert r.to_specifier_set() is None

    def test_full_configured_false(self) -> None:
        # ">=0.dev0" (not ">=0"): the floor must stay so the recovered set still
        # admits 0.dev0 under a prereleases=True override, matching the range.
        r = VersionRange.full(admit_arbitrary=False, prereleases=False)
        assert str(r.to_specifier_set()) == ">=0.dev0"

    def test_arbitrary_literal(self) -> None:
        assert str(vr("===wat").to_specifier_set()) == "===wat"

    def test_multiple_arbitrary_none(self) -> None:
        assert (vr("===a") | vr("===b")).to_specifier_set() is None

    def test_arbitrary_literal_with_comma_none(self) -> None:
        # A ``===`` literal may hold a comma (its arbitrary version excludes only
        # whitespace, ``;`` and ``)``), which the set string splits on, so it has
        # no single specifier-set spelling. It must return ``None``, not raise.
        r = SpecifierSet([Specifier("===a,b")]).to_range()
        assert r.to_specifier_set() is None

    def test_bounds_plus_literal_none(self) -> None:
        r = VersionRange.singleton("1.0") | vr("===garbage")
        assert r.to_specifier_set() is None

    def test_singleton_none(self) -> None:
        assert VersionRange.singleton("1.5").to_specifier_set() is None

    def test_equals_singleton_recovers_as_equals(self) -> None:
        # ``[V, AFTER_LOCALS(V)]`` is the natural ``==V``, not ``>=V,<=V``.
        assert str(vr("==1.0").to_specifier_set()) == "==1.0"
        assert str(vr("==1!2.3").to_specifier_set()) == "==1!2.3"
        assert str(vr("==1.0.post1").to_specifier_set()) == "==1.0.post1"
        # A pre-release singleton keeps its opt-in and still compacts.
        assert str(vr("==1.0a1").to_specifier_set()) == "==1.0a1"
        # A local segment keeps the existing ``==V+local`` compaction.
        assert str(vr("==1.0+local").to_specifier_set()) == "==1.0+local"

    def test_false_policy_recovers_release_equivalent(self) -> None:
        # ``~(>=3.14)`` is ``(-inf, 3.14)``, whose exclusive final upper admits
        # 3.14's pre-releases at the bounds level. Under ``prereleases=False``
        # those are excluded, so it recovers as the terser release-equivalent
        # ``<3.14``; the recovered set accepts the same releases.
        r = ~vr(">=3.14", prereleases=False)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "<3.14"
        assert r._same_releases(recovered.to_range())
        # None / True keep pre-releases, so the tightening is not equivalent and
        # the exact ``!=3.14,<=3.14`` form stands.
        assert str((~vr(">=3.14")).to_specifier_set()) == "!=3.14,<=3.14"
        true_recovered = (~vr(">=3.14", prereleases=True)).to_specifier_set()
        assert str(true_recovered) == "!=3.14,<=3.14"

    def test_false_policy_no_tightening_when_unbounded_above(self) -> None:
        # ``~(==3.14+local)`` extends to +inf, so its last upper is not a final
        # exclusive bound; nothing is tightened and the exact ``!=`` form stands.
        r = ~vr("==3.14+local", prereleases=False)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=3.14+local"
        assert recovered.to_range() == r

    def test_false_policy_disjoint_union_stays_none(self) -> None:
        # A disjoint union under ``prereleases=False`` has no single-set form, the
        # same as under None/True. Tightening only the last (here pre-release dev0)
        # upper avoids snapping the inner ``5)`` into a ``.dev0`` gap, which would
        # otherwise fabricate a long ``!=5.*,...,!=999.*`` chain.
        r = vr("<=5,!=5", prereleases=False) | vr("==1000.*", prereleases=False)
        assert len(r._bounds) == 2
        assert r.to_specifier_set() is None

    def test_disjoint_none(self) -> None:
        # Two intervals split by a whole-interval gap (not a ``!=`` exclusion)
        # are a disjoint union, which has no single-set form.
        assert (vr(">=1,<2") | vr(">=4,<5")).to_specifier_set() is None

    def test_disjoint_wildcards_roundtrip(self) -> None:
        # ``==1.* | ==3.*`` is one span with an ``!=2.*`` hole: !=0.*,!=2.*,<4.
        r = vr("==1.*") | vr("==3.*")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r
        assert str(recovered) == "!=0.*,!=2.*,<4"

    def test_wide_wildcard_gap_none(self) -> None:
        # A far-apart wildcard union would decompose into one ``!=N.*`` per family
        # in the gap. Past ``_MAX_EXCLUSION_RUN`` that has no practical single-set
        # form, so it returns None instead of an unbounded chain.
        r = vr("==5.*") | vr("==1000000.*")
        assert len(r._bounds) == 2
        assert r.to_specifier_set() is None
        # The budget is the total across the recursion, so a chain that stays
        # narrow at the top level but widens (or deepens) below is bounded too.
        assert (vr("==5.*") | vr("==7.200.*")).to_specifier_set() is None
        wide = vr("==0.*") | vr("==" + ".".join(["99"] * 100) + ".*")
        assert wide.to_specifier_set() is None
        # Each level also costs at least one, so a deep run of zero-span levels
        # (a valid version with hundreds of trailing components) is bounded and
        # returns None rather than recursing past the interpreter's stack limit.
        deep = vr("==0.*") | vr("==1." + ".".join(["0"] * 400) + ".1.*")
        assert deep.to_specifier_set() is None

    def test_specifier_set_exclusion_cap_returns_none(self) -> None:
        # A plain specifier set that spells out a long exclusion run reaches the
        # same cap: past ``_MAX_EXCLUSION_RUN`` families the recovery gives up. So
        # a specifier-derived range can return None without any set algebra.
        def excl(n: int) -> str:
            return ",".join(f"!={k}.*" for k in range(1, n + 1))

        at_cap = SpecifierSet(excl(_MAX_EXCLUSION_RUN)).to_range()
        assert at_cap.to_specifier_set() is not None
        over_cap = SpecifierSet(excl(_MAX_EXCLUSION_RUN + 1)).to_range()
        assert over_cap.to_specifier_set() is None

    def test_wildcards_then_dev_run_share_cap(self) -> None:
        # A gap spelled by a ``!=P.*`` chain plus a trailing dev run charges
        # both against one budget, so the pair caps at ``_MAX_EXCLUSION_RUN``
        # total rather than getting a full cap each.
        run = _MAX_EXCLUSION_RUN // 2

        def spec(families: int) -> SpecifierSet:
            prefixes = [f"!={k}.*" for k in range(1, families + 1)]
            devs = [f"!={families + 1}.dev{d}" for d in range(run)]
            return SpecifierSet(",".join(prefixes + devs))

        at_cap = spec(_MAX_EXCLUSION_RUN - run).to_range()
        assert at_cap.to_specifier_set() is not None
        over_cap = spec(_MAX_EXCLUSION_RUN - run + 1).to_range()
        assert over_cap.to_specifier_set() is None

    def test_cross_epoch_dev_gap_none(self) -> None:
        # A dev-run gap whose family sits in another epoch is not a
        # wildcard-plus-run shape; the gap has no exclusion spelling and the
        # disjoint union has no single-set form.
        assert (vr("<1") | vr(">=1!0.dev1,!=1!0.dev1")).to_specifier_set() is None

    def test_recovery_caps_long_dev_runs(self) -> None:
        # A ``.dev`` run longer than ``_MAX_EXCLUSION_RUN`` also has no practical
        # single-set form. The bound encoders keep the terse ``>=V,!=V`` spelling
        # or return None rather than spell out a huge ``!=`` chain from a short
        # input. The four run sites, driven by an attacker-controlled dev number:
        dev = _MAX_EXCLUSION_RUN
        anchor = vr(f">=1.dev{dev},!=1.dev{dev}").to_specifier_set()
        assert str(anchor) == f"!=1.dev{dev},>=1.dev{dev}"
        assert (
            str(vr(f">=1!0.dev{dev},!=1!0.dev{dev},<1!1").to_specifier_set())
            == f"!=1!0.dev{dev},<1!1.dev0,>=1!0.dev{dev}"
        )
        assert (~vr(f">=1.0,<=1.0.post0.dev{dev}")).to_specifier_set() is None
        assert (~vr(f">=1.dev0,<=2.dev{dev}")).to_specifier_set() is None

    def test_reject_none(self) -> None:
        assert (~vr("===1.0")).to_specifier_set() is None

    def test_arbitrary_admitting_empty_none(self) -> None:
        # ``~vr("")`` is the empty set still tagged arbitrary-admitting. No
        # SpecifierSet reproduces that shape (the empty ``<0`` admits no
        # strings), so it returns None rather than the usual empty ``<0``.
        r = ~vr("")
        assert r.is_empty
        assert r.to_specifier_set() is None

    def test_complement_gt_none(self) -> None:
        # (-inf, AFTER_POSTS] inclusive upper has no specifier form.
        assert (~vr(">1.0")).to_specifier_set() is None

    def test_complement_closed_interval_none(self) -> None:
        # ~(>=2.3,<=2.7) is two disjoint intervals, NOT a single ``!=2.3``;
        # the gap spans the whole [2.3, 2.7] interval so there is no form.
        r = ~vr(">=2.3,<=2.7")
        assert r.to_specifier_set() is None
        assert Version("2.5") not in r
        assert Version("2.3") not in r
        assert Version("2.8") in r
        assert Version("2.0") in r

    def test_whole_region_recovers_with_floor(self) -> None:
        # Bounds ``[2.0, +inf)`` with the whole range opted in (inherited from the
        # ``>=1.0a1`` operand). Clean ``>=2.0`` alone carries no opt-in, so the
        # no-op ``>=0.dev0`` floor is added to force-admit the in-bounds pre-releases.
        r = vr(">=1.0a1") & vr(">=2.0")
        assert r._pre_region == r._bounds
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r
        assert str(recovered) == ">=0.dev0,>=2.0"

    def test_wildcard_with_exclusion(self) -> None:
        r = vr("==1.*") & ~vr("==1.5.*")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_explicit_policy_recovers(self) -> None:
        # An explicit configured policy carries onto the recovered set, so a
        # pre-release-naming range under ``prereleases=True`` still re-encodes.
        r = vr(">=1.0a1,>=2.0", prereleases=True)
        recovered = r.to_specifier_set()
        assert recovered is not None

    @pytest.mark.parametrize("prereleases", [None, True, False])
    def test_dev0_span_roundtrips_every_policy(self, prereleases: bool | None) -> None:
        # The reported regression: a ``.dev0`` lower with a wider-than-one-family
        # span (``>=3.8.dev0,<3.14``) re-encodes under every pre-release policy.
        r = vr(">=3.8.dev0,<3.14", prereleases=prereleases)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r
        assert str(recovered) == "<3.14.dev0,>=3.8.dev0"

    @pytest.mark.parametrize(
        ("spec", "expected"),
        [
            # Family-base ``.dev0`` lowers recover without a synthetic prerelease.
            (">=3,!=3.*", "!=3.*,>=3"),
            (">=3.8,!=3.8.*", "!=3.8.*,>=3.8"),
            # At the floor the ``>=P`` half is redundant.
            ("!=0.*", "!=0.*"),
            ("!=0.0.*", "!=0.0.*"),
            ("!=0.dev0", "!=0.dev0"),
            # Post-release boundary and dev0 upper keep their clean spellings.
            (">3.8.post1", ">3.8.post1"),
            ("<3.8.post1", "<3.8.post1"),
            # AFTER_LOCALS(dev0) lower, then a wildcard-chain + dev0-point gap.
            ("!=3.8.dev0,==3.8.*", "!=3.7.*,!=3.8.dev0,<3.9,>=3.7"),
            ("!=3.9.dev0,!=3.8.*", "!=3.8.*,!=3.9.dev0"),
        ],
    )
    def test_prerelease_free_recovery_spelling(self, spec: str, expected: str) -> None:
        # With an empty opt-in region the encoder must avoid a synthetic
        # ``.dev0`` so the recovered set opts no pre-release in either.
        recovered = vr(spec).to_specifier_set()
        assert recovered is not None
        assert str(recovered) == expected
        assert recovered.to_range() == vr(spec)

    def test_after_locals_final_lower_roundtrips(self) -> None:
        # ``~(<=1.0)`` is ``(AFTER_LOCALS(1.0), +inf)``; a final-version
        # AFTER_LOCALS lower has no clean family form, so it stays ``>=1.0,!=1.0``.
        r = ~vr("<=1.0")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=1.0,>=1.0"
        assert recovered.to_range() == r

    def test_literal_sibling_dev_recovers_bare(self) -> None:
        # ``>=3.8.dev0,===3.8`` intersects to the bare literal ``{3.8}`` (empty
        # bounds), which carries no opt-in region under clipping, so it recovers
        # as the plain ``===3.8`` with no restoring floor.
        r = vr(">=3.8.dev0,===3.8")
        assert r._admit == {"3.8"}
        assert r._pre_region == ()
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "===3.8"
        assert recovered.to_range() == r

    def test_epoch_base_dev0_lower_none(self) -> None:
        # ``[1!0.dev0, +inf)`` has no prerelease-free family form (``1!0`` cannot
        # decrement), and ``>=1!0.dev0`` would opt pre-releases in (a whole-bounds
        # region) that this range does not, so it returns None.
        r = ~vr("<1!0")
        assert not r.is_empty
        assert r.to_specifier_set() is None

    def test_after_locals_final_lower_recovers(self) -> None:
        # Canonicalization folds ``[3.8.post0.dev0, +inf)`` to
        # ``(AFTER_LOCALS(3.8), +inf)``. A final-release AFTER_LOCALS lower has
        # no clean ``>`` form, so it recovers as ``>=3.8,!=3.8``.
        r = ~vr("<3.8.post0")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=3.8,>=3.8"
        assert recovered.to_range() == r

    def test_undecomposable_chain_before_dev0_point_none(self) -> None:
        # The gap before ``AFTER_LOCALS(1.3.dev0)`` starts at ``1.2.3.dev0``,
        # whose wildcard chain to ``1.3.dev0`` is undecomposable, so the
        # combined chain + ``!=1.3.dev0`` gap has no form.
        r = ~vr(">=1.2.3.dev0,<=1.3.dev0")
        assert not r.is_empty
        assert r.to_specifier_set() is None

    @pytest.mark.parametrize(
        ("spec", "expected"),
        [
            # The epoch-zero family floor: 1!0.dev0 has no >=P,!=P.* spelling, so
            # within its family it recovers as ==1!0.* trimmed by the upper.
            ("==1!0.*,<=1!0", "<=1!0,==1!0.*"),
            ("==1!0.*,<1!0.5", "<1!0.5,==1!0.*"),
            ("==2!0.*,<=2!0", "<=2!0,==2!0.*"),
            ("==1!0.0.*,<=1!0.0", "<=1!0.0,==1!0.*"),
            # An AFTER_LOCALS(1!0.dev0) lower drops 1!0.dev0 from the family.
            ("!=1!0.dev0,==1!0.*", "!=1!0.dev0,==1!0.*"),
        ],
    )
    def test_epoch_zero_family_floor_roundtrips(self, spec: str, expected: str) -> None:
        recovered = vr(spec).to_specifier_set()
        assert recovered is not None
        assert str(recovered) == expected
        assert recovered.to_range() == vr(spec)

    def test_arbitrary_literal_recovers_bare(self) -> None:
        # ``{abc}`` (an arbitrary ``===`` string) carries no opt-in region under
        # clipping, so it recovers as the plain ``===abc``, with no restoring
        # floor to reject the non-version string.
        r = (vr("===abc") & vr(">=1.0a1")) | vr("===abc")
        assert "abc" in r
        assert r._pre_region == ()
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "===abc"
        assert recovered.to_range() == r

    def test_epoch_dev0_with_post_is_not_a_family_floor(self) -> None:
        # 1!0.post1.dev0 is an epoch-zero release with a post, not the family
        # floor, so it recovers through the post-release path, not ==1!0.*.
        r = ~vr("<1!0.post1")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == ">1!0.post0"
        assert recovered.to_range() == r

    def test_epoch_floor_unencodable_upper_none(self) -> None:
        # An epoch-floor lower inside its family, but the upper is an inclusive
        # AFTER_POSTS boundary with no specifier form.
        r = vr("==1!0.*") & ~vr(">1!0.5")
        assert not r.is_empty
        assert r.to_specifier_set() is None

    def test_adjacent_not_equal_chain_roundtrips(self) -> None:
        # Two adjacent exclusions (V and its immediate successor) share one gap
        # that recovers as the ``!=`` chain.
        r = vr("!=1.0,!=1.0.post0.dev0")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=1.0,!=1.0.post0.dev0"
        assert recovered.to_range() == r

    def test_long_not_equal_chain_roundtrips(self) -> None:
        # Three adjacent exclusions collapse to one gap spanning a dev run.
        r = vr(">=0.dev0,!=1.0,!=1.0.post0.dev0,!=1.0.post0.dev1")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_floor_dev_run_roundtrips(self) -> None:
        # ``!=0.dev0,!=0.dev1`` excludes the two least versions, leaving the lone
        # ``(AFTER_LOCALS(0.dev1), +inf)`` interval, which recovers the floor run.
        r = vr("!=0.dev0,!=0.dev1")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=0.dev0,!=0.dev1"
        assert recovered.to_range() == r

    def test_after_posts_inclusive_upper_roundtrips(self) -> None:
        # ``<1.0a1.dev0`` folds to an inclusive ``AFTER_POSTS(1.0a0)]`` upper,
        # which recovers as ``<`` its least successor.
        r = vr("<1.0a1.dev0")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "<1.0a1.dev0"
        assert recovered.to_range() == r

    def test_final_after_posts_left_upper_none(self) -> None:
        # A two-interval range whose left interval ends at an inclusive final
        # ``AFTER_POSTS(1.0)]`` upper names no single point, so the gap is not a
        # ``!=`` chain and the disjoint union has no specifier form.
        r = ~vr(">1.0") | ~vr("<2.0")
        assert len(r._bounds) == 2
        assert r.to_specifier_set() is None

    def test_epoch_prerelease_singleton_no_opt_in_none(self) -> None:
        # ``~(!=1!0a0.dev0)`` holds just ``1!0a0.dev0`` and its locals, which
        # ``==1!0a0.dev0`` also spells, but that spelling opts the pre-release in
        # (whole-bounds region) while this range carries no opt-in, so None.
        r = ~vr("!=1!0a0.dev0")
        assert not r.is_empty
        assert r._pre_region == ()
        assert r.to_specifier_set() is None

    def test_leading_interval_post_dev_collapse_recovers(self) -> None:
        # Adjacent exclusions collapse into the leading interval's lower
        # (``(AFTER_LOCALS(1.0.post0.dev0), +inf)``). Anchoring at the
        # prerelease-free base 1.0 recovers ``>=1.0,!=1.0,!=1.0.post0.dev0``.
        r = vr(">=1.0,!=1.0,!=1.0.post0.dev0")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=1.0,!=1.0.post0.dev0,>=1.0"
        assert recovered.to_range() == r

    def test_release_base_dev_floor_recovers(self) -> None:
        # ``==1.0.*`` minus its two least dev releases leaves an
        # ``AFTER_LOCALS(1.0.dev1)`` lower, recovered via the ``!=0.*`` family
        # floor plus the dev run.
        r = vr("==1.0.*,!=1.0.dev0,!=1.0.dev1")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=0.*,!=1.0.dev0,!=1.0.dev1,<1.1"
        assert recovered.to_range() == r

    def test_epoch_floor_dev_run_recovers(self) -> None:
        # An epoch>0 zero-family floor with a leading dev run recovers as
        # ``==1!0.*`` plus the excluded dev releases.
        r = vr("==1!0.*,!=1!0.dev0,!=1!0.dev1")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=1!0.dev0,!=1!0.dev1,==1!0.*"
        assert recovered.to_range() == r

    def test_wildcard_then_adjacent_dev_run_roundtrips(self) -> None:
        # A wildcard exclusion abutting a dev run of length 2+ shares one gap:
        # the ``!=2.*`` family and then ``3.dev0,3.dev1`` in 3's own family.
        r = vr("!=2.*,!=3.dev0,!=3.dev1")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "!=2.*,!=3.dev0,!=3.dev1"
        assert recovered.to_range() == r

    def test_prerelease_dev_singleton_no_opt_in_none(self) -> None:
        # ``~(!=1.0a1.dev1)`` is the singleton ``{1.0a1.dev1}`` with no opt-in
        # region; every spelling of a pre-release singleton opts it in, so None.
        r = ~vr("!=1.0a1.dev1")
        assert not r.is_empty
        assert r._pre_region == ()
        assert r.to_specifier_set() is None

    def test_epoch_prerelease_floor_lower_declines_family_form(self) -> None:
        # An epoch>0 floor lower that names a pre-release (``1!0a0.dev0``) has no
        # ``==1!0.*`` family form, so the encoder falls back to the generic
        # ``>=,<`` spelling.
        r = vr(">=1!0a0.dev0,<1!5")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert str(recovered) == "<1!5,>=1!0a0.dev0"
        assert recovered.to_range() == r


# Boundary-sensitive specs and versions exercising the union / complement /
# empty-check / encoder edge branches deterministically.
_GRID_SPECS = [
    "",
    ">=1.0,<2.0",
    "!=1.5",
    "~=1.4.2",
    "==1.*",
    "==2.*",
    "==2.0.*",
    "==1.2.*",
    "==1.2.3.*",
    "!=1.0",
    "!=1.5.*",
    ">1.0.post1",
    "<=1.0.post2",
    "==1.0+local",
    "!=1.0+local",
    ">=1.0a1",
    "<1.0rc1",
    "==2!1.0",
    ">=2!1.0",
    "<2!1.0",
    ">=1.0.dev0",
    "!=1.0.dev0",
    "==1.0.dev0",
    "!=1.0a1",
    "<1.0",
    ">1.0",
    "===wat",
    "===1.0",
]

_GRID_VERSIONS = [
    "0.dev0",
    "0",
    "1.0.dev0",
    "1.0a1",
    "1.0rc1",
    "1.0",
    "1.0+local",
    "1.0.post0",
    "1.0.post1",
    "1.0.post2",
    "1.0.1",
    "1.2",
    "1.2.3",
    "1.4.2",
    "1.4.9",
    "1.5",
    "1.5.1",
    "1.6",
    "2.0.dev0",
    "2.0",
    "2!1.0",
    "3.0",
]


_GRID_RANGES = [SpecifierSet(s).to_range() for s in _GRID_SPECS]
_GRID_VERSION_OBJS = [Version(v) for v in _GRID_VERSIONS]


class TestAlgebraInvariants:
    """Membership invariants over an exhaustive small grid.

    Every range here is autodetect (configured policy None), so ``contains``
    on a :class:`Version` reduces to pure bounds membership and the set-algebra
    identities hold exactly.
    """

    def _same_versions(self, a: VersionRange, b: VersionRange) -> bool:
        return all((v in a) == (v in b) for v in _GRID_VERSION_OBJS)

    def test_complement_is_negation(self) -> None:
        for r in _GRID_RANGES:
            comp = ~r
            for v in _GRID_VERSION_OBJS:
                assert (v in comp) == (v not in r), (r, v)

    def test_double_complement_matches(self) -> None:
        # ``~~r`` matches the same versions as ``r``. It is structurally equal
        # for canonical ranges; the degenerate ``>=0.dev0`` canonicalizes to
        # the full range, which is version-equivalent.
        for r in _GRID_RANGES:
            assert self._same_versions(~~r, r), r

    def test_intersection_is_and(self) -> None:
        for a in _GRID_RANGES:
            for b in _GRID_RANGES:
                ab = a & b
                for v in _GRID_VERSION_OBJS:
                    assert (v in ab) == ((v in a) and (v in b)), (a, b, v)

    def test_union_is_or(self) -> None:
        for a in _GRID_RANGES:
            for b in _GRID_RANGES:
                ab = a | b
                for v in _GRID_VERSION_OBJS:
                    assert (v in ab) == ((v in a) or (v in b)), (a, b, v)

    def test_to_specifier_set_roundtrips(self) -> None:
        for r in _GRID_RANGES:
            recovered = r.to_specifier_set()
            if recovered is not None:
                assert self._same_versions(recovered.to_range(), r), r

    def test_complement_to_specifier_set_roundtrips(self) -> None:
        for r in _GRID_RANGES:
            comp = ~r
            recovered = comp.to_specifier_set()
            if recovered is not None:
                assert self._same_versions(recovered.to_range(), comp), comp

    def test_union_to_specifier_set_roundtrips(self) -> None:
        for a in _GRID_RANGES:
            for b in _GRID_RANGES:
                ab = a | b
                recovered = ab.to_specifier_set()
                if recovered is not None:
                    assert self._same_versions(recovered.to_range(), ab), ab


class TestSyntheticEmptyGaps:
    """Intervals that are ordered yet hold no real version.

    ``>V`` excludes V's post-releases (AFTER_POSTS) and ``<=V`` includes V's
    locals (AFTER_LOCALS), so a bound can sit just below the next real version.
    When the opposite bound lands on that successor, the interval is ordered but
    empty: ``>1.0a1`` admits nothing below ``1.0a2.dev0`` because every
    ``1.0a1.postN`` is excluded. The empty interval must be detected so that
    ``is_empty``, equality, and the set algebra stay correct.
    """

    @pytest.mark.parametrize(
        "spec",
        [
            ">1.0a1,<1.0a2.dev0",  # AFTER_POSTS pre-release, next pre-release
            ">1.0a0,<1.0a1.dev0",
            ">1.0b0,<1.0b1.dev0",
            ">1.0rc1,<1.0rc2.dev0",
            ">1!1.0a1,<1!1.0a2.dev0",  # epoch carried through
            ">1.0,<1.0.post0.dev0",  # AFTER_POSTS final, below its post0.dev0
        ],
    )
    def test_is_empty(self, spec: str) -> None:
        assert SpecifierSet(spec).to_range().is_empty

    @pytest.mark.parametrize(
        "spec",
        [
            ">1.0a2,<1.0b0.dev0",  # 1.0a3.dev0 sits between
            ">1.5,<2",  # 1.5.1.dev0 sits between
            ">1.0,<1.0.0.1",  # 1.0.0.0.1.dev0 sits between
            ">1.0a1,<1.0a2",  # 1.0a2.dev0 sits between
        ],
    )
    def test_not_empty(self, spec: str) -> None:
        assert not SpecifierSet(spec).to_range().is_empty

    def test_equal_substitutability(self) -> None:
        # Equality is substitutability: two synthetic-empty ranges match no
        # version, so they compare equal (both reduce to empty bounds).
        a = vr(">1.0a1,<1.0a2.dev0")
        b = vr(">1.0b0,<1.0b1.dev0")
        assert a == b
        assert hash(a) == hash(b)
        assert a._bounds == ()

    def test_subset_of_anything(self) -> None:
        # The PubGrub subset test ``(a & ~b).is_empty``: the empty set is a
        # subset of every range.
        empty = vr(">1.0a1,<1.0a2.dev0")
        assert (empty & ~vr(">=5.0")).is_empty

    @pytest.mark.parametrize(
        ("spec", "excluded"),
        [
            ("!=1.0,<1.0.post0.dev0", "1.0"),  # AFTER_LOCALS, post0 successor
            ("!=1.0.post3,<1.0.post4.dev0", "1.0.post3"),  # post(N+1) successor
            ("!=1.0.dev5,<1.0.dev6", "1.0.dev5"),  # dev(N+1) successor
        ],
    )
    def test_intersection_drops_embedded_empty(self, spec: str, excluded: str) -> None:
        # The empty AFTER_LOCALS interval must not survive in the bounds.
        r = SpecifierSet(spec).to_range()
        assert len(r._bounds) == 1
        assert not r.is_empty
        assert Version(excluded) not in r

    def test_complement_of_covering_union_is_empty(self) -> None:
        # ``~(>1.0a1)`` (everything up to and including 1.0a1's posts) and
        # ``>=1.0a2.dev0`` leave only the empty gap uncovered, so the union is
        # everything and its complement is empty.
        covering = ~vr(">1.0a1") | vr(">=1.0a2.dev0")
        assert covering._bounds == VersionRange.full()._bounds
        assert covering.complement().is_empty

    def test_double_complement_of_empty(self) -> None:
        r = vr(">1.0a1,<1.0a2.dev0")
        assert (~~r).is_empty


class TestBoundaryCanonicalization:
    """Different specifiers for the same set canonicalize to one form.

    ``>1.0a1`` excludes ``1.0a1``'s post-releases, so its smallest member is
    ``1.0a2.dev0``, exactly what ``>=1.0a2.dev0`` starts at. The two are the
    same set, so they fold to one boundary form and compare equal. The boundary
    (non-``.dev0``) form is canonical, so ``>=1.0a2.dev0`` adopts ``>1.0a1``'s.
    """

    @pytest.mark.parametrize(
        ("dev_form", "boundary_form"),
        [
            # Both operands are pre-releases, so the pair shares one pre-release
            # policy and equality reduces to the (identical) version set.
            (">=1.0a2.dev0", ">1.0a1"),  # AFTER_POSTS pre-release
            (">=1!1.0a2.dev0", ">1!1.0a1"),  # epoch carried through
            (">=1.0a1.post1.dev0", ">1.0a1.post0"),  # AFTER_LOCALS post(N+1)
            (">=1.0a1.dev6", ">1.0a1.dev5"),  # AFTER_LOCALS dev(N+1)
            (">=1.0.dev6", ">1.0.dev5"),  # AFTER_LOCALS dev on a final base
            (">=1.0a1.post1.dev6", ">1.0a1.post1.dev5"),  # AFTER_LOCALS post+dev
            (">=1.0.post0.dev1", ">1.0.post0.dev0"),  # post+dev on a final base
        ],
    )
    def test_equal_and_hash(self, dev_form: str, boundary_form: str) -> None:
        a, b = vr(dev_form), vr(boundary_form)
        assert a == b
        assert hash(a) == hash(b)
        assert a._bounds == b._bounds
        assert len({a, b}) == 1

    def test_upper_bound_folds_to_boundary(self) -> None:
        # The exclusive-upper mirror: ``<1.0a2.dev0`` ends at AFTER_POSTS(1.0a1).
        assert "1.0a1[AFTER_POSTS]" in repr(vr("<1.0a2.dev0"))

    def test_keeps_non_dev_anchor(self) -> None:
        # The boundary form is canonical, so the repr keeps the non-dev anchor.
        assert "1.0a1[AFTER_POSTS]" in repr(vr(">=1.0a2.dev0"))

    def test_prerelease_policy_keeps_them_distinct(self) -> None:
        # Same set, but ``<1.0.post0.dev0`` admits pre-releases by default and
        # ``<=1.0`` does not, so they are not substitutable and stay unequal.
        assert vr("<1.0.post0.dev0") != vr("<=1.0")

    def test_plain_version_is_not_folded(self) -> None:
        # ``1.0a2`` is not a boundary successor, so ``>=1.0a2`` stays plain.
        assert "1.0a2" in repr(vr(">=1.0a2"))
        assert "AFTER" not in repr(vr(">=1.0a2"))


class TestEmptyMatchesUnsatisfiable:
    """``is_empty`` agrees with ``SpecifierSet.is_unsatisfiable``.

    Both fold in the pre-release policy: a range whose only members are
    pre-releases is empty when the policy excludes them.
    """

    @pytest.mark.parametrize(
        "spec",
        [
            "==1.0a1",
            "===1.0a1",
            "==1.0a1,==1.0a1",
            "==0.dev0",  # floor: only member 0.dev0 is a pre-release
            "<0.dev1",  # floor: nothing below 0.dev1 but the pre-release 0.dev0
        ],
    )
    def test_prerelease_only_empty_when_policy_excludes(self, spec: str) -> None:
        assert vr(spec, prereleases=False).is_empty
        assert not vr(spec, prereleases=True).is_empty
        assert SpecifierSet(spec, prereleases=False).is_unsatisfiable()

    def test_non_prerelease_literal_survives(self) -> None:
        # ``===1.0`` admits a final release, so the policy does not empty it.
        assert not vr("===1.0", prereleases=False).is_empty

    @pytest.mark.parametrize(
        "spec", [">=1.0", ">=1.0a1.post0,<=1.0", ">=1.0.post0.dev0,<=1.0.post0"]
    )
    def test_non_prerelease_bounds_survive(self, spec: str) -> None:
        # A pre-release-with-post lower still admits the final/post release.
        assert not vr(spec, prereleases=False).is_empty

    def test_arbitrary_admission_is_not_empty(self) -> None:
        # The universal range admits any string regardless of policy.
        assert not vr("", prereleases=False).is_empty


class TestCoverageEdges:
    """Targeted cases for branches the grid does not reach."""

    def test_build_admit_and_reject(self) -> None:
        r = (vr("===a") | vr("===b")) & vr("===a")
        assert "a" in r
        assert "b" not in r

    def test_combine_literal_reject(self) -> None:
        # Version literals so the reject set survives _build against full bounds.
        r = (~vr("===1.0")) | vr("===2.0")
        assert Version("2.0") in r
        assert Version("1.5") in r
        assert Version("1.0") not in r

    def test_filter_literal_nonmatching_string(self) -> None:
        assert list(vr("===wat").filter(["other"])) == []

    def test_filter_admission_false_mixed(self) -> None:
        r = ~vr("===1.0")
        assert list(r.filter(["1.0", "2.0"], prereleases=False)) == ["2.0"]

    def test_filter_admission_arbitrary_after_final(self) -> None:
        r = vr(">=1.0") | vr("===wat")
        assert list(r.filter(["1.5", "wat"])) == ["1.5", "wat"]

    def test_filter_admission_prerelease_buffer(self) -> None:
        r = vr(">=1.0") | vr("===wat")
        assert list(r.filter(["1.5a1", "wat"])) == ["1.5a1", "wat"]

    def test_contains_literal_nonprerelease_false_policy(self) -> None:
        assert vr("===1.0", prereleases=False).contains("1.0")

    def test_multi_wildcard_adjacent_roundtrips(self) -> None:
        # ==2.0.* adjoins ==1.* (both touch 2.dev0), so the union is the single
        # contiguous span [1.dev0, 2.1.dev0), recovered as !=0.*,<2.1.
        r = vr("==1.*") | vr("==2.0.*")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r
        assert str(recovered) == "!=0.*,<2.1"

    def test_multi_wildcard_with_exclusion_roundtrips(self) -> None:
        # The span [1.dev0, 3.dev0) minus the 1.5 family is one set: !=0.*,!=1.5,<3.
        r = (vr("==1.*") | vr("==2.*")) & ~vr("==1.5")
        assert Version("1.5") not in r
        assert Version("1.4") in r
        assert Version("2.5") in r
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r
        assert str(recovered) == "!=0.*,!=1.5,<3"

    def test_multi_wildcard_wildcard_exclusion_roundtrips(self) -> None:
        # A ``==V.*`` outer with several ``!=P.*`` holes (including nested
        # ``1.0.1.*`` / ``1.3.1.*``) re-encodes to a single set.
        r = vr("==1.*,!=1.0.1.*,!=1.3.1.*,!=1.2.*")
        assert Version("1.0.0") in r
        assert Version("1.0.1") not in r
        assert Version("1.2.5") not in r
        assert Version("1.3.1") not in r
        assert Version("1.4") in r
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_not_equal_local_gap(self) -> None:
        r = vr("!=1.0+local")
        assert Version("1.0+local") not in r
        assert Version("1.0") in r
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_after_posts_boundary_total_order_consistent(self) -> None:
        # ``AFTER_POSTS(1.0)`` and ``AFTER_POSTS(1.0.post1)`` mark the same point
        # on the version line, so equality must agree with the ordering:
        # exactly one of ``<``, ``==``, ``>`` holds for any two boundaries.
        a = BoundaryVersion(Version("1.0"), BoundaryKind.AFTER_POSTS)
        b = BoundaryVersion(Version("1.0.post1"), BoundaryKind.AFTER_POSTS)
        assert a == b
        assert hash(a) == hash(b)
        assert (a < b) + (a == b) + (a > b) == 1

        # Distinct points stay unequal and strictly ordered, and the two kinds
        # at one version are different points.
        c = BoundaryVersion(Version("1.1"), BoundaryKind.AFTER_POSTS)
        assert a != c
        assert (a < c) ^ (a > c)
        assert a != BoundaryVersion(Version("1.0"), BoundaryKind.AFTER_LOCALS)

    def test_arbitrary_after_locals_dev(self) -> None:
        # !=1.0.dev0 produces an AFTER_LOCALS(1.0.dev0) boundary with a dev
        # inner version, exercising the dev successor path under complement.
        r = ~vr("!=1.0.dev0")
        assert Version("1.0.dev0") in r
        assert Version("1.1") not in r

    def test_encode_interval_undecomposable_dev0(self) -> None:
        # [1.2.dev0, 3.dev0): not a clean wildcard family, falls through to the
        # plain bounds encoding.
        r = vr(">=1.2.dev0,<3")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_wildcard_chain_cross_epoch_gap(self) -> None:
        # !=V.* gap between two different-epoch wildcard families.
        r = vr("==1!1.*") | vr("==2!1.*")
        assert Version("1!1.5") in r
        assert Version("2!1.5") in r
        assert r.to_specifier_set() is None

    def test_equal_wildcard_cross_epoch_interval(self) -> None:
        # A single interval spanning two epochs is not a wildcard family.
        r = vr(">=1!1.dev0,<2!1")
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_double_complement_min_boundary(self) -> None:
        # >=0.dev0 is already canonicalized to the full range at construction,
        # so ~~ round-trips it (full -> empty -> full).
        r = vr(">=0.dev0")
        comp2 = ~~r
        for v in ["0.dev0", "0", "1.0", "2!1.0"]:
            assert (Version(v) in comp2) == (Version(v) in r)

    def test_configured_false_lower_keeps_dev0(self) -> None:
        # Under configured False the recovered set keeps the synthetic .dev0 so
        # it matches the range under a prereleases=True override (no stripping).
        r = ~vr("<1.5", prereleases=False)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r
        assert r.contains("1.5a1", prereleases=True) == recovered.contains(
            "1.5a1", prereleases=True
        )

    def test_configured_false_upper_keeps_dev0(self) -> None:
        r = ~vr(">1.0.post1", prereleases=False)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_sub_minimum_union(self) -> None:
        # Union touching the 0.dev0 floor exercises the sub-minimum empty check.
        r = vr("==0.dev0") | vr(">=1.0")
        assert Version("0.dev0") in r
        assert Version("1.0") in r
        assert Version("0.5") not in r

    def test_floor_exclusive_upper_is_empty(self) -> None:
        # ``<0.dev0`` excludes the smallest version: the canonical empty.
        r = vr("<0.dev0")
        assert r.is_empty
        assert r == VersionRange.empty()
        assert r._pre_region == ()

    def test_exact_equals_successor_interval_bounds(self) -> None:
        # ``==1.0`` and ``>=1.0,<1.0.post0.dev0`` share bounds; the dev
        # spelling carries an opt-in region, so they stay unequal.
        a, b = vr("==1.0"), vr(">=1.0,<1.0.post0.dev0")
        assert a._bounds == b._bounds
        assert a != b
        assert a._pre_region == ()
        assert b._pre_region != ()

    def test_lte_and_post_dev_upper_same_bounds(self) -> None:
        # ``<=1.0`` and ``<1.0.post0.dev0`` share bounds; only the opt-in
        # region tells them apart.
        a, b = vr("<=1.0"), vr("<1.0.post0.dev0")
        assert a._bounds == b._bounds
        assert list(a.filter(["1.0.dev1", "0.9"])) == ["0.9"]
        assert list(b.filter(["1.0.dev1", "0.9"])) == ["1.0.dev1", "0.9"]

    def test_strict_singleton_complement_no_form(self) -> None:
        # ~singleton has an exclusive plain-version lower with no specifier form.
        comp = ~VersionRange.singleton("1.0")
        assert Version("1.0") not in comp
        assert Version("2.0") in comp
        assert comp.to_specifier_set() is None

    def test_two_singletons_complement_no_form(self) -> None:
        # The strict-point gaps have no ``!=`` spelling (``!=1.0`` would also
        # drop 1.0's locals), so the three intervals cannot fuse.
        r = ~(VersionRange.singleton("1.0") | VersionRange.singleton("2.0"))
        assert Version("1.5") in r
        assert Version("1.0") not in r
        assert r.to_specifier_set() is None

    def test_configured_false_multi_bound_roundtrip(self) -> None:
        r = vr(">=1.5,<3", prereleases=False)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r

    def test_ge_floor_is_canonical_full(self) -> None:
        # >=0.dev0 admits every version, so its bounds canonicalize to the full
        # range (its complement is empty). It still carries an opt-in region from
        # its .dev0 bound, so it is not equal to the region-free full().
        r = vr(">=0.dev0")
        assert r._bounds == VersionRange.full()._bounds
        assert (~r).is_empty

    def test_ne_floor_drops_empty_leading_interval(self) -> None:
        # !=0.dev0's lower (-inf, 0.dev0) interval is empty (sub-floor) and is
        # dropped, leaving only the upper half.
        r = vr("!=0.dev0")
        assert Version("0.dev0") not in r
        assert Version("1.0") in r
        assert Version("0") in r

    def test_complement_singleton_floor(self) -> None:
        # ~singleton(0.dev0): the empty (-inf, 0.dev0) leading gap is dropped.
        r = ~VersionRange.singleton("0.dev0")
        assert not r.is_empty
        assert Version("0.dev0") not in r
        assert Version("1.0") in r
        assert r.to_specifier_set() is None

    def test_eq_ranges_filter_identically(self) -> None:
        # Two ranges with identical bounds but a different opt-in region must NOT
        # compare equal, so equal ranges always filter the same.
        autodetect_true = vr(">=1.0a1") & vr(">=2.0")  # opt-in region [1.0a1, inf)
        autodetect_none = vr(">=2.0")  # empty opt-in region
        assert autodetect_true._bounds == autodetect_none._bounds
        assert autodetect_true != autodetect_none
        assert hash(autodetect_true) != hash(autodetect_none)
        assert list(autodetect_true.filter(["2.0", "2.5a1"])) != list(
            autodetect_none.filter(["2.0", "2.5a1"])
        )

    def test_eq_full_region_mismatch(self) -> None:
        # Same bounds and arbitrary flag but a different opt-in region must stay
        # unequal, so the two never substitute for each other. ``>=0.dev0`` names
        # a pre-release across the whole line, so it carries a full opt-in region;
        # ``full(admit_arbitrary=False)`` carries none.
        b = vr(">=0.dev0")
        c = VersionRange.full(admit_arbitrary=False)
        assert b._bounds == c._bounds
        assert b._admit_arbitrary == c._admit_arbitrary
        assert b != c
        assert list(b.filter(["0.dev0", "1.0"])) != list(c.filter(["0.dev0", "1.0"]))

    def test_filter_universal_false_yields_final(self) -> None:
        assert list(
            VersionRange.full().filter(["1.0", "1.5a1"], prereleases=False)
        ) == ["1.0"]

    def test_filter_universal_unparsable_after_final(self) -> None:
        assert list(VersionRange.full().filter(["1.0", "junk"])) == ["1.0", "junk"]

    def test_complement_zero_singleton(self) -> None:
        r = ~vr("==0")
        assert Version("0") not in r
        assert Version("1.0") in r

    def test_complement_post_boundary(self) -> None:
        # AFTER_LOCALS boundary adjacent to its post successor.
        r = ~vr("==1.0") | vr("==1.0.post0")
        assert Version("1.0") not in r
        assert Version("1.0.post0") in r
        assert Version("2.0") in r

    def test_union_after_locals_successor_merge(self) -> None:
        # ==1.0 upper (AFTER_LOCALS) meets 1.0.post0.dev0: the empty gap merges.
        r = vr("==1.0") | vr(">=1.0.post0.dev0")
        assert Version("1.0") in r
        assert Version("1.0.post0") in r
        assert Version("0.9") not in r

    def test_filter_universal_two_finals(self) -> None:
        assert list(VersionRange.full().filter(["1.0", "2.0"])) == ["1.0", "2.0"]

    def test_filter_admission_true_skips_rejected(self) -> None:
        r = ~vr("===1.0")
        assert list(r.filter(["1.0", "2.0"], prereleases=True)) == ["2.0"]

    def test_filter_admission_two_finals(self) -> None:
        r = vr(">=1.0") | vr("===wat")
        assert list(r.filter(["1.5", "2.5"])) == ["1.5", "2.5"]

    def test_filter_admission_prerelease_after_final(self) -> None:
        r = vr(">=1.0") | vr("===wat")
        assert list(r.filter(["1.5", "2.5a1"])) == ["1.5"]

    def test_configured_false_le_roundtrip(self) -> None:
        r = vr("<=1.0", prereleases=False)
        recovered = r.to_specifier_set()
        assert recovered is not None
        assert recovered.to_range() == r
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4577525
packaging-26.3/tests/test_requirements.py0000644000000000000000000010633515234171317015630 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"),
    # Trailing-zero-equivalent specifiers compare equal, so they must hash
    # equal too (regression guard for the __hash__/__eq__ invariant).
    ("foo==1.0.0", "foo==1.0.0.0"),
    ("foo>=1.0", "foo>=1.0.0"),
    # Canonical-specifier hashing must hold alongside extras + marker.
    (
        'foo[a]==1.0.0; python_version>="3.8"',
        'foo[a]==1.0.0.0; python_version>="3.8"',
    ),
    # Extras that normalize to the same value are equivalent.
    ("urllib3[secure]", "urllib3[SECURE]"),
    ("fishtank[all-blue]", "fishtank[all_blue]"),
    ("fishtank[all-blue]", "fishtank[all---blue]"),
    ("fishtank[crazy-bunches]", "fishtank[cRazy_BUnches]"),
]

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


def test_requirement_marker_with_embedded_double_quote_round_trips() -> None:
    req_string = 'demo; \'a" == os_name or python_version >= "0" or "b\' == os_name'
    req = Requirement(req_string)

    assert str(req) == req_string
    assert req.marker is not None
    assert req.marker.evaluate() is False
    round_tripped_marker = Requirement(str(req)).marker
    assert round_tripped_marker is not None
    assert round_tripped_marker.evaluate() is False


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

    @pytest.mark.parametrize("line_break", ["\n", "\r", "\r\n"])
    @pytest.mark.parametrize(
        "requirement",
        [
            "name>=1",
            'name; python_version >= "3"',
        ],
    )
    def test_error_when_suffixed_with_line_break(
        self, requirement: str, line_break: str
    ) -> None:
        with pytest.raises(InvalidRequirement):
            Requirement(requirement + line_break)

    @pytest.mark.parametrize("whitespace", [" ", "\t", " \t"])
    def test_trailing_horizontal_whitespace(self, whitespace: str) -> None:
        assert Requirement("name>=1" + whitespace) == Requirement("name>=1")

    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_specifier_set_rejects_parsed_specifier(self) -> None:
        # GIVEN
        to_parse = "demo===x,y"

        # WHEN
        with pytest.raises(InvalidRequirement, match="Invalid specifier: 'y'"):
            Requirement(to_parse)

    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_prefix_match_uses_post_release(self, operator: str) -> None:
        # GIVEN
        to_parse = f"name {operator} 1.2.3.post4.*"
        op_tilde = len(operator) * "~"

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

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            ".* suffix cannot be used with pre-release, post-release, "
            "dev or local versions\n"
            f"    name {operator} 1.2.3.post4.*\n"
            f"         {op_tilde}~~~~~~~~~~~~~^"
        )

    def test_error_when_prefix_match_uses_post_release_without_spaces(
        self,
    ) -> None:
        # GIVEN
        to_parse = "name==1.2.3.post4.*"

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

        # THEN
        assert ctx.exconly() == (
            "packaging.requirements.InvalidRequirement: "
            ".* suffix cannot be used with pre-release, post-release, "
            "dev or local versions\n"
            "    name==1.2.3.post4.*\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"
            "                   ^"
        )

    @pytest.mark.parametrize(
        ("to_parse", "expected"),
        [
            (
                'name; os_name == "C:\\"',
                "packaging.requirements.InvalidRequirement: Invalid quoted string\n"
                '    name; os_name == "C:\\"\n'
                "                     ~~~~~^",
            ),
            (
                r'name; os_name == "\x"',
                "packaging.requirements.InvalidRequirement: Invalid quoted string\n"
                r'    name; os_name == "\x"'
                "\n"
                "                     ~~~~^",
            ),
        ],
    )
    def test_error_invalid_marker_malformed_quoted_string(
        self, to_parse: str, expected: str
    ) -> None:
        # WHEN
        with pytest.raises(InvalidRequirement) as ctx:
            Requirement(to_parse)

        # THEN
        assert ctx.exconly() == expected

    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"


def test_requirement_slots() -> None:
    # Requirement defines __slots__, so instances have no __dict__ and reject
    # unknown attributes.
    r = Requirement("requests>=2.0")
    assert not hasattr(r, "__dict__")
    with pytest.raises(AttributeError):
        r.nonexistent = 1  # type: ignore[attr-defined]


@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)


@pytest.mark.parametrize("prereleases", [None, True, False])
def test_pickle_requirement_preserves_prereleases(prereleases: bool | None) -> None:
    # The specifier's explicit prereleases override is not captured by the
    # requirement string, so it must be preserved separately across a pickle
    # round trip.  See https://github.com/pypa/packaging/issues/1204.
    r = Requirement("foo>=1.0")
    r.specifier.prereleases = prereleases
    loaded = pickle.loads(pickle.dumps(r))
    assert loaded.specifier._prereleases == prereleases
    assert loaded == 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))


@pytest.mark.parametrize(
    "invalid_requirement",
    ["this is not a valid requirement", "demo===x,y"],
)
def test_pickle_requirement_setstate_rejects_invalid_string(
    invalid_requirement: str,
) -> None:
    # Cover the string branch where Requirement() raises InvalidRequirement.
    r = Requirement.__new__(Requirement)
    with pytest.raises(TypeError, match="Cannot restore Requirement"):
        r.__setstate__(invalid_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."
)


# Pickle bytes generated with packaging==26.1, Python 3.13.1, pickle protocol 2,
# for ``Requirement("requests>=2.0")`` after setting
# ``r.specifier.prereleases = True``.  Format: plain __dict__ (no __getstate__),
# with the override stored on the nested SpecifierSet.
_PACKAGING_26_1_PICKLE_REQUESTS_GE_2_0_PRERELEASES = (
    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\x00\x00"
    b"urlq\x05NX\x06\x00\x00\x00extrasq\x06c__builtin__\nset\nq\x07]q\x08\x85q"
    b"\tRq\nX\t\x00\x00\x00specifierq\x0bcpackaging.specifiers\nSpecifierSet\n"
    b"q\x0c)\x81q\rN}q\x0e(X\x0e\x00\x00\x00_canonicalizedq\x0f\x88X\x0e\x00"
    b"\x00\x00_has_arbitraryq\x10\x89X\x11\x00\x00\x00_is_unsatisfiableq\x11N"
    b"X\x0c\x00\x00\x00_prereleasesq\x12\x88X\r\x00\x00\x00_resolved_opsq\x13N"
    b"X\x06\x00\x00\x00_specsq\x14cpackaging.specifiers\nSpecifier\nq\x15)\x81"
    b"q\x16N}q\x17(h\x12NX\x07\x00\x00\x00_rangesq\x18NX\x05\x00\x00\x00_specq"
    b"\x19X\x02\x00\x00\x00>=q\x1aX\x03\x00\x00\x002.0q\x1b\x86q\x1cX\r\x00\x00"
    b"\x00_spec_versionq\x1dNX\x0f\x00\x00\x00_wildcard_splitq\x1eNu\x86q\x1f"
    b'b\x85q u\x86q!bX\x06\x00\x00\x00markerq"Nub.'
)


# Pickle bytes generated with packaging==26.2, Python 3.13.1, pickle protocol 2,
# for ``Requirement("requests>=2.0")`` after setting
# ``r.specifier.prereleases = True``.  Format: just the requirement string, so
# the override was already dropped at pickle time (the bug fixed in 26.3).
_PACKAGING_26_2_PICKLE_REQUESTS_GE_2_0_PRERELEASES = (
    b"\x80\x02cpackaging.requirements\nRequirement\nq\x00)\x81q\x01X\r\x00\x00"
    b"\x00requests>=2.0q\x02b."
)


# Pickle bytes generated with packaging==26.3, Python 3.13.1, pickle protocol 2,
# for ``Requirement("requests>=2.0")`` after setting
# ``r.specifier.prereleases = True``.  Format: (requirement string, prereleases).
_PACKAGING_26_3_PICKLE_REQUESTS_GE_2_0_PRERELEASES = (
    b"\x80\x02cpackaging.requirements\nRequirement\nq\x00)\x81q\x01X\r\x00\x00"
    b"\x00requests>=2.0q\x02\x88\x86q\x03b."
)


def test_pickle_requirement_old_format_preserves_prereleases() -> None:
    # A specifier prereleases override stored in a packaging <= 26.1 pickle
    # (plain __dict__) is preserved on load.
    r = pickle.loads(_PACKAGING_26_1_PICKLE_REQUESTS_GE_2_0_PRERELEASES)
    assert isinstance(r, Requirement)
    assert r == Requirement("requests>=2.0")
    assert r.specifier.prereleases is True


def test_pickle_requirement_26_2_format_loads() -> None:
    # A packaging 26.2 pickle uses the string-only format, which never stored
    # the prereleases override (the bug fixed in 26.3).  It must still load,
    # with prereleases defaulting back to None.
    r = pickle.loads(_PACKAGING_26_2_PICKLE_REQUESTS_GE_2_0_PRERELEASES)
    assert isinstance(r, Requirement)
    assert r == Requirement("requests>=2.0")
    assert r.specifier.prereleases is None


def test_pickle_requirement_new_format_preserves_prereleases() -> None:
    # A specifier prereleases override stored in a packaging 26.3+ pickle
    # ((requirement string, prereleases) tuple) is preserved on load.
    r = pickle.loads(_PACKAGING_26_3_PICKLE_REQUESTS_GE_2_0_PRERELEASES)
    assert isinstance(r, Requirement)
    assert r == Requirement("requests>=2.0")
    assert r.specifier.prereleases is True


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=1785787087.4587524
packaging-26.3/tests/test_specifiers.py0000644000000000000000000043545415234171317015250 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 InvalidVersion, 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.*",
            # Local segment with a non-ASCII letter that matches regex '[a-z]'
            # when re.IGNORECASE is in force and re.ASCII is not (issue #469)
            "==1.2+\u0130",
            "==1.2+\u0130\u0131\u017fK",
        ],
    )
    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"),
        list(
            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"),
        list(
            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)
        # The range conversion must answer membership identically.
        version_range = SpecifierSet(spec_str, prereleases=True).to_range()

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

            assert version in version_range
            assert Version(version) in version_range
        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))

            assert version not in version_range
            assert Version(version) not in version_range

    @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
        # The ``===`` carve-out range answers via the literal match.
        version_range = SpecifierSet(spec_str, prereleases=True).to_range()
        assert (version in version_range) == 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)
            version_range = SpecifierSet(specifier).to_range()
        else:
            spec = Specifier(specifier, prereleases=specifier_prereleases)
            version_range = SpecifierSet(
                specifier, prereleases=specifier_prereleases
            ).to_range()

        if prereleases is None:
            result = list(spec.filter(input))
            range_result = list(version_range.filter(input))
        else:
            result = list(spec.filter(input, prereleases=prereleases))
            range_result = list(version_range.filter(input, prereleases=prereleases))

        assert result == expected
        # The range conversion must filter identically.
        assert range_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 cache the parsed base version once."""
        spec = Specifier(specifier, prereleases=True)

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

        # ``==1.0.*`` parses ``1.0`` for the range bounds; that
        # parsed base lands in the cache.
        assert spec._spec_version is not None
        assert spec._spec_version[0] == "1.0"

    @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)
        version_range = spec.to_range()

        if prereleases is None:
            result = list(spec.filter(input))
            range_result = list(version_range.filter(input))
        else:
            result = list(spec.filter(input, prereleases=prereleases))
            range_result = list(version_range.filter(input, prereleases=prereleases))

        assert result == expected
        # The range conversion must filter identically.
        assert range_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.parametrize(
        ("spec_str", "version", "expected"),
        [
            # ">V" excludes every post-release of V (PEP 440 exclusive ordered
            # comparison); intersecting with "!=V.postN" must not re-admit a
            # different post-release of V.
            (">1.0,!=1.0.post1", "1.0.post2", False),
            (">1.0,!=1.0.post1", "1.0.post2.dev3", False),
            (">1.0,!=1.0.post1", "1.0.post1", False),
            (">1.0,!=1.0.post1", "1.1", True),
            (">2.3,!=2.3.post1", "2.3.post2", False),
            (">1!1.0,!=1!1.0.post1", "1!1.0.post2", False),
        ],
    )
    def test_contains_post_release_boundary_intersection(
        self, spec_str: str, version: str, expected: bool
    ) -> None:
        ss = SpecifierSet(spec_str)
        assert ss.contains(version, prereleases=True) == expected
        # set membership must equal the conjunction of its member specifiers
        assert ss.contains(version, prereleases=True) == all(
            s.contains(version, prereleases=True) for s in ss
        )

    def test_filter_post_release_boundary_intersection(self) -> None:
        ss = SpecifierSet(">1.0,!=1.0.post1")
        result = list(ss.filter(["1.0.post2", "1.0.post3", "1.1"], prereleases=True))
        assert result == ["1.1"]

    @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"),
        list(
            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"),
        list(
            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(
        ("left", "right", "expected"),
        [
            (">2", ">1", True),
            (">1", ">2", False),
            (">=3.12,<3.13", ">=3.12", True),
            (">=3.12,<3.13", ">=3.11,<3.13", True),
            (">=3.12,<3.13", ">=3.12,<3.13", True),
            (">=3.12,<3.13", ">=3.12,<3.12.5", False),
            (">=2.0,<1.0", ">=3.12", True),
            ("", ">=3.12", False),
        ],
    )
    def test_is_subset(self, left: str, right: str, expected: bool) -> None:
        spec = SpecifierSet(left)
        other = SpecifierSet(right)

        assert spec.is_subset(other) is expected
        assert spec.is_subset(other) == spec.to_range().is_subset(other.to_range())

    @pytest.mark.parametrize(
        ("left", "right", "expected"),
        [
            (">1", ">2", True),
            (">2", ">1", False),
            (">=3.12", ">=3.12,<3.13", True),
            (">=3.11,<3.13", ">=3.12,<3.13", True),
            (">=3.12,<3.13", ">=3.12,<3.13", True),
            (">=3.12,<3.12.5", ">=3.12,<3.13", False),
            (">=3.12", ">=2.0,<1.0", True),
            (">=3.12", "", False),
        ],
    )
    def test_is_superset(self, left: str, right: str, expected: bool) -> None:
        spec = SpecifierSet(left)
        other = SpecifierSet(right)

        assert spec.is_superset(other) is expected
        assert spec.is_superset(other) == spec.to_range().is_superset(other.to_range())

    @pytest.mark.parametrize(
        ("left", "right", "expected"),
        [
            ("<3.12", ">=3.12", True),
            ("<3.12", ">=3.11", False),
            (">=3.12,<3.13", ">=3.13", True),
            (">=3.12,<3.13", "==3.12.1", False),
            (">=2.0,<1.0", ">=3.12", True),
            ("", ">=3.12", False),
        ],
    )
    def test_is_disjoint(self, left: str, right: str, expected: bool) -> None:
        spec = SpecifierSet(left)
        other = SpecifierSet(right)

        assert spec.is_disjoint(other) is expected
        assert spec.is_disjoint(other) == spec.to_range().is_disjoint(other.to_range())

    @pytest.mark.parametrize(
        "method",
        ["is_subset", "is_superset", "is_disjoint"],
    )
    def test_set_relations_raise_on_prerelease_policy_mismatch(
        self, method: str
    ) -> None:
        spec = SpecifierSet(">=1.0", prereleases=True)
        other = SpecifierSet(">=1.0", prereleases=False)

        with pytest.raises(ValueError, match="pre-release"):
            getattr(spec, method)(other)

    @pytest.mark.parametrize(
        "method",
        ["is_subset", "is_superset", "is_disjoint"],
    )
    def test_set_relations_require_specifierset(self, method: str) -> None:
        spec = SpecifierSet(">=1.0")

        with pytest.raises(TypeError, match="SpecifierSet"):
            getattr(spec, method)(">=1.0")

    @pytest.mark.parametrize(
        "method",
        ["is_subset", "is_superset", "is_disjoint"],
    )
    @pytest.mark.parametrize(
        ("left", "right"),
        [
            ("===1.0", "==1.0"),
            ("==1.0", "===1.0"),
            ("===foobar", ">=1.0"),
        ],
    )
    def test_set_relations_reject_arbitrary_equality(
        self, method: str, left: str, right: str
    ) -> None:
        spec = SpecifierSet(left)
        other = SpecifierSet(right)

        with pytest.raises(ValueError, match="==="):
            getattr(spec, method)(other)

    @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]] = [
        # Synthetic gaps: >V excludes V's post-releases, so the least version
        # >1.0a1 admits is 1.0a2.dev0, which <1.0a2.dev0 excludes (#1267).
        ">1.0a1,<1.0a2.dev0",
        ">1!1.0a1,<1!1.0a2.dev0",
        ">1.0b0,<1.0b1.dev0",
        ">1.0,<1.0.post0.dev0",
        # Floor: an exclusive upper at or below 0.dev0 strands an empty interval
        "!=0.dev0,<0.dev1",
        "!=0.dev0,<=0.dev0",
        # 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,>=0.5",
        "==1.0,!=0.5",
        "==1.0,<=2.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",
        # Lower bound below base.dev0: other-base versions survive
        ">=0,<1.0.post0,!=1.0",
        # =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",
        # Floor: only members are pre-releases (#1267)
        "<0.dev1",
        "<=0.dev0",
        "<0a1",
        # 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",
        # === forces range fallback in prerelease check
        "===1.0",
        # === 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",
        # Pre-release-with-post lower: the final release still satisfies (#1267)
        ">=1.0a1.post0,<=1.0",
        ">=1.0.post0.dev0,<=1.0.post0",
    ]

    @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()

    @pytest.mark.parametrize(
        "spec_str",
        [
            ">1.0,<=1.0.post1",
            ">1.0,<=1.0.post5",
            ">2.3,<=2.3.post1",
            ">1!1.0,<=1!1.0.post1",
        ],
    )
    def test_post_release_boundary_unsatisfiable(self, spec_str: str) -> None:
        # ">V" excludes every "V.postN", so ">V,<=V.postN" admits no version.
        ss = SpecifierSet(spec_str)
        assert ss.is_unsatisfiable(), f"Expected unsatisfiable: {spec_str!r}"

    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_canonicalization_keeps_range_cache(self) -> None:
        """Canonicalization must not discard the computed range cache.

        ``_canonical_specs`` only reorders and dedupes specs, which leaves
        the intersected ranges unchanged, so the expensive ``_ranges`` cache
        must survive a canonicalizing operation such as ``str()``.
        """
        ss = SpecifierSet(">=1.0,<2.0,!=1.5")
        # filter() builds and caches the intersected ranges, the same cache
        # the range path of contains() reuses.
        assert list(ss.filter(["1.2"])) == ["1.2"]
        assert ss._ranges is not None
        cached_ranges = ss._ranges
        # str() forces canonicalization (sort + dedup of the spec tuple).
        str(ss)
        # The range cache must still be present and unchanged.
        assert ss._ranges is cached_ranges
        # A subsequent contains() now reuses the surviving cache.
        assert ss.contains("1.2")
        assert ss._ranges is cached_ranges

    def test_canonicalization_keeps_unsatisfiable_cache(self) -> None:
        """Canonicalization must not discard the unsatisfiability cache."""
        ss = SpecifierSet(">=2.0,<1.0")
        assert ss.is_unsatisfiable()
        assert ss._is_unsatisfiable is True
        # Force canonicalization; the cached verdict must remain.
        str(ss)
        assert ss._is_unsatisfiable is True

    @pytest.mark.parametrize(
        ("spec", "versions"),
        [
            # Duplicate specifiers.
            (">=1.0,>=1.0,<2.0", ["0.5", "1.0", "1.5", "2.0", "2.5"]),
            # Unsorted order.
            ("<2.0,!=1.5,>=1.0", ["0.5", "1.0", "1.5", "1.9", "2.0"]),
            # != plus post-release edge cases.
            ("!=1.0,>=1.0", ["1.0", "1.0.post1", "1.1"]),
            (">1.0,!=1.0.post1", ["1.0", "1.0.post1", "1.0.post2", "1.1"]),
        ],
    )
    def test_contains_identical_across_canonicalization(
        self, spec: str, versions: list[str]
    ) -> None:
        """contains() results are stable before and after canonicalization."""
        before = {v: SpecifierSet(spec).contains(v) for v in versions}
        ss = SpecifierSet(spec)
        # Populate the range cache, then canonicalize via str().
        _ = {v: ss.contains(v) for v in versions}
        str(ss)
        after = {v: ss.contains(v) for v in versions}
        assert after == before

    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) == ">"
        assert repr(upper) == ""

        [(lower2, upper2)] = Specifier(">1.0")._to_ranges()
        assert (
            repr(lower2)
            == ", AFTER_POSTS)>"
        )
        assert repr(upper2) == ""

    def test_range_bounds_reject_foreign_comparison(self) -> None:
        # The bound classes only compare to their own kind; anything else
        # returns NotImplemented so Python falls back to identity.
        [(lower, upper)] = Specifier(">=1.0")._to_ranges()
        assert lower.__eq__(object()) is NotImplemented
        assert lower.__lt__(object()) is NotImplemented  # type: ignore[operator]
        assert upper.__eq__(object()) is NotImplemented
        assert upper.__lt__(object()) is NotImplemented  # type: ignore[operator]


@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 cached slots to their reset
    # values, regardless of what was cached before the call.
    s = Specifier("==1.*")
    # Warm up every cache slot.
    _ = s._to_ranges()  # populates _spec_version + _ranges
    assert s._spec_version is not None
    assert s._ranges is not None

    s.__setstate__((("==", "1.*"), None))

    assert s._spec_version is None
    assert s._ranges is None


def test_pickle_specifierset_setstate_clears_cache() -> None:
    # Verify that __setstate__ resets all cached slots, 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 + _ranges
    assert ss._is_unsatisfiable is not None
    assert ss._ranges is not None

    ss.__setstate__(((Specifier(">=3.0"), Specifier("<4.0")), None))

    assert ss._is_unsatisfiable is None
    assert ss._ranges 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


def test_filter_multirange_pep440_prerelease_after_final() -> None:
    """Multi-range PEP 440 path drops a prerelease that arrives after a final."""
    # `!=1.5` has two ranges: (-inf, 1.5) and (AFTER_LOCALS(1.5), +inf).
    ss = SpecifierSet("!=1.5")
    assert list(ss.filter(["1.4", "1.6a1"])) == ["1.4"]
    assert list(ss.filter(["1.6a1", "1.4"])) == ["1.4"]


@pytest.mark.parametrize(
    "spec",
    [
        ">0.5",
        ">=1.0",
        "<=2.0",
        "<3.0",
        "==1.5",
        "!=1.5",
        "==1.*",
        "!=1.0+local",
        "~=1.2.3",
        "===wat",
    ],
)
def test_specifier_construction_is_lazy(spec: str) -> None:
    s = Specifier(spec)
    assert s._spec_version is None
    assert s._ranges is None


@pytest.mark.parametrize(
    "spec",
    [
        "",
        ">=1.0",
        ">=1.0,<2.0",
        ">=3.8,!=3.9.*,!=3.10.0,!=3.10.1,~=3.10.2,<3.14,!=3.11.0",
        "===wat",
    ],
)
def test_specifierset_construction_is_lazy(spec: str) -> None:
    ss = SpecifierSet(spec)
    assert ss._is_unsatisfiable is None
    assert ss._ranges is None
    # Every inner Specifier must also be untouched.
    for inner in ss._specs:
        assert inner._spec_version is None
        assert inner._ranges is None


def test_specifier_filter_with_version_iterable_warms_then_reuses_cache() -> None:
    """filter() reuses warm _ranges and exercises the Version isinstance branch."""
    spec = Specifier(">=1.5")
    assert spec.contains(Version("2.0"))
    items = [Version("1.0"), Version("2.0"), Version("3.0")]
    assert list(spec.filter(items)) == [Version("2.0"), Version("3.0")]


@pytest.mark.parametrize(
    ("spec_str", "version_str", "expected"),
    [
        # >V (AFTER_POSTS): trimmed release longer than parsed.release
        (">1.2.3", "2", True),
        # !=V (AFTER_LOCALS upper-side): trimmed release longer than parsed
        ("!=1.2.3", "2", True),
        # <=V (AFTER_LOCALS upper): parsed > V cmpkey-wise but shorter release
        ("<=1.2.3", "2", False),
    ],
)
def test_boundary_closure_short_release(
    spec_str: str, version_str: str, expected: bool
) -> None:
    """Closures handle parsed versions whose release is shorter than the boundary's."""
    spec = Specifier(spec_str)
    version = Version(version_str)
    assert spec.contains(version) is expected
    # Also drive Specifier.filter directly: contains has a fast path that
    # bypasses the range closures for short releases, but filter does not.
    filtered = list(spec.filter([version], prereleases=True))
    assert (filtered == [version]) is expected


def test_filter_arbitrary_with_prereleases_false_skips_pre() -> None:
    """``===1.0a1`` with ``prereleases=False`` drops the pre-release."""
    spec = Specifier("===1.0a1")
    assert list(spec.filter(["1.0a1", "0.9"], prereleases=False)) == []


def test_filter_arbitrary_constructor_prereleases_false_skips_pre() -> None:
    """``Specifier('===1.0a1', prereleases=False)`` honors the constructor flag."""
    spec = Specifier("===1.0a1", prereleases=False)
    assert list(spec.filter(["1.0a1"])) == []
    assert spec.contains("1.0a1") is False


def test_filter_arbitrary_unparsable_uses_key() -> None:
    """``===`` filter with ``key=`` matches against the keyed value."""
    items = [{"v": "wat"}, {"v": "WAT"}, {"v": "else"}]
    spec = Specifier("===wat")
    assert list(spec.filter(items, key=lambda x: x["v"])) == [
        {"v": "wat"},
        {"v": "WAT"},
    ]


def test_filter_keyed_none_version_is_skipped() -> None:
    """Non-string keyed versions are skipped like other invalid versions."""
    items = [{"v": "1.0"}, {"v": None}, {"v": "2.0"}]
    spec = SpecifierSet(">=1")
    assert list(spec.filter(items, key=lambda x: x["v"])) == [  # type: ignore[index]
        {"v": "1.0"},
        {"v": "2.0"},
    ]


def test_filter_arbitrary_pep440_unparsable_buffer_flush() -> None:
    """``===wat`` flushes the unparsable buffer when no final ever lands."""
    # "wat" never parses, so no final can be reached for the literal
    # match. Two matching items both buffer and then flush at the end.
    spec = Specifier("===wat")
    assert list(spec.filter(["wat", "wat"])) == ["wat", "wat"]


def test_filter_arbitrary_pep440_pre_only() -> None:
    """``===1.0a1`` PEP 440 default: prerelease literal flushes without a final."""
    pre_spec = Specifier("===1.0a1")
    assert list(pre_spec.filter(["1.0a1"])) == ["1.0a1"]


def test_specifierset_contains_reads_cached_bounds() -> None:
    # ``filter`` populates the intersected bounds; ``contains`` then answers
    # from that cache rather than re-folding the specifiers. Poisoning the
    # cache with empty bounds (which match nothing) flips the answer, proving
    # ``contains`` reads ``_ranges`` instead of recomputing it.
    ss = SpecifierSet(">=1.0,!=1.5,<3.0")
    list(ss.filter([Version("2.0")]))
    assert ss._ranges is not None
    assert ss.contains("2.0") is True

    ss._ranges = ()
    assert ss.contains("2.0") is False


# Every shape ``SpecifierSet`` can take: each operator, wildcards, ``===``,
# epochs, pre/post/dev/local boundaries, multi-spec sets, and unsatisfiable
# sets. Used to prove ``to_range()`` preserves membership and filtering.
_EQUIV_SPECS = [
    "",
    ">=1.0",
    ">1.0",
    "<=1.0",
    "<1.0",
    "==1.0",
    "!=1.0",
    "~=1.4.2",
    "==1.2.*",
    "!=1.2.*",
    "==1.0+local",
    "!=1.0+local",
    ">=1.0a1",
    "<1.0rc1",
    ">2.0.post1",
    "<=1.0.post2",
    ">=1.0.dev1",
    "==2!1.0",
    ">=2!1.0,<2!2.0",
    "===foobar",
    "===1.0",
    ">=1.0,<2.0",
    ">=1.0,<2.0,!=1.5",
    "!=1.4,!=1.6",
    ">=1.0,<2.0,!=1.2.*",
    "==1.0,!=1.0",
    "<=1.0,!=1.0",
    ">=2.0,<1.0",
    "<0",
]

# Versions and arbitrary strings that stress every boundary the engine tracks.
_EQUIV_ITEMS = [
    "0.dev0",
    "1.0.dev1",
    "1.0a1",
    "1.0rc1",
    "1.0",
    "1.0+local",
    "1.0.post1",
    "1.0.post2",
    "1.0.post3",
    "1.0.1",
    "1.2",
    "1.2.3",
    "1.4.2",
    "1.4.9",
    "1.5",
    "1.6",
    "2.0",
    "2.0.dev1",
    "2!1.0",
    "1.0.0",
    "foobar",
    "garbage",
]


def _parse_or_none(value: str) -> Version | None:
    try:
        return Version(value)
    except InvalidVersion:
        return None


_EQUIV_VERSION_OBJS = [v for v in map(_parse_or_none, _EQUIV_ITEMS) if v is not None]


class TestSpecifierSetToRangeEquivalence:
    """``SpecifierSet.to_range()`` answers ``contains`` and ``filter``
    identically to the originating :class:`SpecifierSet` for every shape,
    item, and pre-release setting."""

    @pytest.mark.parametrize("spec_str", _EQUIV_SPECS)
    @pytest.mark.parametrize("configured", [None, True, False])
    def test_contains_equivalent(self, spec_str: str, configured: bool | None) -> None:
        spec_set = SpecifierSet(spec_str, prereleases=configured)
        version_range = spec_set.to_range()
        for item in _EQUIV_ITEMS:
            assert (item in spec_set) == (item in version_range), (spec_str, item)
            for prereleases in (None, True, False):
                for installed in (None, True, False):
                    assert spec_set.contains(
                        item, prereleases=prereleases, installed=installed
                    ) == version_range.contains(
                        item, prereleases=prereleases, installed=installed
                    ), (spec_str, item, prereleases, installed)

    @pytest.mark.parametrize("spec_str", _EQUIV_SPECS)
    @pytest.mark.parametrize("configured", [None, True, False])
    def test_filter_equivalent(self, spec_str: str, configured: bool | None) -> None:
        spec_set = SpecifierSet(spec_str, prereleases=configured)
        version_range = spec_set.to_range()
        for prereleases in (None, True, False):
            assert list(spec_set.filter(_EQUIV_ITEMS, prereleases=prereleases)) == list(
                version_range.filter(_EQUIV_ITEMS, prereleases=prereleases)
            ), (spec_str, prereleases)

    @pytest.mark.parametrize("spec_str", _EQUIV_SPECS)
    @pytest.mark.parametrize("configured", [None, True, False])
    def test_to_specifier_set_roundtrip_matches(
        self, spec_str: str, configured: bool | None
    ) -> None:
        # When to_specifier_set() returns a non-None set, that set matches the
        # same versions as the range. Under a None/True policy the recovery is an
        # exact round trip, so it matches under every prereleases/installed
        # override. A configured False policy admits no pre-releases, so its
        # recovery need only match the releases the policy leaves observable;
        # overrides that admit pre-releases (prereleases=True / installed=True)
        # reinterpret the range cross-policy, which is unsound (see
        # docs/ranges.rst), so they are checked only for the None/True policies.
        version_range = SpecifierSet(spec_str, prereleases=configured).to_range()
        recovered = version_range.to_specifier_set()
        if recovered is None:
            return
        exact = configured is not False
        pre_opts = (None, True, False) if exact else (None, False)
        inst_opts = (None, True, False) if exact else (None, False)
        for item in _EQUIV_ITEMS:
            for prereleases in pre_opts:
                for installed in inst_opts:
                    assert version_range.contains(
                        item, prereleases=prereleases, installed=installed
                    ) == recovered.contains(
                        item, prereleases=prereleases, installed=installed
                    ), (spec_str, configured, item, prereleases, installed)
        for prereleases in pre_opts:
            assert list(
                version_range.filter(_EQUIV_ITEMS, prereleases=prereleases)
            ) == list(recovered.filter(_EQUIV_ITEMS, prereleases=prereleases)), (
                spec_str,
                configured,
                prereleases,
            )

    @pytest.mark.parametrize("spec_str", _EQUIV_SPECS)
    def test_contains_equivalent_with_version_objects(self, spec_str: str) -> None:
        # The same equivalence holds when the item is a ``Version`` instance.
        spec_set = SpecifierSet(spec_str)
        version_range = spec_set.to_range()
        for version in _EQUIV_VERSION_OBJS:
            assert (version in spec_set) == (version in version_range), (
                spec_str,
                version,
            )
            assert spec_set.contains(version) == version_range.contains(version)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4587524
packaging-26.3/tests/test_tags.py0000644000000000000000000025413115234171317014041 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_limit_allows_exact_number_of_tags(self) -> None:
        expected = {tags.Tag("py2", "none", "any"), tags.Tag("py3", "none", "any")}
        given = tags.parse_tag("py2.py3-none-any", limit=2)
        assert given == expected

    def test_limit_raises_when_exceeded(self) -> None:
        with pytest.raises(tags.TooManyTagsError, match="would generate 2 tags"):
            tags.parse_tag("py2.py3-none-any", limit=1)

    def test_limit_counts_cartesian_product_entries(self) -> None:
        # "py3.py3" generates two entries, even though both collapse to the
        # same Tag in the returned frozenset.
        with pytest.raises(tags.TooManyTagsError, match="would generate 2 tags"):
            tags.parse_tag("py3.py3-none-any", limit=1)

    def test_limit_rejects_negative_value(self) -> None:
        with pytest.raises(ValueError, match="limit must be non-negative"):
            tags.parse_tag("py3-none-any", limit=-1)

    def test_limit_can_be_combined_with_validate_order(self) -> None:
        with pytest.raises(ValueError, match="not in sorted order"):
            tags.parse_tag("py3.py2-none-any", validate_order=True, limit=2)

    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

    @pytest.mark.parametrize(
        "tag",
        [
            "-none-any",  # Empty interpreter
            "py3--any",  # Empty ABI
            "py3-none-",  # Empty platform
            "py3.-none-any",  # Empty member of a compressed interpreter set
            "py3-none-any.",  # Empty member of a compressed platform set
            "--",  # All empty
        ],
    )
    def test_empty_component_raises(self, tag: str) -> None:
        with pytest.raises(tags.InvalidTag, match="empty component"):
            tags.parse_tag(tag)

    @pytest.mark.parametrize(
        "tag",
        [
            "2-none-any",
            "2.7.6-none-any",
            "py3.2-none-any",
            "py+3-none-any",
        ],
    )
    def test_invalid_interpreter_raises(self, tag: str) -> None:
        with pytest.raises(tags.InvalidTag, match="invalid interpreter"):
            tags.parse_tag(tag)

    @pytest.mark.parametrize("interpreter", ["sillywalk", "graalpy311", "_custom"])
    def test_identifier_interpreter_is_valid(self, interpreter: str) -> None:
        assert tags.parse_tag(f"{interpreter}-none-any") == {
            tags.Tag(interpreter, "none", "any")
        }

    @pytest.mark.parametrize(
        "tag",
        [
            "py3-none",
            "py3-none-any-extra",
        ],
    )
    def test_invalid_component_count_raises(self, tag: str) -> None:
        with pytest.raises(tags.InvalidTag, match="exactly three components"):
            tags.parse_tag(tag)


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", "fat3", "universal2", "universal"],
            ),
            (
                (10, 4),
                "x86_64",
                ["x86_64", "intel", "fat64", "fat3", "universal2", "universal"],
            ),
            ((10, 3), "x86_64", []),
            ((10, 15), "i386", ["i386", "intel", "fat3", "fat", "universal"]),
            ((10, 4), "i386", ["i386", "intel", "fat3", "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", "fat3", "fat", "universal"]),
            ((10, 0), "ppc", ["ppc", "fat3", "fat", "universal"]),
            ((11, 0), "riscv", ["riscv"]),
            (
                (11, 0),
                "x86_64",
                ["x86_64", "intel", "fat64", "fat3", "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_fat3",
            "macosx_10_5_universal2",
            "macosx_10_5_universal",
            "macosx_10_4_x86_64",
            "macosx_10_4_intel",
            "macosx_10_4_fat64",
            "macosx_10_4_fat3",
            "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

    def test_no_mac_ver_when_both_args_given(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # When both version and arch are explicitly provided, platform.mac_ver()
        # must not be called — it reads from the system and is irrelevant for
        # cross-targeting use cases.
        mac_ver_stub = pretend.call_recorder(
            pretend.raiser(AssertionError("platform.mac_ver() must not be called"))
        )
        monkeypatch.setattr(platform, "mac_ver", mac_ver_stub)
        list(tags.mac_platforms(version=(11, 0), arch="x86_64"))
        assert mac_ver_stub.calls == []


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


@pytest.fixture
def _disable_musl_detection(monkeypatch: pytest.MonkeyPatch) -> None:
    # The manylinux platform tests assert exact tag lists and do not expect
    # musllinux_* entries. On a musl host (e.g. Alpine), ``_get_musl_version()``
    # returns a real version and those tags leak into ``_linux_platforms()`` /
    # ``sys_tags()``, breaking the assertions. Neutralize musl detection by
    # default; tests that exercise musllinux re-patch ``_get_musl_version``.
    monkeypatch.setattr(tags._musllinux, "_get_musl_version", lambda _: None)  # type: ignore[attr-defined]


@pytest.mark.usefixtures("_disable_musl_detection")
class TestManylinuxPlatform:
    def teardown_method(self) -> None:
        # Clear the version and module caches
        tags._manylinux._get_glibc_version.cache_clear()  # type: ignore[attr-defined]
        tags._manylinux._get_manylinux_module.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 == [
            "linux_x86_64",
            "manylinux_2_5_x86_64",
            "manylinux1_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 = [
            "linux_x86_64",
            "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",
        ]
        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 = [
            "linux_" + arch,
            "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,
        ]
        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 = [f"linux_{arch}" for arch in archs]
        for arch in archs:
            expected.extend([f"manylinux_2_17_{arch}", f"manylinux2014_{arch}"])
        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 = [
            "linux_i686",
            "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",
        ]
        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 = (
            [
                "linux_aarch64",
                "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"]
        )
        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 = [f"linux_{arch}" for arch in archs]
        for arch in archs:
            expected.extend(
                f"musllinux_{musl_version[0]}_{minor}_{arch}"
                for minor in range(musl_version[1], -1, -1)
            )
        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, 15), ["cp315t", "abi3t"], ["platform"]))
        assert result == [
            tags.Tag("cp315", "cp315t", "platform"),
            tags.Tag("cp315", "abi3t", "platform"),
            tags.Tag("cp315", "none", "platform"),
        ] + [tags.Tag(f"cp3{minor}", "abi3t", "platform") for minor in range(14, 1, -1)]

        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)

    # ".cpython.so" has no version component at all (would raise IndexError);
    # ".cpython-.so" has a dash but an empty version (would build an invalid
    # "cp" ABI). Both are malformed cpython soabis that should surface the same
    # actionable SystemError as the other malformed EXT_SUFFIX cases.
    @pytest.mark.parametrize("ext_suffix", [".cpython.so", ".cpython-.so"])
    def test__generic_abi_cpython_missing_version(
        self, ext_suffix: str, 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 TestPurePythonTags:
    def test_python_version(self) -> None:
        result = list(tags.pure_python_tags((3, 3)))
        assert result == [
            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_major_only_python_version(self) -> None:
        assert list(tags.pure_python_tags((3,))) == [tags.Tag("py3", "none", "any")]

    def test_empty_python_version(self) -> None:
        with pytest.raises(ValueError, match="must contain at least one item"):
            list(tags.pure_python_tags(()))

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

    def test_does_not_query_platforms(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(
            tags,
            "platform_tags",
            lambda: pytest.fail("pure_python_tags() queried the running platform"),
        )
        assert list(tags.pure_python_tags((3,))) == [tags.Tag("py3", "none", "any")]


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"),
        ]


@pytest.mark.usefixtures("_disable_musl_detection")
class TestSysTags:
    def teardown_method(self) -> None:
        # Clear the version cache
        tags._glibc_version = []  # type: ignore[attr-defined]
        tags._manylinux._get_manylinux_module.cache_clear()  # 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

    def test_warn_forwarded_to_generic_tags(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        # On non-CPython interpreters ``generic_tags()`` is the primary tag
        # source, so ``sys_tags(warn=...)`` must forward the flag to it.
        class MockGenericTags:
            def __init__(self) -> None:
                self.warn: bool | None = None

            def __call__(
                self, *, warn: bool = False
            ) -> collections.abc.Iterator[tags.Tag]:
                self.warn = warn
                return iter(())

        mock_generic_tags = MockGenericTags()
        monkeypatch.setattr(tags, "interpreter_name", lambda: "generic")
        monkeypatch.setattr(tags, "generic_tags", mock_generic_tags)
        list(tags.sys_tags(warn=True))
        assert mock_generic_tags.warn

    @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 = [
            "linux_ppc64",
            "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
        ]
        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"linux_{machine}"]
        if tf:
            expected.append(f"manylinux_2_22_{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 = [
            "linux_x86_64",
            "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",
        ]
        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=1785787087.4587524
packaging-26.3/tests/test_utils.py0000644000000000000000000001714115234171317014241 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"),
        ("a--b", "a-b"),
        ("1--1", "1-1"),
    ],
)
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-2-py2.py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
            "foo",
            Version("2"),
            (),
            {
                Tag("py2", "none", "manylinux_2_17_x86_64"),
                Tag("py2", "none", "manylinux2014_x86_64"),
                Tag("py3", "none", "manylinux_2_17_x86_64"),
                Tag("py3", "none", "manylinux2014_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\n-1.0-py3-none-any.whl"),  # Invalid name (`\n`)
        ("foo#bar-1.0-py3-none-any.whl"),  # Invalid name (`#`)
        ("-1.0-py3-none-any.whl"),  # Empty project name
        ("-1.0-200-py3-none-any.whl"),  # Empty project name (with build number)
        ("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`)
        ("foo-1.0--none-any.whl"),  # Empty interpreter component
        ("foo-1.0-py3-none-.whl"),  # Empty platform component
        ("foo-1.0-py3.-none-any.whl"),  # Empty member in a compressed tag set
        ("playlyfe-0.1.1-2.7.6-none-any.whl"),  # Invalid interpreter components
    ],
)
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
        ("-1.0.tar.gz"),  # Empty project name
        ("-1.0.zip"),  # Empty project name (zip)
    ],
)
def test_parse_sdist_invalid_filename(filename: str) -> None:
    with pytest.raises(InvalidSdistFilename):
        parse_sdist_filename(filename)
././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1785787087.4587524
packaging-26.3/tests/test_version.py0000644000000000000000000014360715234171317014575 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,
    _TrimmedRelease,
    _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.parametrize("version", [None, 1, ["1", ".", "0"], ("1",), b"1.0"])
    def test_non_string_versions_raise_invalid_version(self, version: object) -> None:
        with pytest.raises(InvalidVersion):
            Version(version)  # type: ignore[arg-type]

    @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: tuple[str, int] | None) -> 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
        list(
            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
        list(
            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_gt_with_cached_other(self) -> None:
        """__gt__ fast path when other already has a cached key."""
        other = Version("1.0")
        # Warm other's key cache.
        _ = other < Version("2.0")
        # Fresh version on the left, cached one on the right.
        assert Version("2.0") > other

    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)


def test_from_parts_rejects_non_str_pre_letter() -> None:
    # A non-string pre letter must raise InvalidVersion rather than escaping
    # as an AttributeError from the normalization step.
    with pytest.raises(InvalidVersion, match="pre must be a tuple"):
        Version.from_parts(release=(1,), pre=(1, 1))  # type: ignore[arg-type]


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


def test_trimmed_release_hash_from_unhashed_version() -> None:
    # Regression test for GH-1239: hashing a _TrimmedRelease built from a fresh
    # Version must not raise AttributeError from the uncopied _hash_cache slot.
    v = Version("1.0")
    tr = _TrimmedRelease(v)
    assert hash(tr) == hash(v)


def test_trimmed_release_hash_from_prehashed_version() -> None:
    # Hashing a _TrimmedRelease built from a Version whose hash has already
    # been computed and cached must also work correctly.
    v = Version("1.0")
    _ = hash(v)  # Populate the hash cache on the source Version.
    tr = _TrimmedRelease(v)
    assert hash(tr) == hash(v)
packaging-26.3/PKG-INFO0000644000000000000000000000673000000000000011362 0ustar00Metadata-Version: 2.4
Name: packaging
Version: 26.3
Summary: Core utilities for Python packages
Author-email: Donald Stufft 
Requires-Python: >=3.9
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.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 :: 3.15
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/